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
<file_sep>import "./App.css"; import ProductList from "./components/ProductList"; import { BrowserRouter as Router, Link, Switch, Route, Redirect, } from "react-router-dom"; import { ConfirmProvider } from "material-ui-confirm"; function App() { return ( <ConfirmProvider> <Router> <div className="App"> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/products/new">Add new product</Link> </li> </ul> </nav> <Switch> <Route path="/products"> <ProductList /> </Route> <Route exact path="/"> <Redirect to="/products" /> </Route> </Switch> </div> </Router> </ConfirmProvider> ); } export default App; <file_sep>import { ErrorMessage, Field, Form, Formik } from "formik"; import * as Yup from 'yup'; const ProductSchema = Yup.object().shape({ title: Yup.string().required("Title is required!"), price: Yup.number().required("Price is required!").positive("Price must be positive"), image: Yup.string() }) export default function ProductForm({ onSubmit, initialValues }) { return ( <div> <Formik onSubmit={onSubmit} initialValues={initialValues} validationSchema={ProductSchema} enableReinitialize={true} > <Form> <Field name="title" placeholder="title"></Field> <ErrorMessage name="title" component="div"/> <Field name="price" placeholder="price"></Field> <ErrorMessage name="price" component="div"/> <Field name="description" placeholder="description"></Field> <Field name="image" placeholder="image"></Field> <ErrorMessage name="image" component="div"/> <Field name="category" placeholder="category"></Field> <button type="submit">Zatwierdź</button> </Form> </Formik> </div> ); }
fc8d9dfd72ffc464707a77520d3fa1cde38364df
[ "JavaScript" ]
2
JavaScript
mvksu/TodoApp
e260235b3d9d1ac8575a267c01e0d99bde9ff49d
5379db171254c29fffd17c5bf1b06fa557209f9b
refs/heads/master
<file_sep>#!/bin/bash #DATE,DAYTOTAL,LASTCONNECTTOTAL DATA=/mnt/usb/graph/measurement.txt IFACE=ppp0 HEADER="Date,CurrentTotal,SubTotal,DailyTotal" if [ -f /mnt/usb/USB_DISK_NOT_PRESENT ]; then exit -1 fi calculate() { DATE=$1 TOTAL=$2 PREVDATE=${3:-""} PREVTOTAL=${4:-0} LASTCT=${5:-0} if [ $PREVDATE == $DATE ];then if [ $PREVTOTAL -gt $TOTAL ]; then let LASTCT=$LASTCT+$PREVTOTAL fi else if [ $TOTAL -ge $PREVTOTAL ]; then let LASTCT=-$PREVTOTAL else LASTCT=0 fi fi let DAYTOTAL=$LASTCT+$TOTAL echo "$DATE,$TOTAL,$LASTCT,$DAYTOTAL" } test() { #echo "DATE: $1 TOTAL: $2 PREVDATE:$3 PREVTOTAL: $4 LASTCT: $5" #echo "DATE,TOTAL,LASTCT,DAYTOTAL" calculate $@ echo } log() { DEBUGDATE=`date` echo "$DEBUGDATE $*" >>$DATA.debug } if [ "$1" == "test" ];then shift test $@ exit 0 fi if ! ifconfig $IFACE &>/dev/null;then log "$IFACE Not found" exit 1 fi RX=`ifconfig $IFACE|grep 'TX bytes'|sed 's/.*RX bytes:\([0-9]*\).*/\1/'` TX=`ifconfig $IFACE|grep 'TX bytes'|sed 's/.*TX bytes:\([0-9]*\).*/\1/'` DATE=`date "+%Y-%m-%d"` if [ ! -w $DATA ];then echo $HEADER >$DATA fi PREV=`grep -v "$HEADER" $DATA|tail -1` let TOTAL=$RX+$TX LASTCT=0 PREVDATE=$DATE PREVTOTAL=0 if [ -n "$PREV" ]; then PREVDATE=`echo $PREV|awk -F, '{print $1}'` PREVTOTAL=`echo $PREV|awk -F, '{print $2}'` LASTCT=`echo $PREV|awk -F, '{print $3}'` fi CALCULATED=`calculate $DATE $TOTAL $PREVDATE $PREVTOTAL $LASTCT` log "$DATE $TOTAL $PREVDATE $PREVTOTAL $LASTCT $CALCULATED" grep -v "^$DATE" $DATA >$DATA.tmp echo $CALCULATED >>$DATA.tmp mv $DATA.tmp $DATA
bf3929ee8bf7438ef3a185fa5f8e8f3ecb95fc8d
[ "Shell" ]
1
Shell
dromie/measurement
4409351dc2570ca663d17203e025789f6f6e9af0
c4c555957e48d0cce384f096877aed838d3737ce
refs/heads/master
<file_sep>import processing.core.PImage; import java.util.List; import java.util.Optional; public class MinerNotFull extends MinerEntity { private int resourceCount; public MinerNotFull(String id, Point position, List<PImage> images, int resourceLimit, int resourceCount, int actionPeriod, int animationPeriod) { super(id, position, images, actionPeriod, animationPeriod, resourceLimit); this.resourceCount = resourceCount; } public void executeActivity(WorldModel world, ImageStore imageStore, EventScheduler scheduler) { Optional<Entity> notFullTarget = world.findNearest(getPosition(), Ore.class); if (!notFullTarget.isPresent() || !moveTo(world, notFullTarget.get(), scheduler) || !transform(world, scheduler, imageStore)) { scheduleEvent(scheduler, new Activity(this, world, imageStore), getActionPeriod()); } } public boolean transform(WorldModel world, EventScheduler scheduler, ImageStore imageStore) { if (resourceCount >= getResourceLimit()) { MovableEntity miner = new MinerFull(getId(), getPosition(), getImages(), getResourceLimit(), getActionPeriod(), getAnimationPeriod()); world.removeEntity(this); scheduler.unscheduleAllEvents(this); world.addEntity(miner); scheduler.scheduleActions(miner, world, imageStore); return true; } return false; } public void _moveToHelper(WorldModel world, Entity target, EventScheduler scheduler) { this.resourceCount += 1; world.removeEntity(target); scheduler.unscheduleAllEvents(target); } public int getResourceCount() { return resourceCount; } } <file_sep># CPE 203 Final Project "A virtual world with vein and ore and miners, oh my!" \- <NAME> "Instant classic" \- <NAME> "Wadu hek" \- <NAME> This is the final project for CPE 203 at Cal Poly with Professor Hatalsky. It was a quarter long project with five parts. 1. Move all static methods into classes that they fit better in. 2. Create interfaces for logical groupings of similar or identical code. 3. Create abstract classes for more connected and streamlined code, allowing for less repetition of code. 4. Create a pathing strategy using a strategy design pattern, and then implement the A* algorithm for pathing. 5. Modify the game to support a world-changing event on a mouse click, including a new entity and modified behavior of exisiting entities. This project was also my first experience in Java. <file_sep>import processing.core.PImage; import java.util.List; import java.util.Optional; public class Ore_Blob extends MovableEntity { private static final String QUAKE_KEY = "quake"; private static final String QUAKE_ID = "quake"; private static final int QUAKE_ACTION_PERIOD = 1100; private static final int QUAKE_ANIMATION_PERIOD = 100; private PathingStrategy strategy = new AStarPathingStrategy(); public Ore_Blob(String id, Point position, List<PImage> images, int actionPeriod, int animationPeriod) { super(id, position, images, actionPeriod, animationPeriod); } public void executeActivity(WorldModel world, ImageStore imageStore, EventScheduler scheduler) { Optional<Entity> blobTarget = world.findNearest(getPosition(), Vein.class); long nextPeriod = getActionPeriod(); if (blobTarget.isPresent()) { Point tgtPos = blobTarget.get().getPosition(); if (moveTo(world, blobTarget.get(), scheduler)) { AnimatedEntity quake = new Quake(QUAKE_ID, tgtPos, imageStore.getImageList(QUAKE_KEY), QUAKE_ACTION_PERIOD, QUAKE_ANIMATION_PERIOD); world.addEntity(quake); nextPeriod += getActionPeriod(); scheduler.scheduleActions(quake, world, imageStore); } } scheduleEvent(scheduler, new Activity(this, world, imageStore), nextPeriod); } public void _moveToHelper(WorldModel world, Entity target, EventScheduler scheduler) { world.removeEntity(target); scheduler.unscheduleAllEvents(target); } public Point nextPosition(WorldModel world, Point destPos) { List<Point> points; points = strategy.computePath(getPosition(), destPos, p -> world.withinBounds(p) && !world.isOccupied(p), Point::adjacent, PathingStrategy.CARDINAL_NEIGHBORS); if (points.size() != 0) return points.get(0); return getPosition(); } } <file_sep>import processing.core.PImage; import java.util.List; final class FrozenBlacksmith extends Entity { public FrozenBlacksmith(String id, Point position, List<PImage> images) { super(id, position, images); } }<file_sep>import java.util.function.BiPredicate; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import java.util.*; import java.util.stream.*; public class AStarPathingStrategy implements PathingStrategy { public List<Point> computePath(Point start, Point end, Predicate<Point> canPassThrough, BiPredicate<Point, Point> withinReach, Function<Point, Stream<Point>> potentialNeighbors) { List<Point> path = new LinkedList<>(); Comparator<MyNode> sorter = Comparator.comparing(MyNode::getF); PriorityQueue<MyNode> open = new PriorityQueue<>(sorter); Map<Point, MyNode> closed = new HashMap<>(); int initG = 0; int initH = getHeuristic(start, end); int initF = initG + initH; MyNode current = new MyNode(start, initG, initH, initF, null); open.add(current); while (open.size() > 0) { current = open.poll(); if (withinReach.test(current.getPos(), end)) { writePath(path, current); break; } closed.put(current.getPos(), current); List<Point> neighbors = potentialNeighbors .apply(current.getPos()) .filter(canPassThrough) .filter(p -> !closed.containsKey(p)) .collect(Collectors.toList()); for (Point neighbor : neighbors) { initG = current.getG() + 1; initH = getHeuristic(neighbor, end); initF = initH + initG; MyNode neigh = new MyNode(neighbor, initG, initH, initF, current); if (!open.contains(neigh)) //WRONG: need to see if it contains a node with that point. open.add(neigh); } } return path; } private void writePath(List<Point> path, MyNode node) { if (node.getPrior() == null) return; path.add(0, node.getPos()); if (node.getPrior().getPrior() != null){ writePath(path, node.getPrior()); } } private int getHeuristic(Point p1, Point p2) { return Math.abs((p1.getY() - p2.getY()) + (p1.getX() - p2.getX())); } private class MyNode { private Point position; private int g; private int h; private int f; private MyNode prior; public MyNode(Point position, int g, int h, int f, MyNode prior) { this.position = position; this.g = g; this.h = h; this.f = f; this.prior = prior; } public boolean equals(Object other) { if (other == null) { return false; } if (other.getClass() != getClass()) { return false; } return ((MyNode)other).position.equals(this.position); } public int getF() { return f; } public int getG() { return g; } public int getH() { return h; } public Point getPos() { return position; } public MyNode getPrior() { return prior; } } }
0e4b8e1d126f63396b5448a090fcd35c71debc44
[ "Markdown", "Java" ]
5
Java
mpgiii/CPE-203-Final-Project
7452e5ed04209ac1fd8d08f0306b70f4f6c524d8
f240dc32a9b9bc2278cc4f5046b6a3d15357f688
HEAD
<file_sep>import turtle turtle.speed (0) def drawCircle(x,y,r): turtle.pu() turtle.goto(x,y-r) turtle.pd() turtle.circle(r) def MakeCock (x,y,r): # rgbcol= "#"+str(x//16)+","str(y//16)+str(r//16) # turtle.colour = str(rgbcol) if r<30: drawCircle (x,y,r) else: drawCircle(x,y,r) MakeCock(x-r,y,r/2) MakeCock(x,y-r,r/2) MakeCock(x,y+r,r/2) MakeCock(x+r,y,r/2) MakeCock (x,y,r/3) MakeCock (0,0,200) <file_sep>class Fraction: """ class for fractions """ def __init__ (self,num,den): self.num = num self.den = den def __str__ (self,num,den): return (str(self.num) + "/" + str(self.den)) def div0check(n): if n == 0: raise ValueError("NOOOO WHAT HAVE YOU DONE") elif n < 0: raise ValueError("Come on it needs to be positive you fuck") else: return (den(n)) print (str(Fraction))
f97e940e46d73684ce31db27340092332b39f917
[ "Python" ]
2
Python
shinigamirei/python-work
468de13de2213957333a3ed4056f95f6a70aad70
8713d8d4df9bc5cc1857424a806bf2647a2af32f
refs/heads/master
<repo_name>raultelbisz/WordGame<file_sep>/prog6Undortelbi2.cpp /* prog6Undortelbi2.cpp AcrossWord with Undo is a 4x4 grid of letters that originally contains four four-letter words. The original configuration is then changed by two row and one column rotation, where the letters wrap around the ends. The user then has to solve the puzzle to get back the original four words. The extra credit has the computer solve the puzzle by itself, but is not implemented here. The Undo option has been added where a player can undo a move by entering 'u'. Author: <NAME> Program: #6, AcrossWord with Undo TA: Moumita Samanta, Mon 11 4/19/2017 Running the program looks like the following: Author: <NAME> Program: #6, AcrossWords with Undo TA: Moumita Samanta, Mon 11 April 19, 2017 Welcome to AcrossWord puzzle, where you rotate rows or columns to restore the board back to containing four words. Each move is a row or column letter followed by the rotation distance 1,2 or 3. When prompted to provide input you may enter: Enter 'r' to reset the board to user-defined values. Enter 'u' to undo a move. Enter 'o' for original board to be shown. Enter 'x' to exit the program. There are 500 4-letter words. E F G H ------- A| b u e h B| k n o w C| i v s l D| e k t o 1. Enter the row or column to be rotated, and a number 1..3: d1 E F G H ------- A| b u e h B| k n o w C| i v s l D| o e k t List: 2->1 2. Enter the row or column to be rotated, and a number 1..3: u You chose u to undo most recent move. * Undoing move * E F G H ------- A| b u e h B| k n o w C| i v s l D| e k t o List: 1 1. Enter the row or column to be rotated, and a number 1..3: u You chose u to undo most recent move. * Undoing move * Can't undo past the beginning of the game. Please try again E F G H ------- A| b u e h B| k n o w C| i v s l D| e k t o List: 1 1. Enter the row or column to be rotated, and a number 1..3: d1 E F G H ------- A| b u e h B| k n o w C| i v s l D| o e k t List: 2->1 2. Enter the row or column to be rotated, and a number 1..3: d1 E F G H ------- A| b u e h B| k n o w C| i v s l D| t o e k List: 3->2->1 3. Enter the row or column to be rotated, and a number 1..3: g2 E F G H ------- A| b u s h B| k n e w C| i v e l D| t o o k List: 4->3->2->1 4. Enter the row or column to be rotated, and a number 1..3: c1 E F G H ------- A| b u s h B| k n e w C| l i v e D| t o o k List: 5->4->3->2->1 You did it! Well done. Press any key to continue . . . */ #include <stdio.h> #include <string.h> #include <stdlib.h> // for the exit() command #include <iostream> #include <math.h> // for random() #include <time.h> // for srand( time(0) ) using namespace std; // Global constants const char SMALL_DICTIONARY_NAME[] = "smallDictionary.txt"; const int WORD_LENGTH = 4; // Minimum dictionary word size to be stored const int BOARD_SIZE = WORD_LENGTH * WORD_LENGTH; //-------------------------------------------------------------------------------- // Linked list which has the following: // Node structure to hold the current move number, // current board at the time of Node creation // and a pointer to the next Node. struct Node { int moveNumber; char board[BOARD_SIZE]; Node *pNext; }; // end of struct Node //-------------------------------------------------------------------------------- // Creates/Saves all values into a node, values saved are: // the current characters spanning the board and move Number void saveNode(Node *&pHead, char board[BOARD_SIZE], int moveNumber) { Node *pTemp = new Node; // Creating a pointer to a new node // Populating the board of the current Node with the current board for (int i = 0; i < BOARD_SIZE; i++) { pTemp->board[i] = board[i]; } pTemp->moveNumber = moveNumber; // Setting the move number of the node pTemp->pNext = pHead; // Setting the next pointer of the node back to the "head" node pHead = pTemp; // Making the head of the node point back to the temporary node } // end of saveNode() //-------------------------------------------------------------------------------- // Display the List of move numbers that have been made void displayList(Node *pHead) { printf("List: "); while (pHead != NULL) { cout << pHead->moveNumber; if (pHead->pNext != NULL) cout << "->"; pHead = pHead->pNext; } cout << endl; } // end of displayList() //-------------------------------------------------------------------------------- // Undo a Node, which in turn undoes a move. // The board is reupdated with the board saved in the previous node // and the last node created gets deleted to save new values // The move number also gets deducted void undoNode(Node *&pHead, char board[BOARD_SIZE], int &moveNumber) { // If the pointer is empty then we can't go back to a "non-existant" board // This is a safeguard against that if (pHead->pNext == NULL) { printf("Can't undo past the beginning of the game. Please try again\n"); return; } Node *pTemp = pHead; // Pointer points back to the sentinel head pHead = pHead->pNext; // "Resetting" the pointer delete(pTemp); // Deleting the old node pointer // Updating the board for (int i = 0; i < BOARD_SIZE; i++) { board[i] = pHead->board[i]; } moveNumber = pHead->moveNumber; // Changing the moveNumber as needed } // end of undoNode() //-------------------------------------------------------------------------------- // Display name and program information void displayIdentifyingInformation() { printf("\n"); printf("Author: <NAME> \n"); printf("Program: #6, AcrossWords with Undo \n"); printf("TA: <NAME>, Mon 11 \n"); printf("April 19, 2017 \n"); printf("\n"); }//end displayIdentifyingInformation() //-------------------------------------------------------------------------------- // Display instructions void displayInstructions() { printf("Welcome to AcrossWord puzzle, where you rotate rows or columns \n"); printf("to restore the board back to containing four words. Each move is \n"); printf("a row or column letter followed by the rotation distance 1,2 or 3.\n"); printf(" \n"); printf("When prompted to provide input you may enter: \n"); printf(" Enter 'r' to reset the board to user-defined values. \n"); printf(" Enter 'u' to undo a move. \n"); printf(" Enter 'o' for original board to be shown. \n"); printf(" Enter 'x' to exit the program. \n"); printf(" \n"); }//end displayInstructions() //--------------------------------------------------------------------------- // Read in dictionary. // First read through the dictionary once to count how many four-letter // words there are. Then dynamically allocate space for those words, // and re-read the dictionary, this time storing those words. // Note that the '&' is needed so that the new array address is // passed back as a reference parameter. void readInDictionary( char** &dictionary, // dictionary words int &numberOfWords) // number of words stored { FILE *pInputFile; // Pointer to input file char theWord[81]; // Used to read in each dictionary word int wordLength; // Set to be the length of each input word int dictionarySize; // User input sets this, which in turn determines which dictionary to open char dictionaryName[81]; // Will be set to the dictionary name corresponding to the dictionary size strcpy(dictionaryName, SMALL_DICTIONARY_NAME); // Read all dictionary words and count how many four-letter words there are pInputFile = fopen(dictionaryName, "r"); // Returns null if not found. Mode is "r" for read // Verify that file open worked if (pInputFile == NULL) { printf("File open failed. Ensure file is in the right location.\n"); printf("Exiting program...\n"); exit(-1); } // Keep repeating while input from the file yields a word while (fscanf(pInputFile, "%s", theWord) != EOF) { wordLength = (int)strlen(theWord); if (wordLength == WORD_LENGTH) { numberOfWords++; } } fclose(pInputFile); // Allocate space for the dictionary of only four-letter words dictionary = (char **)malloc(sizeof(char *) * numberOfWords); // For each array entry, allocate space for the word (C-string) to be stored there for (int i = 0; i < numberOfWords; i++) { // Extra character for the NULL dictionary[i] = (char *)malloc(sizeof(char) * (WORD_LENGTH + 1)); } // Now reread the input file, this time storing the four-letter words into dictionary pInputFile = fopen(dictionaryName, "r"); // Returns null if not found. Mode is "r" for read numberOfWords = 0; // reset, then use as index to count up // Keep repeating while input from the file yields a word while (fscanf(pInputFile, "%s", theWord) != EOF) { wordLength = (int)strlen(theWord); if (wordLength == WORD_LENGTH) { strcpy(dictionary[numberOfWords++], theWord); } } fclose(pInputFile); printf("There are %d %d-letter words. \n", numberOfWords, WORD_LENGTH); }//end readInDictionary() //-------------------------------------------------------------------------------- // Select four random words from the dictionary of 4-letter words and // place them on the board. void placeFourRandomWordsOnBoard( char **dictionary, // Array of all dictionary words int numberOfWords, // How many words there are in above dictionary char board[BOARD_SIZE]) // The board where words will be placed { srand(0); // Place words horizontally. If random number dictates vertical, we will rotate board // 90 degrees clockwise. for (int i = 0; i<WORD_LENGTH; i++) { // Find starting location for word to be placed int startingIndex = i * WORD_LENGTH; // Find the word to be placed int wordIndex = rand() % numberOfWords; // Copy the four word letters onto the board for (int j = 0; j<WORD_LENGTH; j++) { board[startingIndex + j] = dictionary[wordIndex][j]; } } }//end placeFourRandomWordsOnBoard() //-------------------------------------------------------------------------------- // Display the board, taking the 16 board characters and displaying them // in a 4x4 grid. void displayBoard(char board[]) { printf("\n"); printf(" E F G H\n"); printf(" -------\n"); for (int row = 0; row<WORD_LENGTH; row++) { printf(" %c| ", 'A' + row); for (int col = 0; col<WORD_LENGTH; col++) { // calculate actual board position int index = row * WORD_LENGTH + col; // display that board character printf("%c ", board[index]); } printf("\n"); } fflush(stdout); // flush the output buffer }//end displayBoard() //-------------------------------------------------------------------------------------- // Rotate the characters right "distance" number of times. Changes to the characters // are reflected back to the caller. void rotate(char &c1, char &c2, char &c3, char &c4, int distance) { char c; // Do a single rotation the determined number of times for (int i = 0; i<distance; i++) { c = c1; // store the first character so it is not overwritten and available at the end // do the single rotation c1 = c4; c4 = c3; c3 = c2; c2 = c; } } //-------------------------------------------------------------------------------------- // Prompt for a row (A..D) or column (E..H) and how many single rotations to make. // Extract those board letters, and make the rotation. // Board index positions for the rotations are: // // E F G H // ------------ // A| 0 1 2 3 // B| 4 5 6 7 // C| 8 9 10 11 // D|12 13 14 15 // void getCharactersAndMakeRotation(char board[BOARD_SIZE], char rowOrColumnToRotate, int rotateDistance) { // printf("Rotating row/col %c by %d\n", rowOrColumnToRotate, rotateDistance); // For debugging // Pull out the four board characters to be used in the rotation, and send them to actually do the rotation switch (toupper(rowOrColumnToRotate)) { case 'A': rotate(board[0], board[1], board[2], board[3], rotateDistance); break; case 'B': rotate(board[4], board[5], board[6], board[7], rotateDistance); break; case 'C': rotate(board[8], board[9], board[10], board[11], rotateDistance); break; case 'D': rotate(board[12], board[13], board[14], board[15], rotateDistance); break; case 'E': rotate(board[0], board[4], board[8], board[12], rotateDistance); break; case 'F': rotate(board[1], board[5], board[9], board[13], rotateDistance); break; case 'G': rotate(board[2], board[6], board[10], board[14], rotateDistance); break; case 'H': rotate(board[3], board[7], board[11], board[15], rotateDistance); break; default: // Sanity check, should never get called printf("Invalid row/col value of %c. Exiting program...\n", rowOrColumnToRotate); exit(-1); } }//end getCharactersAndMakeRotation() //-------------------------------------------------------------------------------------- // Make two row rotations and one column rotation, randomly choosing in which of the // three moves the column rotation is done. void makeBoardRotations(char board[BOARD_SIZE]) { srand(0); // Seed the random number generator with time(0) rather than just 0, // if you want different results each time // Generate the two row letters ('A'..'D') to be used char rowsToUse[2]; rowsToUse[0] = rand() % 4 + 'A'; // Add 0..3 to 'A', giving 'A'..'D' // Make sure the second one is a different row do { rowsToUse[1] = rand() % 4 + 'A'; // Add 0..3 to 'A', giving 'A'..'D' } while (rowsToUse[1] == rowsToUse[0]); // Create the array where those three values will be placed, with the column letter ('E'..'H') // being placed at random into one of the three positions char rowOrColumnToUse[3] = { ' ',' ',' ' }; rowOrColumnToUse[rand() % 3] = rand() % 4 + 'E'; // Add 0..3 to 'E', giving 'E'..'H' // Put the two row letters into the remaining empty spots int rowIndex = 0; for (int i = 0; i<3; i++) { if (rowOrColumnToUse[i] == ' ') { // Put the next row letter into this empty spot rowOrColumnToUse[i] = rowsToUse[rowIndex++]; } } // Now make the three rotations for (int i = 0; i<3; i++) { int rotateDistance = (rand() % 3 + 1); // We will rotate 1..3 times getCharactersAndMakeRotation(board, rowOrColumnToUse[i], rotateDistance); // displayBoard( board); // For debugging } } // end makeBoardRotations() //-------------------------------------------------------------------------------------- // Use binary search to look up the search word in the dictionary array, returning index // if found, -1 otherwise int binarySearch(const char searchWord[WORD_LENGTH + 1], // word to be looked up char *dictionary[], // the dictionary of words int numberOfWords) // number of dictionary words { int low, mid, high; // array indices for binary search int searchResult = -1; // Stores index of word if search succeeded, else -1 // Binary search for word low = 0; high = numberOfWords - 1; while (low <= high) { mid = (low + high) / 2; // searchResult negative value means word is to the left, positive value means // word is to the right, value of 0 means word was found searchResult = strcmp(searchWord, dictionary[mid]); if (searchResult == 0) { // Word IS in dictionary, so return the index where the word was found return mid; } else if (searchResult < 0) { high = mid - 1; // word should be located prior to mid location } else { low = mid + 1; // word should be located after mid location } } // Word was not found return -1; }//end binarySearch() //-------------------------------------------------------------------------------------- // Check the four row four-letter words. If all four are in the dictionary, then we're done. bool done(char board[BOARD_SIZE], char **dictionary, int numberOfWords) { bool allWordsAreFound = true; for (int i = 0; i<WORD_LENGTH; i++) { // Make a word out of the 4 letters char theWord[5]; theWord[0] = board[i*WORD_LENGTH + 0]; theWord[1] = board[i*WORD_LENGTH + 1]; theWord[2] = board[i*WORD_LENGTH + 2]; theWord[3] = board[i*WORD_LENGTH + 3]; theWord[4] = '\0'; // Null terminate each word // See if it is in the dictionary. If not, indicate all words are not found and return false if (binarySearch(theWord, dictionary, numberOfWords) == -1) { // word was not found. allWordsAreFound = false; // We're not done yet, since all words are not found break; } }//end for( int i.. return allWordsAreFound; // True when we're not done yet, false otherwise }// end done() //-------------------------------------------------------------------------------------- // Prompt the user for 16 board values and reset the board void resetBoard(char board[BOARD_SIZE]) { char userInput[81]; userInput[0] = '\0'; // Set the first character to NULL, so strlen will work // Validate user input as being the same size as the board while (strlen(userInput) != BOARD_SIZE) { printf("Enter %d char values to reset the board: ", BOARD_SIZE); scanf("%s", userInput); // validate length of user input if (strlen(userInput) != 16) { printf("Sorry, needed to provide exactly 16 characters of user input to reset the board. Please retry.\n"); } }//end while // User input length is correct. Copy over from user input into the board. for (int i = 0; i<BOARD_SIZE; i++) { board[i] = userInput[i]; } }//end resetBoard() //-------------------------------------------------------------------------------------- // main function int main() { // Declare the board char board[BOARD_SIZE]; // The boad of letters, that starts with 4 words on it char backupBoard[BOARD_SIZE]; // Used to make a copy of the board, to display when "cheat" selected char **dictionary; // Will store dynamically-allocated dictionary of words int numberOfWords = 0; // How many words of correct length are in the dictionary int moveNumber = 1; // Display move numbers as play progresses char rowOrColumn = ' '; // Will be 'A'..'H' char rotateDistance = ' '; // Should be '1'..'3', since '4' and above starts to repeat Node *pHead = NULL; // Display identifying information and instructions displayIdentifyingInformation(); displayInstructions(); // Seed the random number generator srand(0); // Use time(0) rather than 0 if you want to get a different board each time // Read each word in the large dictionary and count how many 4-letter words are there. readInDictionary(dictionary, numberOfWords); // Choose four words at random, and set them on the board. placeFourRandomWordsOnBoard(dictionary, numberOfWords, board); // Make a copy of the original board for (int i = 0; i<BOARD_SIZE; i++) { backupBoard[i] = board[i]; } // Make two rotations of a row and one rotation of a column makeBoardRotations(board); // Save a new Node with the current board saveNode(pHead, board, moveNumber); // display the board displayBoard(board); // Present the puzzle to the user to try and interactively solve while (!done(board, dictionary, numberOfWords)) { printf("%d. Enter the row or column to be rotated, and a number 1..3: ", moveNumber); scanf(" %c", &rowOrColumn); // Check for 'r' to reset, 'u' to undo, 'o' to cheat, or 'x' to exit if (rowOrColumn == 'x') { printf("You chose x to Exit...\n"); break; } else if (rowOrColumn == 'u') { printf("You chose u to undo most recent move.\n"); printf("* Undoing move *\n"); // Reverts to the previous node with the previous board undoNode(pHead, board, moveNumber); // Displays the new "older" board displayBoard(board); // Display the lis of moves displayList(pHead); continue; // continue back up to retru user input } else if (rowOrColumn == 'r') { printf("You chose 'r' to reset the board. \n"); resetBoard(board); displayBoard(board); continue; // continue back up to retry user input } else if (rowOrColumn == 'o') { // 'o' for 'originalboard' was chosen. Display the backup board printf("You chose 'o' for the original board to be shown. Here are the underlying words: \n"); displayBoard(backupBoard); printf("\n"); displayBoard(board); continue; // continue back up to retry user input } // Neither 'x','r','u', or 'o' were chosen, so go on to read the rotate distance scanf(" %c", &rotateDistance); // Make the rotation getCharactersAndMakeRotation(board, toupper(rowOrColumn), rotateDistance - '0'); // Display the board displayBoard(board); moveNumber++; // Update the move number saveNode(pHead, board, moveNumber); // save a new Node with updated board and moveNumber displayList(pHead); // Display the list of moves done printf("\n"); } // Display congratulatory message if solution was found if (done(board, dictionary, numberOfWords)) { printf("You did it! Well done. \n"); } system("pause"); printf("\nEnd of program. Exiting... \n"); return 0; }// end main() <file_sep>/prog5Wordsrtelbi2.cpp // AcrossWordsrtelbi2.cpp // // Author: <NAME> // Program: #5, AcrossWords // TA: Moum<NAME> // April 14, 2017 // // AcrossWords is a game where you rotate rows or columns // to restore the board back to containing four words. Each // move is a row or column letter followed by the rotation distance // 1,2,3. User may also select 'u' to unveil which words are hidden // on the board. // /* A runthrough of the program might look like: Author: <NAME> Program 5: AcrossWords TA: Moumita Samanta, Mo 11-12 April 10, 2017 Welcome to AcrossWord puzzle, where you rotate rows or columns to restore the board back to containing four words. Each move is a row or column letter followed by the rotation distance 1, 2 or 3. When prompted to provide input you may enter: Enter 'r' to reset the board to user - defined values. Enter 'u' to unveil the underlying words. Enter 'x' to exit the program. Which dictionary size do you want? (1 = small, 2 = medium, 3 = large): 1 There are 500 four letter words E F G H ------- A| n r d o B| l y a r C| o e w s D| m u c k 1. Enter the row or column to be rotated, and a number 1..3: r You chose 'r' to reset the board. Enter 16 char values to reset the board: eushtnewblivokko E F G H ------- A| e u s h B| t n e w C| b l i v D| o k k o 1. Enter the row or column to be rotated, and a number 1..3: d2 Rotating row/col D by 2 E F G H ------- A| e u s h B| t n e w C| b l i v D| k o o k 2. Enter the row or column to be rotated, and a number 1..3: e2 Rotating row/col E by 2 E F G H ------- A| b u s h B| k n e w C| e l i v D| t o o k 3. Enter the row or column to be rotated, and a number 1..3: c3 Rotating row/col C by 3 E F G H ------- A| b u s h B| k n e w C| l i v e D| t o o k Congratulations! You solved it! Press any key to continue . . . */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h> //----------------------------------------------------------------------------- // Display program information void displayInformation() { printf("Author: <NAME>\n"); printf("Program 5: AcrossWords\n"); printf("TA: Moumita Samanta, Mo 11-12\n"); printf("April 10, 2017\n"); printf("\n"); } // end of displayInformation() //----------------------------------------------------------------------------- // Display program instructions void displayInstructions() { printf("Welcome to AcrossWord puzzle, where you rotate rows or columns\n"); printf("to restore the board back to containing four words. Each move is \n"); printf("a row or column letter followed by the rotation distance 1, 2 or 3.\n"); printf("When prompted to provide input you may enter:\n"); printf(" Enter 'r' to reset the board to user - defined values.\n"); printf(" Enter 'u' to unveil the underlying words.\n"); printf(" Enter 'x' to exit the program.\n"); printf("\n"); printf("Which dictionary size do you want? (1 = small, 2 = medium, 3 = large): \n"); printf("\n"); } // end of displayInstructions() //----------------------------------------------------------------------------- // Read in a dictionary, of which 3 sizes exist: // dictionaryNumber: 1 - small ; 2 - medium ; 3 - large // // This function simply "reads" in the words, storing happens in a later function int readInDictionary(int dictionaryNumber) // specifies which dictionary to use { char tempWord[81]; // string which temporarily holds each and every word as it is scanned in int numberOfWords = 0; // counts the total number of words in dictionary int wordLength = 0; // placeholder for length of each word // (we are only looking to store 4-letter words) FILE *fDictionary; // File type for our dictionary if (dictionaryNumber == 1) { // small dictionary fDictionary = fopen("smallDictionary.txt", "r"); while (fscanf(fDictionary, "%s", tempWord) != EOF) { wordLength = strlen(tempWord); if (wordLength == 4) { // We are only checking for 4-letter words numberOfWords++; } } printf("There are %d four letter words\n", numberOfWords); fclose(fDictionary); } else if (dictionaryNumber == 2) { // medium dictionary fDictionary = fopen("mediumDictionary.txt", "r"); while (fscanf(fDictionary, "%s", tempWord) != EOF) { wordLength = strlen(tempWord); if (wordLength == 4) { numberOfWords++; } } printf("There are %d four letter words\n", numberOfWords); fclose(fDictionary); } else if (dictionaryNumber == 3) { // large dictionary fDictionary = fopen("largeDictionary.txt", "r"); while (fscanf(fDictionary, "%s", tempWord) != EOF) { wordLength = strlen(tempWord); if (wordLength == 4) { numberOfWords++; } } printf("There are %d four letter words\n", numberOfWords); fclose(fDictionary); } return numberOfWords; }// end of readinDictionary //----------------------------------------------------------------------------- // This opens the dictionary file again each number corresponding to a size: // dicitonaryNumber 1 - small; 2 - medium; 3 - large // The function then stores these words into a local array of pointers **dictionary // Once the words are stored locally, we can perform necessayr operations void storeWords(int dictionaryNumber, char **dictionary) { char tempWord[81]; // Temporary holds every word scanned in int wordLength = 0; // Needed to store only 4 letter words FILE *fDictionary; // Pointer to dictionary stored on user's drive int i = 0; // Placeholder for dictionary location if (dictionaryNumber == 1) { fDictionary = fopen("smallDictionary.txt", "r"); while (fscanf(fDictionary, "%s", tempWord) != EOF) { wordLength = strlen(tempWord); if (wordLength == 4) { strcpy(dictionary[i], tempWord); // copying each 4 letter word into our dictionary i++; // incrementing to the next word in the dictionary } } fclose(fDictionary); } else if (dictionaryNumber == 2) { fDictionary = fopen("mediumDictionary.txt", "r"); while (fscanf(fDictionary, "%s", tempWord) != EOF) { wordLength = strlen(tempWord); if (wordLength == 4) { strcpy(dictionary[i], tempWord); i++; } } fclose(fDictionary); } else if (dictionaryNumber == 3) { fDictionary = fopen("largeDictionary.txt", "r"); while (fscanf(fDictionary, "%s", tempWord) != EOF) { wordLength = strlen(tempWord); if (wordLength == 4) { strcpy(dictionary[i], tempWord); i++; } } fclose(fDictionary); } }// end of storeWords() //----------------------------------------------------------------------------- // Creates a local copy of the original board the user started the game with // This is to be used later with the 'unveil' option in which the user // Can choose to unveil the words on the original board. // Function used in conjunction with displayOriginalBoard() method void createOriginalBoard(char board[17], char originalBoard[17]) { for (int i = 0; i < 17; i++) { originalBoard[i] = board[i]; } } // end of CreateOriginalBoard() //----------------------------------------------------------------------------- // If the user selects the 'u' to unveil option, this method // Displays all the contents of the original words that the user // Started the game with, all in sensical order void displayOriginalBoard(char originalBoard[17]) { printf("\n"); printf(" E F G H \n"); printf(" ------- \n"); printf("A| %c %c %c %c \n", originalBoard[0], originalBoard[1], originalBoard[2], originalBoard[3]); printf("B| %c %c %c %c \n", originalBoard[4], originalBoard[5], originalBoard[6], originalBoard[7]); printf("C| %c %c %c %c \n", originalBoard[8], originalBoard[9], originalBoard[10], originalBoard[11]); printf("D| %c %c %c %c \n", originalBoard[12], originalBoard[13], originalBoard[14], originalBoard[15]); printf("\n"); } // end of displayOriginalBoard() //----------------------------------------------------------------------------- // Creates a board for which the user can play with, also scrambles the words // on the board. To present a challenge to the user, in having to solve it. // Argument **dictionary is our local dictionary which has all stored words // Board[17] will be the board that we create // numberOfWords is the number of Words that exist in the specified dictionary // originalBoard[17] is passed through so we may create a copy of the board for // use with the 'u' unveil option void createBoard( char **dictionary, char board[17], int numberOfWords, char originalBoard[17]) { srand((int)time(0)); // seeding our random number generator with the time int randomIndex; // random number we will use to select words for the board randomIndex = ((rand() % numberOfWords) + 1); // gives us a random value strcpy(board, dictionary[randomIndex]); // we copy this random value // to our board // Scrambling the letters of the board for (int i = 0; i < 3; i++) { randomIndex = ((rand() % numberOfWords) + 1); strcat(board, dictionary[randomIndex]); } // Creating an original copy of the board for use with the unveil option createOriginalBoard(board, originalBoard); } // end of createBoard() //----------------------------------------------------------------------------- // Shifts the positions of the letters on board based on an input of // A,B,C,D which coincide with rows or // E,F,G,H which coincide with columns. // The shift amount determines by how many "places" to shift letters over // This function also "wraps" the letters "around" the board void shiftLetters(char board[17], int firstSpot, // first location to be shifted int secondSpot, // second location to be shifted int thirdSpot, // third location to be shifted int fourthSpot, // fourth location to be shifted int shiftAmount) // number to be shifted by { char temporaryVariable0; // holds location of the first location on the board char temporaryVariable1; // holds location of the second location on the board char temporaryVariable2; // holds location of the third location on the board char temporaryVariable3; // holds location of the fourth location on the board // Saving all original chars in temporary variables temporaryVariable0 = board[firstSpot]; temporaryVariable1 = board[secondSpot]; temporaryVariable2 = board[thirdSpot]; temporaryVariable3 = board[fourthSpot]; if (shiftAmount == 1) { // shifts locations by 1 spot board[firstSpot] = temporaryVariable3; board[secondSpot] = temporaryVariable0; board[thirdSpot] = temporaryVariable1; board[fourthSpot] = temporaryVariable2; } else if (shiftAmount == 2) { // shifts locations by 2 spots board[firstSpot] = temporaryVariable2; board[secondSpot] = temporaryVariable3; board[thirdSpot] = temporaryVariable0; board[fourthSpot] = temporaryVariable1; } else if (shiftAmount == 3) { // shifts locations by 3 spots board[firstSpot] = temporaryVariable1; board[secondSpot] = temporaryVariable2; board[thirdSpot] = temporaryVariable3; board[fourthSpot] = temporaryVariable0; } } // end of shiftLetters() //----------------------------------------------------------------------------- // Moves all characters in a "row" on the board over by a number as specified // by shiftNum. This function only shifts rows in a horizontal direction. // columnOrRow will only call this function if it is an A,B,C, or D // which corresponds to a row call, to be shifted. void makeMoveRow(char columnOrRow, int shiftNum, char board[17]) { // columnOrRow dictates which row is to be shifted // shiftNum dictates by how much we are shifting // shiftLetters performs the shifting of all characters in the row // the arguments shiftLetters() indicate which locations on the board[] will shift // For example: Row A corresponds to locations 0, 1, 2, 3 // Row B corresponds to locations 4, 5, 6, 7 // Row C corresponds to locations 8, 9, 10, 11 // Row C corresponds to locations 12, 13, 14, 15 if (columnOrRow == 'A') { if (shiftNum == 1) { shiftLetters(board, 0, 1, 2, 3, 1); } else if (shiftNum == 2) { shiftLetters(board, 0, 1, 2, 3, 2); } else if (shiftNum == 3) { shiftLetters(board, 0, 1, 2, 3, 3); } } else if (columnOrRow == 'B') { if (shiftNum == 1) { shiftLetters(board, 4, 5, 6, 7, 1); } else if (shiftNum == 2) { shiftLetters(board, 4, 5, 6, 7, 2); } else if (shiftNum == 3) { shiftLetters(board, 4, 5, 6, 7, 3); } } else if (columnOrRow == 'C') { if (shiftNum == 1) { shiftLetters(board, 8, 9, 10, 11, 1); } else if (shiftNum == 2) { shiftLetters(board, 8, 9, 10, 11, 2); } else if (shiftNum == 3) { shiftLetters(board, 8, 9, 10, 11, 3); } } else if (columnOrRow == 'D') { if (shiftNum == 1) { shiftLetters(board, 12, 13, 14, 15, 1); } else if (shiftNum == 2) { shiftLetters(board, 12, 13, 14, 15, 2); } else if (shiftNum == 3) { shiftLetters(board, 12, 13, 14, 15, 3); } } } // end of makeMoveRow() //----------------------------------------------------------------------------- // Moves all characters in a column based on the input of columnOrRow // Values of which can only be E,F,G,H and shiftNum 1 .. 3 // The characters on the board are all shifted vertically, up to down // while wrapping the letters around the board. void makeMoveColumn(char columnOrRow, int shiftNum, char board[17]) { // columnOrRow dictates which column is to be shifted // shiftNum dictates by how much we are shifting // shiftLetters performs the shifting of all characters in the row // the arguments shiftLetters() indicate which locations on the board[] will shift // For example: Col E corresponds to locations 0, 4, 8, 12 // Col F corresponds to locations 1, 5, 9, 13 // Col G corresponds to locations 2, 6, 10, 14 // Col H corresponds to locations 3, 7, 11, 15 if (columnOrRow == 'E') { if (shiftNum == 1) { shiftLetters(board, 0, 4, 8, 12, 1); } else if (shiftNum == 2) { shiftLetters(board, 0, 4, 8, 12, 2); } else if (shiftNum == 3) { shiftLetters(board, 0, 4, 8, 12, 3); } } else if (columnOrRow == 'F') { if (shiftNum == 1) { shiftLetters(board, 1, 5, 9, 13, 1); } else if (shiftNum == 2) { shiftLetters(board, 1, 5, 9, 13, 2); } else if (shiftNum == 3) { shiftLetters(board, 1, 5, 9, 13, 3); } } else if (columnOrRow == 'G') { if (shiftNum == 1) { shiftLetters(board, 2, 6, 10, 14, 1); } else if (shiftNum == 2) { shiftLetters(board, 2, 6, 10, 14, 2); } else if (shiftNum == 3) { shiftLetters(board, 2, 6, 10, 14, 3); } } else if (columnOrRow == 'H') { if (shiftNum == 1) { shiftLetters(board, 3, 7, 11, 15, 1); } else if (shiftNum == 2) { shiftLetters(board, 3, 7, 11, 15, 2); } else if (shiftNum == 3) { shiftLetters(board, 3, 7, 11, 15, 3); } } } // end of makeMoveColumn() //----------------------------------------------------------------------------- // Display the board in its current state void displayBoard(char board[17]) { printf("\n"); printf(" E F G H \n"); printf(" ------- \n"); printf("A| %c %c %c %c \n", board[0], board[1], board[2], board[3]); printf("B| %c %c %c %c \n", board[4], board[5], board[6], board[7]); printf("C| %c %c %c %c \n", board[8], board[9], board[10], board[11]); printf("D| %c %c %c %c \n", board[12], board[13], board[14], board[15]); printf("\n"); } // end of displayBoard() //----------------------------------------------------------------------------- // Takes an input of letters and returns a random one out of the 4 given char randomLetter(char first, char second, char third, char fourth) { char letterChosen; // The letter that will be returned char arrayLetters[5]; // Storing all the letters in an array int randomInt; // Used to select one of the 4 randomly randomInt = (rand() % 4); // Gives us a number 1 through 4 // Assignment of letters to array locations arrayLetters[0] = first; arrayLetters[1] = second; arrayLetters[2] = third; arrayLetters[3] = fourth; arrayLetters[4] = '\0'; // Assignment of our randomletter by the randomInt letterChosen = arrayLetters[randomInt]; //returning the random Letter return letterChosen; } // end of randomLetter() //----------------------------------------------------------------------------- // Performs an automated and randomized rotation of a single row by a single number void doRowRotation(char board[17], char columnOrRow, int shiftingNumber) { // First we select a random row to be rotated, and then a random value // by which to rotate columnOrRow = randomLetter('A', 'B', 'C', 'D'); shiftingNumber = (rand() % 3) + 1; // perform the shifting of the row if (columnOrRow == 'A' || columnOrRow == 'B' || columnOrRow == 'C' || columnOrRow == 'D') { makeMoveRow(columnOrRow, shiftingNumber, board); } } // end of doRowRotation() //----------------------------------------------------------------------------- // Performs an automated and randomized rotation of a single column by a number void doColumnRotation(char board[17], char columnOrRow, int shiftingNumber) { // First we select a random column to be rotated // and then a random value by which to rotate columnOrRow = randomLetter('E', 'F', 'G', 'H'); shiftingNumber = (rand() % 3) + 1;; // perform the shifting of the column if (columnOrRow == 'E' || columnOrRow == 'F' || columnOrRow == 'G' || columnOrRow == 'H') { makeMoveColumn(columnOrRow, shiftingNumber, board); } } // end of doColumnRotation() //----------------------------------------------------------------------------- // Randomizes the order of rotations of one column and two rows // Three possible iterations of rotation exist: // Column, Row, Row ; Row, Column, Row; Row, Row, Column; void randomizeRotations( char board[17], // The playing board char &columnOrRow, // Passed as an argument for later use int &shiftingNumber, // Specifies by what amount to rotate by int orderNumber) // Specifies which order to rotate by { if (orderNumber == 1) { doColumnRotation(board, columnOrRow, shiftingNumber); doRowRotation(board, columnOrRow, shiftingNumber); doRowRotation(board, columnOrRow, shiftingNumber); } else if (orderNumber == 2) { doRowRotation(board, columnOrRow, shiftingNumber); doColumnRotation(board, columnOrRow, shiftingNumber); doRowRotation(board, columnOrRow, shiftingNumber); } else if (orderNumber == 3) { doRowRotation(board, columnOrRow, shiftingNumber); doRowRotation(board, columnOrRow, shiftingNumber); doColumnRotation(board, columnOrRow, shiftingNumber); } } // end of randomizeRotations() //----------------------------------------------------------------------------- // Loops through a dictionary searching for matching words, as words are found // the wordCounter is increased void loopThroughDictionary( char wordToSearch[4], // word we will look to match char **dictionary, // dictionary we will try to search int &wordCounter, // counter for words found int numberOfWords) // number of total words in dictionary { char *pstr = NULL; // pointer to be used for words in the dictionary int i = 0; // if our pstr pointer does not return NULL, a word was found, so wordcounter++ for (i = 0; i < numberOfWords; i++) { pstr = strstr(dictionary[i], wordToSearch); if (pstr != NULL) { wordCounter++; } } } // end of loopThroughDictionary() //----------------------------------------------------------------------------- // Checks if all rows on the board match up with words found in the dictionary // If all rows match, a congratulatory message is displayed and the program exits void checkForWin(char board[17], char **dictionary, int numberOfWords) { int wordCounter = 0; // Counts number of words found char wordToSearch[5]; // Word on the board we are searching for int boardLocation = 0; // Current location on the board int boardRow = 0; int boardCol = 0; // Loop through every location on the board searching for matching words for (boardCol = 0; boardCol < 4; boardCol++) { for (boardLocation = 0; boardLocation < 4; boardLocation++) { wordToSearch[boardLocation] = board[boardRow]; boardRow++; } wordToSearch[4] = '\0'; // Looping through dictionary searching for matches loopThroughDictionary(wordToSearch, dictionary, wordCounter, numberOfWords); // Finding all words on the board match if (wordCounter == 4) { printf("Congratulations! You solved it!\n"); system("pause"); exit(0); } } } // end of CheckForWin() //----------------------------------------------------------------------------- // Changes all characters on the board to 16 characters the user specifies // in both identical order, format, and capitalization. // We prompt the user for 16 characters exact, through which we will change the // board void resetBoard(char board[17]) { char resetString[17]; // The new string of chars to reset the board with printf("\nYou chose 'r' to reset the board.\n"); printf("Enter 16 char values to reset the board: \n"); scanf("%16s", resetString); while (strlen(resetString) != 16) { printf("Sorry, needed to provide exactly 16 characters of user input to reset the board.Please retry.\n"); printf("Enter 16 char values to reset the board: \n"); scanf("%16s", resetString); } // Changing all characters on the board to the new string of chars for (int i = 0; i < 16; i++){ board[i] = resetString[i]; } displayBoard(board); // Displaying the new board } // end of resetBoard() //----------------------------------------------------------------------------- // Allows the user to try and unscramble the board, unveil the words on the board, // or reset the board with a new set of characters void playGame (char board[17], // Board to play with char columnOrRow, // Whether a row or column will be shifted char shiftingNumber, // How much to shift by char moveCounter, // Counts how many moves have been performed char **dictionaryWords, // Dictionary of words int numberOfWords, // Number of words in dictionary char originalBoard[17]) // A copy of the original board pre-scramble { // We prompt the user for a move do { printf("%d. Enter the row or column to be rotated, and a number 1..3: \n", moveCounter); scanf(" %c", &columnOrRow); columnOrRow = toupper(columnOrRow); if (columnOrRow == 'R') { // Reset the board resetBoard(board); continue; } if (columnOrRow == 'U') { // Unveils all words on the board printf("\nYou chose 'u' to unveil. Here are the underlying words.\n"); displayOriginalBoard(originalBoard); displayBoard(board); continue; } if (columnOrRow == 'X') { // Exits the game printf("You chose to exit. Exiting...\n"); system("pause"); exit(0); } scanf(" %d", &shiftingNumber); // Number by which to shift // Performing specified rotations printf("Rotating row/col %c by %d", columnOrRow, shiftingNumber); if (columnOrRow == 'A' || columnOrRow == 'B' || columnOrRow == 'C' || columnOrRow == 'D') { makeMoveRow(columnOrRow, shiftingNumber, board); } else if (columnOrRow == 'E' || columnOrRow == 'F' || columnOrRow == 'G' || columnOrRow == 'H') { makeMoveColumn(columnOrRow, shiftingNumber, board); } // Displaying the board and checking for a win displayBoard(board); checkForWin(board, dictionaryWords, numberOfWords); moveCounter++; } while (columnOrRow != 'X'); // Loop continues until a win or exit } // end of playGame() //----------------------------------------------------------------------------- int main(){ int dictionaryInput = 0; // which dictionary size to use int numberOfWords = 0; // number of words in the dictionary char **dictionaryWords; // words stored in the dictionary char board[17]; // playing board int moveCounter = 1; // count moves as the user goes char columnOrRow; // whether a row or column rotates int shiftingNumber = 0; // how much to rotate a row or column by int orderNumber = 0; // randomized order number to scramble board char originalBoard[17]; // copy of original board pre-scrambled displayInformation(); displayInstructions(); // ask for a dictionary size scanf("%d", &dictionaryInput); // count words in dictionary numberOfWords = readInDictionary(dictionaryInput); // allocate memory for words in dictionary dictionaryWords = (char**)malloc(numberOfWords * sizeof(char*)); for (int i = 0; i < numberOfWords; i++) { dictionaryWords[i] = (char*)malloc(5 * sizeof(char)); } // store words in the dictionary from a .txt file storeWords(dictionaryInput, dictionaryWords); // create a board to play with createBoard(dictionaryWords, board, numberOfWords, originalBoard); // seed a random number generator srand((int)time(0)); // choose a random order number orderNumber = (rand() % 3) + 1; // randomize rotations of the board (scramble) randomizeRotations(board, columnOrRow, shiftingNumber, orderNumber); displayBoard(board); // user can now play the game playGame(board, columnOrRow, shiftingNumber, moveCounter, dictionaryWords, numberOfWords, originalBoard); system("pause"); return 0; } //end of main()
0120e972593ebcd77b2e45e1df26777978ba8f5f
[ "C++" ]
2
C++
raultelbisz/WordGame
37b116a6a0afcad6ae9129c5bb081c0f0557ced5
dfc9b98af17c746d32ce18e88911fd2f1eaccf55
refs/heads/master
<file_sep>from django.db import models from django.contrib.auth.models import User # Create your models here. class User_Regular(models.Model): user = models.OneToOneField(User) isAdmin = models.BooleanField() class Location(models.Model): name = models.CharField(max_length=850) # Location name - example "Faculty of Organizational Sciences" locationImg = models.CharField(max_length =850) # Location image description = models.TextField(max_length = 800) # Location description locationLink = models.CharField(max_length = 800) # Link to otganization website longitude = models.CharField(max_length =800) # Longitude for Google Maps latitude = models.CharField(max_length =800) # Latitude for Google Maps owner = models.ForeignKey(User_Regular) class Box(models.Model): Location = models.ForeignKey(Location) class Log(models.Model): NumberOfCaps = models.IntegerField() Timestamp = models.DateTimeField(auto_now_add = True) isFull = models.BooleanField() Box = models.ForeignKey(Box) <file_sep>from django.conf.urls import patterns, include, url import views urlpatterns = patterns('', #url(r'^lokacije/$', views.locations, name= "locations"), url(r'^$', views.home, name= "home"), url(r'^admin/$', views.admin, name="admin"), url(r'^admin/addlocation/$', views.addlocation, name="addlocation"), url(r'^admin/addbox/$', views.addbox, name="addbox"), url(r'^admin/adduser/$', views.adduser, name="adduser"), url(r'^lokacije/$', views.locations, name="locations"), url(r'^lokacija$', views.location, name="location"), url(r'^api/$', views.api, name="api"), )<file_sep># Create your views here. from django import forms from django.utils import timezone from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from models import Location, Box, Log, User_Regular from datetime import datetime, timedelta import pytz GOAL = 1000 def makeLog(number, full, box_ID): box = Box.objects.get(id = box_ID) log = Log(Box = box) log.NumberOfCaps = number log.isFull = full log.save() def adduser(request): request.session.set_expiry(0) username = request.POST['username'] password = request.POST['<PASSWORD>'] email = request.POST['email'] user = User.objects.create_user(username, email, password) newUser = User_Regular() newUser.user = user newUser.isAdmin = False newUser.save() return redirect('admin') def getCapSum(): capSum = 0 logs = Log.objects.all() for log in logs: capSum += log.NumberOfCaps return capSum def percentCompleted(): capSumGoal = float(getCapSum()%GOAL) percent = (capSumGoal/GOAL)*100 return percent def daysLeft(): capSum = 0 date = datetime.now(pytz.utc) fiveDaysAgo = date+timedelta(days=-5) logs = Log.objects.all() for log in logs: if log.Timestamp > fiveDaysAgo: capSum+= log.NumberOfCaps mean = float(capSum)/5 if mean == 0: return 30 daysLeft = (GOAL-(getCapSum()%GOAL))/mean return round(daysLeft, 2) def home(request): #makeLog() capSum = getCapSum() ctx = {'capSum':capSum, 'percent': percentCompleted(),'daysLeft':daysLeft()} return render(request, "home.html", ctx) def admin(request): locations = Location.objects.all() boxes = Box.objects.all() users = User_Regular.objects.all() ctx = {'locations':locations, 'boxes':boxes, 'users':users} return render(request, "admin.html", ctx) def addlocation(request): request.session.set_expiry(0) location = Location() location.name = request.POST['name'] location.locationImg = request.POST['locationImg'] location.description = request.POST['description'] location.locationLink = request.POST['locationLink'] location.longitude = request.POST['longitude'] location.latitude = request.POST['latitude'] user_id = request.POST['sel1'] userUser = User.objects.get(id = user_id) user = User_Regular.objects.get(user = userUser) location.owner = user location.save() return redirect('admin') def addbox(request): request.session.set_expiry(0) box = Box() location_id = request.POST['sel2'] box.Location = Location.objects.get(id = location_id) box.save() return redirect('admin') @csrf_exempt def api(request): number = request.POST['NumberOfCaps'] full = request.POST['isFull'] box_ID = request.POST['Box'] makeLog(number, full, box_ID) return HttpResponse(status = 200) def locations(request): locations = Location.objects.all() ctx = {'locations': locations} return render(request, "locations.html", ctx) def location(request): location_id = request.GET.get('id') location = Location.objects.get(id = location_id) ctx = {'location': location} return render(request, "location.html",ctx)
0a4bf2e0763eb3c161c0cd20bf3b1b49584661c7
[ "Python" ]
3
Python
dkeske/KutijaSajt
58e8d479cee3ca6c298cd86dee07767f8c7d9c5c
011591aedcfaa57115f93151592946a1c7967eb8
refs/heads/main
<repo_name>LGLTeam/FreeFire-ESP-And-Aimbot<file_sep>/app/src/main/jni/src/main.cpp #include <pthread.h> #include <jni.h> #include <src/Includes/Utils.h> #include "Hook.h" #include "Função.h" #if defined(__aarch64__) //Compile for arm64 lib only #include <src/And64InlineHook/And64InlineHook.hpp> #else //Compile for armv7 lib only. Do not worry about greyed out highlighting code, it still works #include <src/Substrate/SubstrateHook.h> #endif #include "KittyMemory/MemoryPatch.h" #include "Includes/Logger.h" #include "struc.h" #define HOOK(offset, ptr, orig) MSHookFunction((void *)getRealOffset(offset), (void *)ptr, (void **)&orig) switch (feature) { // The category was 0 so "case 0" is not needed case 0: MT.hs100 = !MT.hs100; byFOV = !byFOV; break; break; case 1: MT.aimFire= !MT.aimFire; break; case 2: MT.aimScope= !MT.aimScope; break; case 3: MT.aimAgachado = !MT.aimAgachado; break; case 4: if (Value > 0) { MT.Fov_Aim = 1.0f - (0.0099f * (float)Value); } break; case 5: if (Value > 0) { MT.aimBotFov = 1.0f - (0.0099f * (float)Value); } break; case 6: if (Value == 0) { Patches.SensiNormal.Restore(); Patches.SensiMedia.Restore(); Patches.SensiAlta.Restore(); } else if (Value == 1) { Patches.SensiNormal.Modify(); } else if (Value == 2) { Patches.SensiMedia.Modify(); } else if (Value == 3) { Patches.SensiAlta.Modify(); } break; case 7: MT.espFire = !MT.espFire; break; default: break; case 8: MT.espNames = !MT.espNames; break; case 9: MT.fakeName = !MT.fakeName; break; case 10: if (Value == 0) { Patches.CorpoHack1.Restore(); Patches.CorpoHack2.Restore(); Patches.CorpoHack3.Restore(); Patches.CorpoHack4.Restore(); Patches.CorpoHack5.Restore(); } else if (Value == 1) { Patches.CorpoHack1.Modify(); } else if (Value == 2) { Patches.CorpoHack2.Modify(); } else if (Value == 3) { Patches.CorpoHack3.Modify(); } else if (Value == 4) { Patches.CorpoHack4.Modify(); } else if (Value == 5) { Patches.CorpoHack5.Modify(); } break; case 11: MT.teleKill = !MT.teleKill; break; case 12: MT.ghost = !MT.ghost; break; case 13: KMHack123 = !KMHack123; if (KMHack123) { Patches.Socofast.Modify(); } else { Patches.Socofast.Restore(); } break; case 14: KMHack5 = !KMHack5; if (KMHack5) { Patches.WhiteBody.Modify(); Patches.WhiteBody2.Modify(); } else { Patches.WhiteBody.Restore(); Patches.WhiteBody2.Restore(); } break; case 15: KMHack4 = !KMHack4; if (KMHack4) { Patches.MedKitRunning.Modify(); Patches.MedKitRunning2.Modify(); } else { Patches.MedKitRunning.Restore(); Patches.MedKitRunning2.Restore(); } break; case 16: KMHack33 = !KMHack33; if (KMHack33) { Patches.modcorHd.Modify(); } else { Patches.modcorHd.Restore(); } break; case 17: KMHack3 = !KMHack3; if (KMHack3) { Patches.NightMod.Modify(); } else { Patches.NightMod.Restore(); } break; case 18: KMHack15 = !KMHack15; if (KMHack15) { Patches.WallPedra.Modify(); } else { Patches.WallPedra.Restore(); } break; } } } void (*LateUpdate)(void *componentPlayer); void AimBot(void *local_player, void *enemy_player) { int pose = GetPhysXPose(enemy_player); bool alive = get_isAlive(enemy_player); bool visible = get_isVisible(enemy_player); bool visi = get_AttackableEntity_IsVisible(enemy_player); bool visir = get_AttackableEntity_GetIsDead(enemy_player); bool sameteam = get_isLocalTeam(enemy_player); void *HeadTF = *(void **)((uintptr_t)enemy_player + Global.HeadTF); void *HipTF = *(void **)((uintptr_t)enemy_player + Global.HipTF); void *Main_Camera = *(void **)((uintptr_t)local_player + Global.MainCameraTransform); if (!get_IsSkyDashing(local_player) && !get_IsParachuting(local_player) && !get_IsSkyDiving(local_player) && !get_IsDieing(local_player) && alive && pose != 8 && !sameteam && HeadTF != NULL && Main_Camera != NULL && HipTF != NULL) { Vector3 EnemyLocation = Transform_INTERNAL_GetPosition(HeadTF); Vector3 CenterWS = GetAttackableCenterWS(local_player); bool scope = get_IsSighting(local_player); bool agachado = get_IsCrouching(local_player); float distance = Vector3::Distance(CenterWS, EnemyLocation); Vector3 PlayerLocation = Transform_INTERNAL_GetPosition(Main_Camera); Quaternion PlayerLook = GetRotationToLocation(EnemyLocation, 0.1f, PlayerLocation); Quaternion PlayerLook2 = GetRotationToLocation(Transform_INTERNAL_GetPosition(HipTF), 0.1f, PlayerLocation); Vector3 fwd = Transform_get_forward(Main_Camera); Vector3 nrml = Vector3::Normalized(EnemyLocation - PlayerLocation); float PlayerDot = Vector3::Dot(fwd, nrml); if (MT.espFire) { void *imo = get_imo(local_player); if (imo != NULL && distance > 1.0f) { set_esp(imo, CenterWS, EnemyLocation); } } if (MT.AlertWorld) { monoString *alert = FormatCount(MT.enemyCountWorld, MT.botCountWorld); if (alert != NULL) { ShowDynamicPopupMessage(alert); } } if (MT.fakeName) { spofNick(local_player); } if (MT.espNames) { void *ui = CurrentUIScene(); if (ui != NULL) { monoString *nick = get_NickName(enemy_player); monoString *distances = U3DStrFormat(distance); AddTeammateHud(ui, nick, distances); } } if (MT.Paraquedas ) { void *_MountTF = Component_GetTransform(enemy_player); if (_MountTF != NULL) { Vector3 MountTF = Patches.Teletransport.Modify(); Patches.Teletransport.Restore(); Transform_INTERNAL_GetPosition(_MountTF) - (GetForward(_MountTF) * 1.6f); Transform_INTERNAL_SetPosition(Component_GetTransform(local_player), Vvector3(MountTF.X, MountTF.Y, MountTF.Z)); } } if (MT.teleKill) { set_aim(local_player, PlayerLook); void *_MountTF = Component_GetTransform(enemy_player); if (_MountTF != NULL) { Vector3 MountTF = Transform_INTERNAL_GetPosition(_MountTF) - (GetForward(_MountTF) * 1.6f); Transform_INTERNAL_SetPosition(Component_GetTransform(local_player), Vvector3(MountTF.X, MountTF.Y, MountTF.Z)); } } if ((agachado && MT.aimAgachado) && ((PlayerDot > 0.998f && !MT.aimBotFov) || (PlayerDot > MT.Fov_Aim && MT.aimBotFov))) { set_aim(local_player, PlayerLook); } if ((scope && MT.aimScope) && ((PlayerDot > 0.998f && !MT.aimBotFov) || (PlayerDot > MT.Fov_Aim && MT.aimBotFov))) { set_aim(local_player, PlayerLook); } bool firing = IsFiring(local_player); if ((firing && MT.aimFire) && ((PlayerDot > 0.998f && !MT.aimBotFov) || (PlayerDot > MT.Fov_Aim && MT.aimBotFov))) { if (MT.aimBody) { set_aim(local_player, PlayerLook2); } if (MT.hs100) { set_aim(local_player, PlayerLook); } if (MT.hs70) { if (MT.aimbotauto) { set_aim(local_player, PlayerLook); ++MT.semihs; } else { set_aim(local_player, PlayerLook2); --MT.semihs; } if (MT.semihs == 6) { MT.aimbotauto = false; } else if (MT.semihs == 0) { MT.aimbotauto = true; } if (MT.semihs > 6 || MT.semihs < 0) { MT.semihs = 3; MT.aimbotauto = true; } } } } } bool isEspReady = false; void *fakeEnemy; void _LateUpdate(void *player){ if (player != NULL) { void *local_player = Current_Local_Player(); if (local_player == NULL){ local_player = GetLocalPlayerOrObServer(); } if (local_player != NULL){ void *current_match = Curent_Match(); if (current_match != NULL) { void *fakeCamPlayer = get_MyFollowCamera(local_player); void *fakeCamEnemy = get_MyFollowCamera(player); if (fakeCamPlayer != NULL && fakeCamEnemy != NULL){ void *fakeCamPlayerTF = Component_GetTransform(fakeCamPlayer); void *fakeCamEnemyTF = Component_GetTransform(player); if (fakeCamPlayerTF != NULL && fakeCamEnemyTF != NULL){ Vector3 fakeCamPlayerPos = Transform_INTERNAL_GetPosition(fakeCamPlayerTF); Vector3 fakeCamEnemyPos = Transform_INTERNAL_GetPosition(fakeCamEnemyTF); float distance = Vector3::Distance(fakeCamPlayerPos, fakeCamEnemyPos); if (player != local_player){ if (distance > 1.6f) { bool sameteams = get_isLocalTeam(player); int pose = GetPhysXPose(player); bool alive = get_isAlive(player); bool visible = get_isVisible(player); bool visir = get_AttackableEntity_GetIsDead(player); if (!sameteams && pose != 8 && alive && !get_IsSkyDashing(player) && !get_IsSkyDiving(player) && !get_IsDieing(player) && IsVisible(player) && get_CurHP(player) > 0) { AimBot(local_player, player); } } else { fakeEnemy = player; } } } } } } } LateUpdate(player); } Vector3 GetHeadPosition(void* player){ return Transform_INTERNAL_GetPosition(*(void**) ((uint64_t) player + 0x1A0)); } Vector3 GetHipPosition(void* player){ return Transform_INTERNAL_GetPosition(*(void**) ((uint64_t) player + 0x1A4)); } void* GetClosestEnemy(void* _this, bool byFOV) { if(_this == NULL) { return NULL; } float shortestDistance = 99999999.0; float maxAngle = 30.0; void* closestEnemy = NULL; void* LocalPlayer = GetLocalPlayer(_this); if(LocalPlayer != NULL && !get_IsSkyDashing(LocalPlayer) && !get_IsParachuting(LocalPlayer) && !get_IsSkyDiving(LocalPlayer) && !get_IsDieing(LocalPlayer)); for (int u = 0; u <= 50; u++) { void *Player = getPlayerByIndex(_this, (uint8_t) u); { if (Player != NULL && !IsSameTeam(LocalPlayer, Player) && !get_IsDieing(Player) && !get_IsSkyDashing(Player) && !get_IsParachuting(Player) && !get_IsSkyDiving(Player) && IsVisible(Player) && get_CurHP(Player) > 0) { Vector3 PlayerPos = GetHipPosition(Player); Vector3 LocalPlayerPos = GetHipPosition(LocalPlayer);Transform_INTERNAL_GetPosition(Component_get_transform(get_main())); float distanceToMe = Vector3::Distance(LocalPlayerPos, PlayerPos); if(byFOV) { Vector3 targetDir = PlayerPos - LocalPlayerPos; float angle = Vector3::Angle(targetDir, Transform_get_forward(Component_get_transform(get_main()))) * 100.0; if(angle <= maxAngle) { if(distanceToMe < shortestDistance) { shortestDistance = distanceToMe; closestEnemy = Player; } } } else { if(distanceToMe < shortestDistance) { shortestDistance = distanceToMe; closestEnemy = Player; } } } } } return closestEnemy; } bool (*orig_ghost)(void* _this, int value); bool _ghost(void* _this, int value){ if (_this != NULL){ if (MT.ghost || MT.teleKill){ return false; } } return orig_ghost(_this, value); } void *hack_thread(void *) { ProcMap il2cppMap; do { il2cppMap = KittyMemory::getLibraryMap(libName); sleep(1); } while (!il2cppMap.isValid()); Patches.Bypass.Modify(); Patches.Teletransport = MemoryPatch("libil2cpp.so", ghost, "\x00\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.Teletransport2 = MemoryPatch("libil2cpp.so", ghost, "\x00\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.Speed1 = MemoryPatch("libil2cpp.so", speed, "\x82\x0F\x43\xE3\x1E\xFF\x2F\xE1", 8); Patches.Speed2 = MemoryPatch("libil2cpp.so", speed, "\x84\x0F\x43\xE3\x1E\xFF\x2F\xE1", 8); Patches.NoParacaidas = MemoryPatch("libil2cpp.so", paraquedas, "\x00\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.Viewcamera1 = MemoryPatch("libil2cpp.so", speed, "\x32\x00\x44\xE3\x1E\xFF\x2F\xE1", 8); Patches.Viewcamera2 = MemoryPatch("libil2cpp.so", speed, "\x64\x00\x44\xE3\x1E\xFF\x2F\xE1", 8); Patches.Viewcamera3 = MemoryPatch("libil2cpp.so", speed, "\x7F\x00\x44\xE3\x1E\xFF\x2F\xE1", 8); Patches.MedKitRunning = MemoryPatch("libil2cpp.so", medkit1, "\x00\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.MedKitRunning2 = MemoryPatch("libil2cpp.so", medkit2, "\x00\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.MedKitRunning3 = MemoryPatch("libil2cpp.so", medkit3, "\x00\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.WhiteBody = MemoryPatch("libil2cpp.so", branco1, "\x01\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.WhiteBody2 = MemoryPatch("libil2cpp.so", branco2, "\x00\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.modcorHd = MemoryPatch("libil2cpp.so", modohd, "\x00\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.SemDano = MemoryPatch("libil2cpp.so", semdano, "\x00\x00\xD0\xC1", 4); Patches.NoScope = MemoryPatch("libil2cpp.so", removermira, "\x00\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.AimbotSemi = MemoryPatch("libil2cpp.so", semi, "\x5C\x04\x44\xE3\x1E\xFF\x2F\xE1", 8); Patches.Socofast = MemoryPatch("libil2cpp.so", soco, "\x8A\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.MiraLockUpd = MemoryPatch("libil2cpp.so", miraLockUpd, "\x00\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.MiraLock = MemoryPatch("libil2cpp.so", aimlock, "\x01\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.RecargaFast = MemoryPatch("libil2cpp.so", recargarapida, "\x12\x03\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.SemDelay = MemoryPatch("libil2cpp.so", semdelay1, "\x00\x00\x00\x00", 4); Patches.SemDelay2 = MemoryPatch("libil2cpp.so", semdelay2, "\x00\x00\x00\x00", 4); Patches.TiroMovimento = MemoryPatch("libil2cpp.so", tiroEmMovimento, "\x01\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.SensiNormal = MemoryPatch("libil2cpp.so", sensibilidade, "\x00\x00\x7A\x43", 4); Patches.SensiMedia = MemoryPatch("libil2cpp.so", sensibilidade, "\x00\x00\x48\x43", 4); Patches.SensiAlta = MemoryPatch("libil2cpp.so", sensibilidade, "\x00\x00\x16\x43", 4); Patches.ChuvaBug = MemoryPatch("libil2cpp.so", chuvaBug, "\x12\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala1 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x02\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala2 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x03\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala3 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x04\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala4 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x05\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala5 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x06\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala6 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x07\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala7 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x08\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala8 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x09\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala9 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x0A\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala10 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x0B\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala11 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x0C\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala12 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x0D\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala13 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x0E\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala14 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x0F\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.ChuvaBala15 = MemoryPatch("libil2cpp.so", chuvaBalas, "\x10\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.WallCarroUpd = MemoryPatch("libil2cpp.so", wallCarroUpd, "\x00\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.WallCarro = MemoryPatch("libil2cpp.so", wallCarro, "\x00\x00\xA0\xE3\x1E\xFF\x2F\xE1", 8); Patches.NightMod = MemoryPatch("libunity.so", modonoite, "\x00\x00\x80\xBF", 4); Patches.AntenaPro = MemoryPatch("libunity.so", antenaCorpo, "\x10\x40\x1C\x46", 4); Patches.CorpoHack1 = MemoryPatch("libil2cpp.so", corpoGrande, "\x81\x0F\x43\xE3\x1E\xFF\x2F\xE1", 8); Patches.CorpoHack2 = MemoryPatch("libil2cpp.so", corpoGrande, "\x82\x0F\x43\xE3\x1E\xFF\x2F\xE1", 8); Patches.CorpoHack3 = MemoryPatch("libil2cpp.so", corpoGrande, "\x83\x0F\x43\xE3\x1E\xFF\x2F\xE1", 8); Patches.CorpoHack4 = MemoryPatch("libil2cpp.so", corpoGrande, "\x84\x0F\x43\xE3\x1E\xFF\x2F\xE1", 8); Patches.CorpoHack5 = MemoryPatch("libil2cpp.so", corpoGrande, "\x85\x0F\x43\xE3\x1E\xFF\x2F\xE1", 8); Patches.SuperSpeed = MemoryPatch("libunity.so", antenaCorpo, "\x10\x40\x1C\x46", 4); Patches.Bypass = MemoryPatch("libtersafe.so", 0x1DEFF8, "\x00\x20\x70\x47", 4); Patches.WallPedra = MemoryPatch("libunity.so", zePedrinha, "\xC9\x3C\x8E\xBF\xC9\x3C\x8E\xBF\xC9\x3C\x8E\xBF\xC9\x3C\x8E\xBF", 16); HOOK(0xA3D2E4, _LateUpdate, LateUpdate); HOOK(0xBF408C, _ghost, orig_ghost); return NULL; } // loop until our target library is found JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *globalEnv; vm->GetEnv((void **) &globalEnv, JNI_VERSION_1_6); // Create a new thread so it does not block the main thread, means the game would not freeze pthread_t ptid; pthread_create(&ptid, NULL, hack_thread, NULL); return JNI_VERSION_1_6; } JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) {} <file_sep>/app/src/main/jni/src/Global.h #ifndef ANDROID_MOD_MENU_GLOBAL_H #define ANDROID_MOD_MENU_GLOBAL_H struct { uintptr_t MainCameraTransform = 0x54; uintptr_t HeadTF = 0x1A0; uintptr_t HipTF = 0x1A4; uintptr_t HandTF = 0x19C; uintptr_t EyeTF = 0x1A8; uintptr_t IsClientBot = 0xC4; uintptr_t U3DStr = 0x2003AE4; uintptr_t U3DStrConcat = 0x2002284; uintptr_t Component_GetTransform = 0x2689594; uintptr_t GetCameraTrackableEntityTransfrom = 0xA5C7CC; uintptr_t Transform_INTERNAL_GetPosition = 0x2C9523C; uintptr_t Transform_INTERNAL_SetPosition = 0x2C952FC; uintptr_t GetForward = 0x2C95920; uintptr_t get_isAlive = 0xA5C7D4; uintptr_t GetPhysXPose = 0xA20504; uintptr_t IsFiring = 0xA32650; uintptr_t IsCrouching = 0xA20538; uintptr_t get_IsSighting = 0xA68864; uintptr_t get_IsCrouching = 0xA20538; uintptr_t get_isLocalPlayer = 0xA18CDC; uintptr_t get_isLocalTeam = 0xA1EC58; uintptr_t get_isVisible = 0xA182F0; uintptr_t set_aim = 0xA162E0; uintptr_t Camera_main_fov = 0x2682544; uintptr_t get_imo = 0xA1B034; uintptr_t set_esp = 0xBDF540; uintptr_t GetAttackableCenterWS = 0xA14E3C; uintptr_t GetCharacterControllerTopPosition = 0xA54880; uintptr_t get_NickName = 0xA15364; uintptr_t WorldToScreenPoint = 0x2684310; uintptr_t get_height = 0x29E2974; uintptr_t get_width = 0x29E28E4; uintptr_t get_deltaTime = 0x2C93CE4; uintptr_t CurrentUIScene = 0x24DF694; uintptr_t Curent_Match = 0x24E00E8; uintptr_t Current_Local_Player = 0x24E043C; uintptr_t GetLocalPlayerOrObServer = 0x24E0AFC; uintptr_t CurrentLocalSpectator = 0x24E08BC; uintptr_t Player_Index = 0x1A061EC; uintptr_t AddTeammateHud = 0x12340C8; uintptr_t get_tele = 0xBF6AE4; uintptr_t spof_uid = 0xA15274; uintptr_t spof_nick = 0xA1536C; uintptr_t ShowDynamicPopupMessage = 0x12222A4; uintptr_t ShowPopupMessage = 0x122242C; uintptr_t GetLocalPlayer = 0x1FBCF6C; uintptr_t GetCharacterHeight = 0xA272E8; uintptr_t set_height = 0x2687EA0; uintptr_t get_CharacterController = 0xA15710; uintptr_t IsUserControlChanged = 0xA20414; uintptr_t set_invitee_nickname = 0x2BC7240; uintptr_t Raycast = 0x298C28C; uintptr_t get_MyFollowCamera = 0xA15C3C; uintptr_t IsSameTeam = 0x24E1894; uintptr_t AttackableEntity_GetIsDead = 0x23A4B4C; uintptr_t AttackableEntity_IsVisible = 0x23A6ADC; uintptr_t Camera_WorldToScreenPoint = 0x2684310; uintptr_t Camera_main = 0x2684900; uintptr_t wallPedra = 0xEF2890; uintptr_t nightMode = 0x1A2280; uintptr_t medKit1 = 0xA91ACC; uintptr_t medKit2 = 0x2160BA0; uintptr_t medKit3 = 0xA3CC6C; uintptr_t ghostHack = 0xBF6AE4; uintptr_t hdGraphic = 0x29DDB78; uintptr_t rainbullets = 0xBD2278; } Global; #endif<file_sep>/app/src/main/jni/src/Função.h #include <pthread.h> #include <jni.h> #include <src/Includes/Utils.h> #include "Hook.h" #if defined(__aarch64__) //Compile for arm64 lib only #include <src/And64InlineHook/And64InlineHook.hpp> #else //Compile for armv7 lib only. Do not worry about greyed out highlighting code, it still works #include <src/Substrate/SubstrateHook.h> #endif #include "KittyMemory/MemoryPatch.h" #include "Includes/Logger.h" extern "C" { JNIEXPORT jboolean JNICALL Java_com_mt_team_FloatingModMenuService_EnableSounds( JNIEnv *env, jobject activityObject) { return true; } JNIEXPORT jstring JNICALL Java_com_mt_team_FloatingModMenuService_lcon( JNIEnv *env, jobject activityObject) { return env->NewStringUTF("https://joelitonmods.000webhostapp.com/Joeliton.php"); } JNIEXPORT jstring JNICALL Java_com_mt_team_FloatingModMenuService_Toggle( JNIEnv *env, jobject activityObject) { return env->NewStringUTF("Tog_"); } JNIEXPORT jstring JNICALL Java_com_mt_team_FloatingModMenuService_Botao( JNIEnv *env, jobject activityObject) { return env->NewStringUTF("Bnt_"); } JNIEXPORT jstring JNICALL Java_com_mt_team_FloatingModMenuService_off( JNIEnv *env, jobject activityObject) { return env->NewStringUTF("Of_"); } JNIEXPORT jstring JNICALL Java_com_mt_team_FloatingModMenuService_Seekbar( JNIEnv *env, jobject activityObject) { return env->NewStringUTF("Sear_"); } JNIEXPORT jint JNICALL Java_com_mt_team_FloatingModMenuService_IconSize( JNIEnv *env, jobject activityObject) { return 70; } JNIEXPORT jstring JNICALL Java_com_mt_team_FloatingModMenuService_Icon( JNIEnv *env, jobject activityObject) { //Use https://www.base64encode.org/ to encode your image to base64 std::string str = "<KEY>ZBl<KEY>lhx<KEY>"; return env->NewStringUTF(str.c_str()); } JNIEXPORT jobjectArray JNICALL Java_com_mt_team_FloatingModMenuService_getMitosTeam( JNIEnv *env, jobject activityObject) { jobjectArray ret; const char *features[] = { "Bnt_Of_HEADSHOT 100%","Bnt_Of_AIM POR TIRO","Bnt_Of_AIM POR MIRA","Bnt_Of_AIM AGACHADO","Sear_AIM FOV_0_360","Sear_AIM PUXADA_0_360","Sear_SENSIBILIDADE_0_3","Bnt_Of_ESP FIRE","Bnt_Of_ESP ALERTA","Bnt_Of_NOME FEIKE","Sear_SPEED HACK_0_5","Bnt_Of_TELEKILL","Bnt_Of_GHOST HACK","Bnt_Of_SOCO RÁPIDO","Bnt_Of_CORPO BRANCO","Bnt_Of_MEDKIT CORRENDO","Bnt_Of_MODO HD","Bnt_Of_MODO NOITE","Bnt_Of_ZÉ PEDRINHA"}; // 7 int Total_Feature = (sizeof features / sizeof features[0]); //Now you dont have to manually update the number everytime; ret = (jobjectArray) env->NewObjectArray(Total_Feature, env->FindClass("java/lang/String"), env->NewStringUTF("")); int i; for (i = 0; i < Total_Feature; i++) env->SetObjectArrayElement(ret, i, env->NewStringUTF(features[i])); return (ret); }<file_sep>/app/src/main/jni/src/KittyMemory/MemoryPatch.h #ifndef MemoryPatch_h #define MemoryPatch_h #include <vector> #include "KittyMemory.h" using KittyMemory::Memory_Status; using KittyMemory::ProcMap; class MemoryPatch { private: uintptr_t _address; size_t _size; std::vector<uint8_t> _orig_code; std::vector<uint8_t> _patch_code; public: MemoryPatch(); /* * expects library name and relative address */ MemoryPatch(const char *libraryName, uintptr_t address, const void *patch_code, size_t patch_size); ~MemoryPatch(); /* * Validate patch */ bool isValid() const; size_t get_PatchSize() const; /* * Returns pointer to the target address */ uintptr_t get_TargetAddress() const; /* * Restores patch to original value */ bool Restore(); /* * Applies patch modifications to target address */ bool Modify(); /* * Returns current patch target address bytes as hex string */ std::string ToHexString(); }; #endif /* MemoryPatch_h */ <file_sep>/app/src/main/jni/src/struc.h struct { MemoryPatch nightMode; MemoryPatch Teletransport; MemoryPatch Teletransport2; MemoryPatch Speed1; MemoryPatch Speed2; MemoryPatch NoParacaidas; MemoryPatch NightMod; MemoryPatch Viewcamera1; MemoryPatch Viewcamera2; MemoryPatch Viewcamera3; MemoryPatch MedKitRunning; MemoryPatch MedKitRunning2; MemoryPatch MedKitRunning3; MemoryPatch WhiteBody; MemoryPatch WhiteBody2; MemoryPatch modcorHd; MemoryPatch AntenaPro; MemoryPatch SemDano; MemoryPatch CorpoHack1; MemoryPatch CorpoHack2; MemoryPatch CorpoHack3; MemoryPatch CorpoHack4; MemoryPatch CorpoHack5; MemoryPatch NoScope; MemoryPatch SuperSpeed; MemoryPatch AimbotSemi; MemoryPatch Socofast; MemoryPatch MiraLockUpd; MemoryPatch MiraLock; MemoryPatch RecargaFast; MemoryPatch SemDelay; MemoryPatch SemDelay2; MemoryPatch TiroMovimento; MemoryPatch SensiNormal; MemoryPatch SensiMedia; MemoryPatch SensiAlta; MemoryPatch ChuvaBug; MemoryPatch ChuvaBala1; MemoryPatch ChuvaBala2; MemoryPatch ChuvaBala3; MemoryPatch ChuvaBala4; MemoryPatch ChuvaBala5; MemoryPatch ChuvaBala6; MemoryPatch ChuvaBala7; MemoryPatch ChuvaBala8; MemoryPatch ChuvaBala9; MemoryPatch ChuvaBala10; MemoryPatch ChuvaBala11; MemoryPatch ChuvaBala12; MemoryPatch ChuvaBala13; MemoryPatch ChuvaBala14; MemoryPatch ChuvaBala15; MemoryPatch WallPedra; MemoryPatch WallCarroUpd; MemoryPatch WallCarro; MemoryPatch wallPedra; MemoryPatch medKit1; MemoryPatch medKit2; MemoryPatch medKit3; MemoryPatch ghostHack; MemoryPatch Bypass; MemoryPatch rain1; MemoryPatch rain2; MemoryPatch rain3; MemoryPatch rain4; MemoryPatch rain5; MemoryPatch rain6; MemoryPatch rain7; MemoryPatch rain8; MemoryPatch rain9; MemoryPatch rain10; MemoryPatch rain11; MemoryPatch rain12; } Patches;; bool byFOV; bool KMHack1 = false, KMHack2 = false, KMHack3 = false, KMHack4 = false, KMHack5 = false, KMHack6 = false, KMHack7 = false, KMHack8 = false, KMHack9 = false, KMHack10 = false, KMHack11 = false, KMHack12 = false, KMHack13 = false, KMHack14 = false, KMHack15 = false, KMHack16 = false, KMHack17 = false, KMHack18 = false, KMHack33 = false, KMHack34 = false, KMHack87 = false, KMHack88 = false, KMHack01 = false, KMHack0 = false, KMHack123 = false, KMHack886 = false; int Desativer = 0; int semi = 0xBCF174; int ghost = 0xBF6AE4; int ghost2 = 0xBF6AE4; int speed = 0xA41BD0; int paraquedas = 0xA1DC2C; int viewcamera = 0x1B2471C; int medkit1 = 0x2160BA0; int medkit2 = 0xA3CC6C; int medkit3 = 0xA3A3D4; int branco1 = 0xA1FD7C; int branco2 = 0x1859F48; int modohd = 0x29DDB78; int semdano = 0x290CE18; int removermira = 0xBA0F08; int soco = 0xBD1FBC; int miraLockUpd = 0xB98834; int aimlock = 0x126F250; int recargarapida = 0x125C5A0; int semdelay1 = 0x2222D14; int semdelay2 = 0x1B436A0; int tiroEmMovimento = 0xA41358; int sensibilidade = 0xA42F44; int chuvaBug = 0xBDC994; int chuvaBalas = 0xBCF820; int wallCarroUpd = 0x2A6C9B4; int wallCarro = 0x21D19E4; int modonoite = 0x1A2280; int antenaCorpo = 0x2A3454; int corpoGrande = 0xA41BD0; int zePedrinha = 0xEF2890; struct { float Fov_Aim = 0.998f; int semihs = 0; bool aimBotFov = false; bool aimScope = false; bool aimTiro = false; bool hs100 = false; bool ghost = false; bool hs70 = false; bool aimAgachado = false; bool aimBody = false; bool aimbotauto = true; bool teleKill = false; bool Paraquedas = false; bool aimVisibilidade = false; bool AlertWorld = false; bool AlertAround = false; bool Angle = false; bool espDistance = false; bool espName = false; bool espNames = false; bool aimFire = false; bool espSkeleton = false; bool espCircle = false; bool espNear = false; bool isEspReady = false; bool closestEnemy = false; bool espFire = false; bool fakeName = false; bool sameteams = false; bool byFOV = false; bool aimTeste = false; bool aimTeste1 = false; bool aimTeste3 = false; bool medKit = false; int enemyCountAround = 0; int botCountAround = 0; int enemyCountWorld = 0; int botCountWorld = 0; } MT; bool active = true; bool launched = false; JNIEXPORT void JNICALL Java_com_mt_team_FloatingModMenuService_Joeliton( JNIEnv *env, jobject activityObject, jint feature, jint Value) { __android_log_print(ANDROID_LOG_VERBOSE, "Mod Menu", "Feature: = %d", feature); __android_log_print(ANDROID_LOG_VERBOSE, "Mod Menu", "Value: = %d", Value); // You must count your features from 0, not 1 <file_sep>/README.md # Free Fire ESP And Aimbot A customized LGL mod menu, containing ESP, aimbot, hooking, and patching codes for Free Fire Mod menu is based on my old template (August 2020) # Screenshot *Taken from random Youtube video, didn't bother testing it, but I know it works like this* ![](https://i.imgur.com/gHsr5Cx.png) # DISCLAIMER **WE SHARE THIS PROJECT FROM TELEGRAM FOR EDUCATIONAL PURPOSES ONLY. WE ENCOURAGE YOU TO NOT MOD IT BECAUSE THERE IS A RISK OF BANS ANYWAY. WE WILL NOT BE RESPONSABLE HOW YOU WILL USE IT.** **DON'T SELL THE SOURCE, AND DON'T GET SCAMMED.** <file_sep>/app/src/main/jni/src/KittyMemory/MemoryPatch.cpp #include "MemoryPatch.h" MemoryPatch::MemoryPatch() { _address = 0; _size = 0; _orig_code.clear(); _patch_code.clear(); } MemoryPatch::MemoryPatch(const char *libraryName, uintptr_t address, const void *patch_code, size_t patch_size) { MemoryPatch(); if (libraryName == NULL || address == 0 || patch_code == NULL || patch_size < 1) return; _address = KittyMemory::getAbsoluteAddress(libraryName, address); if(_address == 0) return; _size = patch_size; _orig_code.resize(patch_size); _patch_code.resize(patch_size); // initialize patch & backup current content KittyMemory::memRead(&_patch_code[0], patch_code, patch_size); KittyMemory::memRead(&_orig_code[0], reinterpret_cast<const void *>(_address), patch_size); } MemoryPatch::~MemoryPatch() { // clean up _orig_code.clear(); _patch_code.clear(); } bool MemoryPatch::isValid() const { return (_address != 0 && _size > 0 && _orig_code.size() == _size && _patch_code.size() == _size); } size_t MemoryPatch::get_PatchSize() const{ return _size; } uintptr_t MemoryPatch::get_TargetAddress() const{ return _address; } bool MemoryPatch::Restore() { if (!isValid()) return false; return KittyMemory::memWrite(reinterpret_cast<void *>(_address), &_orig_code[0], _size) == Memory_Status::SUCCESS; } bool MemoryPatch::Modify() { if (!isValid()) return false; return (KittyMemory::memWrite(reinterpret_cast<void *>(_address), &_patch_code[0], _size) == Memory_Status::SUCCESS); } std::string MemoryPatch::ToHexString() { if (!isValid()) return std::string("0xInvalid"); return KittyMemory::read2HexStr(reinterpret_cast<const void *>(_address), _size); }
17d927b6afdaa6ba4bb52bb8204b44fda7ef7e1d
[ "Markdown", "C", "C++" ]
7
C++
LGLTeam/FreeFire-ESP-And-Aimbot
d20bf52215d7b21d0af76add4a6d632b735e40da
1ff9f48a341264328e635cc54ab653db30ff9745
refs/heads/master
<repo_name>mrn-i/name_prediction<file_sep>/config.py import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False # Psycopg : Python adapter of PostgreSQSL database # Adapt Python types to PostgreSQSL types. # While doing so, database will be connected to the application. # This will occure into models.py. class ProductionConfig(Config): DEBUG = False SQLALCHEMY_TRACK_MODIFICATIONS = True class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): SQLALCHEMY_TRACK_MODIFICATIONS = True DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True <file_sep>/manage.py #!/usr/bin/env python3 import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from name_predict_app.views import app manager = Manager(app) if __name__ == '__main__': manager.run() <file_sep>/name_predict_app/views.py #!/usr/bin/env python3 from flask import Flask, render_template, url_for, request import os import pandas as pd import numpy as np def get_enriched_description(character): character_enriched = [] for i in range(0,len(character)): character_enriched return character_enriched def get_jaccard_sim(str1, str2): a = set(str1.replace(",","").split()) b = set(str2.replace(",","").split()) c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c)) def name_predict_model(is_boy, is_girl, characters): df = pd.read_csv("name_predict_app/data/names_database_clean_v1.csv") if (is_boy == False) & (is_girl == True): df = df.loc[df.gender == 'girl'] if (is_boy == True) & (is_girl == False): df = df.loc[df.gender == 'boy'] df_traits = pd.read_csv("name_predict_app/data/traits_database_v1.csv") user_input = '' for trait_id in characters: user_input = user_input + df_traits["traits_enriched_stemmed"].iloc[trait_id] + " " result = pd.DataFrame(df[["name", "meaning", "bullshit_reduced"]], columns=["name", "meaning", "bullshit_reduced", "jaccard_similarity"]) result["jaccard_similarity"] = df["adj_and_nouns_enriched_stemmed"].apply(lambda x: get_jaccard_sim(x, user_input)) result = result.sort_values(by=["jaccard_similarity"], ascending=False)[:15] result = result.reset_index() random_result_index = [] while len(random_result_index) < 3: r = np.random.randint(0, 15) if r not in random_result_index: random_result_index.append(r) result = result.iloc[random_result_index] result = result.reset_index() return result os.environ["APP_SETTINGS"] = "config.ProductionConfig" app = Flask(__name__) app.config.from_object(os.environ["APP_SETTINGS"]) app.secret_key = 'development key' # Flask_WTform CSFR protection from .templates.includes.forms import Choose_Character_Form @app.route("/", methods=('GET', 'POST')) def index(): form = Choose_Character_Form() if request.method == "POST": keylist = [("trait" + str(x)) for x in range(0, 5)] characters = [int(form.data[x]) for x in keylist] is_boy = form.data["boy"] is_girl = form.data["girl"] #print(characters) #print(is_boy) #print(is_girl) names = name_predict_model(is_boy, is_girl, characters) print(names) return render_template("name_prediction.html", predictions = names) return render_template("index.html", form = form) @app.route("/essai") def index2(): form = Choose_Character_Form() if request.method == "POST": keylist = [("trait" + str(x)) for x in range(0,5)] characters = [int(form.data[x]) for x in keylist] is_boy = form.data["boy"] is_girl = form.data["girl"] print(int(form.data[trait4])) print(type(int(form.data[trait4]))) print(characters) print(is_boy) print(is_girl) return render_template("index.html", form = form) return render_template("index.html", form = form) @app.route("/about") def about(): return render_template("about.html") @app.route("/contact") def contact(): return render_template("contact.html") @app.route("/test1", methods=('GET', 'POST')) def test1(): form = AnswerForms() if request.method == "POST": keylist = [("word" + str(x)) for x in range(1,15)] student_answers = [form.data[x] for x in keylist] result = SaveTest( nom=str(dict(request.form)["nom"]), prenom=str(dict(request.form)["prenom"]), groupe=str(dict(request.form)["groupe"]), answer=[form.data[x] for x in keylist], exercice = 'Synthese 2A' ) db.session.add(result) db.session.commit() app.logger.info(result.id) return render_template("answer1.html", prop = student_answers) else : return render_template("test1.html", form = form) <file_sep>/name_predict_app/templates/includes/forms.py from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField, IntegerField, DateField, SelectField, FieldList from wtforms.validators import DataRequired, InputRequired traitlist = [(0, 'Active'), (1, 'Friendly'), (2, 'Creative'), (3, 'Clever'), (4, 'Self-Assured'), (5, 'Attractive'), (6, 'Perfectionist'), (7, 'Ambitious'), (8, 'Self-Aware'), (9, 'Open-minded'), (10, 'Empathic'), (11, 'Adaptable')] class Choose_Character_Form(FlaskForm): boy = BooleanField(render_kw={ "class":"form-check-input"}) girl = BooleanField(render_kw={"type":"checkbox"}) trait0 = SelectField('Characteristic 1', choices=traitlist, render_kw={"placeholder": "Choose", "class":"form-control"}) trait1 = SelectField('Characteristic 2', choices=traitlist, render_kw={"placeholder": "Choose", "class":"form-control"}) trait2 = SelectField('Characteristic 3', choices=traitlist, render_kw={"placeholder": "Choose", "class":"form-control"}) trait3 = SelectField('Characteristic 4', choices=traitlist, render_kw={"placeholder": "Choose", "class":"form-control"}) trait4 = SelectField('Characteristic 5', choices=traitlist, render_kw={"placeholder": "Choose", "class":"form-control"}) submit = SubmitField("Find name", render_kw={"class":"gradient-button gradient-button-1"})
dd1a42e68f8c8445f5c0c1926760ee99b9ad3bda
[ "Python" ]
4
Python
mrn-i/name_prediction
3486871ab5e6da95311308216a54258600b45c26
07e6f6f2b9ba537a022699273a602a1645b26cdd
refs/heads/master
<repo_name>retgits/lambda-util<file_sep>/s3_test.go // Package util implements utility methods package util import ( "fmt" "os" "path/filepath" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) var ( // The region used to test AWSREGION = os.Getenv("AWSREGION") // The bucket to use AWSBUCKET = os.Getenv("AWSBUCKET") // The directory containing testdata TESTDATADIR = os.Getenv("TESTDATADIR") ) // The test suite for the S3 code type S3TestSuite struct { suite.Suite awsSession *session.Session testDir string } // The SetupSuite method will be run by testify once, at the very // start of the testing suite, before any tests are run. func (suite *S3TestSuite) SetupSuite() { // Create an AWS session awsAccessKeyID := os.Getenv("AWSACCESSKEYID") awsSecretAccessKey := os.Getenv("AWSSECRETACCESSKEY") if len(awsAccessKeyID) == 0 && len(awsSecretAccessKey) == 0 { suite.awsSession = session.Must(session.NewSession(&aws.Config{ Region: aws.String(AWSREGION), })) } else { awsCredentials := credentials.NewStaticCredentials(awsAccessKeyID, awsSecretAccessKey, "") suite.awsSession = session.Must(session.NewSession(&aws.Config{ Region: aws.String(AWSREGION), Credentials: awsCredentials, })) } suite.testDir = TESTDATADIR } // The TearDownSuite method will be run by testify once, at the very // end of the testing suite, after all tests are run. func (suite *S3TestSuite) TearDownSuite() { os.RemoveAll(filepath.Join(suite.testDir)) s3Session := s3.New(suite.awsSession) s3Session.DeleteObject(&s3.DeleteObjectInput{Bucket: aws.String(AWSBUCKET), Key: aws.String("helloworld.txt")}) } func (suite *S3TestSuite) TestUploadNotExistingFile() { err := UploadFile(suite.awsSession, filepath.Join(suite.testDir, "downloads"), "notexistingfile.txt", AWSBUCKET) assert.Error(suite.T(), err) } func (suite *S3TestSuite) TestUploadExistingFile() { err := UploadFile(suite.awsSession, suite.testDir, "helloworld.txt", AWSBUCKET) assert.NoError(suite.T(), err) s3Session := s3.New(suite.awsSession) output, err := s3Session.ListObjects(&s3.ListObjectsInput{Bucket: aws.String(AWSBUCKET)}) fmt.Println("---") for _, val := range output.Contents { fmt.Println(val.Key) } assert.NoError(suite.T(), err) assert.Equal(suite.T(), "helloworld.txt", *output.Contents[0].Key) } func (suite *S3TestSuite) TestDownloadNotExistingFile() { err := DownloadFile(suite.awsSession, filepath.Join(suite.testDir, "downloads"), "notexistingfile.txt", AWSBUCKET) assert.Error(suite.T(), err) } func (suite *S3TestSuite) TestDownloadExistingFile() { suite.TestUploadExistingFile() err := DownloadFile(suite.awsSession, filepath.Join(suite.testDir, "downloads"), "helloworld.txt", AWSBUCKET) assert.NoError(suite.T(), err) } func (suite *S3TestSuite) TestCopyNotExistingFile() { err := CopyFile(suite.awsSession, "notexistingfile.txt", AWSBUCKET) assert.Error(suite.T(), err) } func (suite *S3TestSuite) TestCopyExistingFile() { suite.TestUploadExistingFile() err := CopyFile(suite.awsSession, "helloworld.txt", AWSBUCKET) assert.NoError(suite.T(), err) } // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run func TestS3TestSuite(t *testing.T) { suite.Run(t, new(S3TestSuite)) } <file_sep>/Makefile .PHONY: install test prep deps #--- Variables --- AWSREGION= AWSBUCKET= VALIDEMAIL= #--- Help --- help: @echo @echo Makefile targets @grep -E '^[a-zA-Z_-]+:.*?## .*$$' Makefile | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' @echo #--- Setup targets --- prep: ## Make preparations to run the tests mkdir -p ./testdata/downloads echo "Hello World!" > ./testdata/helloworld.txt #--- Test targets --- test: prep ## Run all testcases export TESTDATADIR=`pwd`/testdata && export AWSREGION=${AWSREGION} && export AWSBUCKET=${AWSBUCKET} && export VALIDEMAIL=${VALIDEMAIL} && go test -coverprofile cover.out ./... go tool cover -html=cover.out -o cover.html && open cover.html<file_sep>/s3.go // Package util implements utility methods package util // The imports import ( "fmt" "os" "path/filepath" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) // DownloadFile downloads a file from Amazon S3 and stores it in the specified location. func DownloadFile(awsSession *session.Session, folder string, filename string, bucket string) error { // Create an instance of the S3 Downloader s3Downloader := s3manager.NewDownloader(awsSession) // Create a new temporary file tempFile, err := os.Create(filepath.Join(folder, filename)) if err != nil { return err } // Prepare the download objectInput := &s3.GetObjectInput{ Bucket: aws.String(bucket), Key: aws.String(filename), } // Download the file to disk _, err = s3Downloader.Download(tempFile, objectInput) if err != nil { os.Remove(filepath.Join(folder, filename)) return err } return nil } // CopyFile creates a copy of an existing file with a new name func CopyFile(awsSession *session.Session, filename string, bucket string) error { // Create an instance of the S3 Session s3Session := s3.New(awsSession) // Prepare the copy object objectInput := &s3.CopyObjectInput{ Bucket: aws.String(bucket), CopySource: aws.String(fmt.Sprintf("/%s/%s", bucket, filename)), Key: aws.String(fmt.Sprintf("%s_bak", filename)), } // Copy the object _, err := s3Session.CopyObject(objectInput) if err != nil { return err } return nil } // UploadFile uploads a file to Amazon S3 func UploadFile(awsSession *session.Session, folder string, filename string, bucket string) error { // Create an instance of the S3 Uploader s3Uploader := s3manager.NewUploader(awsSession) // Create a file pointer to the source reader, err := os.Open(filepath.Join(folder, filename)) if err != nil { return err } defer reader.Close() // Prepare the upload uploadInput := &s3manager.UploadInput{ Bucket: aws.String(bucket), Key: aws.String(filename), Body: reader, } // Upload the file _, err = s3Uploader.Upload(uploadInput) if err != nil { return err } return nil } <file_sep>/http.go // Package util implements utility methods package util // The imports import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" ) // HTTPResponse is the response type for the HTTP requests type HTTPResponse struct { Body map[string]interface{} StatusCode int Headers http.Header } // HTTPPost executes a POST request to a URL and returns the response body as a JSON object func HTTPPost(URL string, encoding string, postData string, header http.Header) (HTTPResponse, error) { return httpcall(URL, "POST", encoding, postData, header) } // HTTPPatch executes a PATCH request to a URL and returns the response body as a JSON object func HTTPPatch(URL string, encoding string, postData string, header http.Header) (HTTPResponse, error) { return httpcall(URL, "PATCH", encoding, postData, header) } // HTTPGet executes a GET request to a URL and returns the response body as a JSON object func HTTPGet(URL string, encoding string, header http.Header) (HTTPResponse, error) { return httpcall(URL, "GET", encoding, "", header) } // httpcall executes an HTTP request request to a URL and returns the response body as a JSON object func httpcall(URL string, requestType string, encoding string, payload string, header http.Header) (HTTPResponse, error) { // Instantiate a response object httpresponse := HTTPResponse{} // Prepare placeholders for the request and the error object req := &http.Request{} var err error // Create a request if len(payload) > 0 { req, err = http.NewRequest(requestType, URL, strings.NewReader(payload)) if err != nil { return httpresponse, fmt.Errorf("error while creating HTTP request: %s", err.Error()) } } else { req, err = http.NewRequest(requestType, URL, nil) if err != nil { return httpresponse, fmt.Errorf("error while creating HTTP request: %s", err.Error()) } } // Associate the headers with the request if header != nil { req.Header = header } // Set the encoding if len(encoding) > 0 { req.Header["Content-Type"] = []string{encoding} } // Execute the HTTP request res, err := http.DefaultClient.Do(req) if err != nil { return httpresponse, fmt.Errorf("error while performing HTTP request: %s", err.Error()) } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { return httpresponse, err } httpresponse.Headers = res.Header httpresponse.StatusCode = res.StatusCode var data map[string]interface{} if err := json.Unmarshal(body, &data); err != nil { return httpresponse, fmt.Errorf("error while unmarshaling HTTP response to JSON: %s", err.Error()) } httpresponse.Body = data return httpresponse, nil } <file_sep>/http_test.go // Package util implements utility methods package util import ( "encoding/base64" "fmt" "io" "io/ioutil" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestHTTPGet(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { w.WriteHeader(http.StatusForbidden) } w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", r.Header["Content-Type"][0]) io.WriteString(w, `{"hello":"world"}`) })) defer ts.Close() resp, err := HTTPGet(ts.URL, "application/json", nil) assert.NoError(t, err) assert.Equal(t, resp.StatusCode, 200) } func TestHTTPPost(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { w.WriteHeader(http.StatusForbidden) } w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", r.Header["Content-Type"][0]) io.WriteString(w, `{"hello":"world"}`) })) defer ts.Close() resp, err := HTTPPost(ts.URL, "application/json", "", nil) assert.NoError(t, err) assert.Equal(t, resp.StatusCode, 200) } func TestHTTPPatch(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "PATCH" { w.WriteHeader(http.StatusForbidden) } w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", r.Header["Content-Type"][0]) io.WriteString(w, `{"hello":"world"}`) })) defer ts.Close() resp, err := HTTPPatch(ts.URL, "application/json", "", nil) assert.NoError(t, err) assert.Equal(t, resp.StatusCode, 200) } func TestHTTPGetWithHeader(t *testing.T) { basicAuthUserPass := "<PASSWORD>" basicAuthString := fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(basicAuthUserPass))) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header["Authorization"][0] != basicAuthString { w.WriteHeader(http.StatusForbidden) } else { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", r.Header["Content-Type"][0]) io.WriteString(w, `{"hello":"world"}`) } })) defer ts.Close() httpHeader := http.Header{"Authorization": {basicAuthString}} resp, err := HTTPGet(ts.URL, "application/json", httpHeader) assert.NoError(t, err) assert.Equal(t, resp.StatusCode, 200) httpHeader = http.Header{"Authorization": {"bla!"}} resp, err = HTTPGet(ts.URL, "application/json", httpHeader) assert.Error(t, err) assert.Equal(t, resp.StatusCode, 403) } func TestHTTPPostWithData(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body, _ := ioutil.ReadAll(r.Body) if r.Method != "POST" || len(string(body)) < 5 { w.WriteHeader(http.StatusForbidden) } w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", r.Header["Content-Type"][0]) io.WriteString(w, `{"hello":"world"}`) })) defer ts.Close() resp, err := HTTPPost(ts.URL, "application/json", `{"hello":"world"}`, nil) assert.NoError(t, err) assert.Equal(t, resp.StatusCode, 200) } <file_sep>/os_test.go // Package util implements utility methods package util import ( "testing" "github.com/stretchr/testify/assert" ) func TestGetEnvKeyExistingKey(t *testing.T) { result := GetEnvKey("PATH", "fallback") assert.NotEqual(t, result, "fallback") assert.NotEmpty(t, result) } func TestGetEnvKeyNonExistingKey(t *testing.T) { result := GetEnvKey("SOMEPATH", "fallback") assert.Equal(t, result, "fallback") assert.NotEmpty(t, result) } func TestGetCurrentDirectory(t *testing.T) { result, err := GetCurrentDirectory() assert.NotEmpty(t, result) assert.NoError(t, err) } <file_sep>/ssm_test.go // Package util implements utility methods package util import ( "os" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // The test suite for the S3 code type SSMTestSuite struct { suite.Suite awsSession *session.Session testDir string } // The SetupSuite method will be run by testify once, at the very // start of the testing suite, before any tests are run. func (suite *SSMTestSuite) SetupSuite() { // Create an AWS session awsAccessKeyID := os.Getenv("AWSACCESSKEYID") awsSecretAccessKey := os.Getenv("AWSSECRETACCESSKEY") if len(awsAccessKeyID) == 0 && len(awsSecretAccessKey) == 0 { suite.awsSession = session.Must(session.NewSession(&aws.Config{ Region: aws.String(AWSREGION), })) } else { awsCredentials := credentials.NewStaticCredentials(awsAccessKeyID, awsSecretAccessKey, "") suite.awsSession = session.Must(session.NewSession(&aws.Config{ Region: aws.String(AWSREGION), Credentials: awsCredentials, })) } } func (suite *SSMTestSuite) TestNotExistingParameter() { _, err := GetSSMParameter(suite.awsSession, "MyAwesomeParameter", true) assert.Error(suite.T(), err) } func (suite *SSMTestSuite) TestExistingParameter() { param, err := GetSSMParameter(suite.awsSession, "TestParamEncrypted", true) assert.NoError(suite.T(), err) assert.Equal(suite.T(), param, "HelloWorld") param, err = GetSSMParameter(suite.awsSession, "TestParamNotEncrypted", false) assert.NoError(suite.T(), err) assert.Equal(suite.T(), param, "HelloWorld") } // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run func TestSSMTestSuite(t *testing.T) { suite.Run(t, new(SSMTestSuite)) } <file_sep>/go.mod module github.com/retgits/lambda-util require ( github.com/aws/aws-sdk-go v1.15.42 github.com/davecgh/go-spew v1.1.1 // indirect github.com/go-ini/ini v1.25.5 // indirect github.com/gopherjs/gopherjs v0.0.0-20180825215210-0210a2f0f73c // indirect github.com/jtolds/gls v4.2.1+incompatible // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/smartystreets/assertions v0.0.0-20180820201707-7c9eb446e3cf // indirect github.com/smartystreets/goconvey v0.0.0-20180222194500-ef6db91d284a // indirect github.com/stretchr/testify v1.2.2 golang.org/x/net v0.0.0-20180925072008-f04abc6bdfa7 // indirect golang.org/x/text v0.3.0 // indirect ) <file_sep>/ses.go // Package util implements utility methods package util // The imports import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ses" ) // SendEmail sends an email using Simple Email Service. func SendEmail(awsSession *session.Session, toAddress string, bodyContent string, fromAddress string, subject string) error { // Create an instance of the SES Session sesSession := ses.New(awsSession) // Create the Email request sesEmailInput := &ses.SendEmailInput{ Destination: &ses.Destination{ ToAddresses: []*string{aws.String(toAddress)}, }, Message: &ses.Message{ Body: &ses.Body{ Text: &ses.Content{ Data: aws.String(bodyContent), }, }, Subject: &ses.Content{ Data: aws.String(subject), }, }, Source: aws.String(fromAddress), ReplyToAddresses: []*string{ aws.String(fromAddress), }, } // Send the email _, err := sesSession.SendEmail(sesEmailInput) return err } <file_sep>/os.go // Package util implements utility methods package util import ( "os" "path/filepath" ) // GetEnvKey tries to get the specified key from the OS environment and returns either the // value or the fallback that was provided func GetEnvKey(key string, fallback string) string { if value, ok := os.LookupEnv(key); ok { return value } return fallback } // GetCurrentDirectory gets the directory in which the app was started and returns either // the full directory or an error func GetCurrentDirectory() (string, error) { return filepath.Abs(filepath.Dir(os.Args[0])) } <file_sep>/README.md # lambda-util A collection of utility methods for my serverless apps ## Layout ```bash . ├── http.go <-- Utils to interact with HTTP requests ├── os.go <-- Utils to interact with the Operating System ├── s3.go <-- Utils to interact with Amazon S3 ├── ses.go <-- Utils to interact with Amazon Simple Email Service ├── ssm.go <-- Utils to interact with Amazon SSM ├── .gitignore <-- Ignoring the things you do not want in git ├── LICENSE <-- The license file └── README.md <-- This file ```
76dc1b0189c0d9f1a6393606fff6efb7f16b0aa7
[ "Makefile", "Go Module", "Go", "Markdown" ]
11
Go
retgits/lambda-util
5c9c71bf61bfef46248e8515b970de500df11e10
2d6bdda94353f1fbc0385b134eb95dccd98a78fe
refs/heads/master
<repo_name>marcofavorito/google-hashcode-2021<file_sep>/Pipfile [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] black = "==20.8b1" mypy = "*" isort = "*" flake8 = "*" pylint = "*" safety = "*" vulture = "*" bandit = "*" ipython = "*" jupyter = "*" flake8-docstrings = "*" flake8-bugbear = "*" flake8-eradicate = "*" flake8-isort = "*" [packages] numpy = "*" scipy = "*" pandas = "*" click = "*" [requires] python_version = "3.8" <file_sep>/hashcode/__init__.py # -*- coding: utf-8 -*- """A framework to participate in the Google Hash Code contest.""" from hashcode.loggers import setup_logger __version__ = "0.1.0" __name__ = "hashcode" setup_logger() <file_sep>/scripts/summary.sh #!/usr/bin/env bash count=0 echo "$(date)" > SUBMISSION echo "Algorithms used for the submission:" >> SUBMISSION for input in data/[a_,b_,c_,d_,e_,f_]*.txt; do test_name=$(echo $input | cut -d'/' -f 2 | cut -d'.' -f 1) echo "======================================================" echo "Processing input $input" echo "======================================================" python3 scripts/dataset_summary.py --in $input if [[ $? -ne 0 ]]; then exit 1; fi (( count++ )); done <file_sep>/hashcode/common/model.py # -*- coding: utf-8 -*- """Common classes to represent the problem.""" from dataclasses import dataclass from typing import List, Set, Tuple, FrozenSet, Dict @dataclass(frozen=True, repr=True, eq=True, unsafe_hash=True) class Street: name: str beginning: int end: int length: int @dataclass(frozen=True, repr=True, eq=True, unsafe_hash=True) class CarPath: streets: Tuple[Street] @property def nb_streets(self) -> int: return len(self.streets) @property def length(self) -> int: return sum([s.length for s in self.streets]) def __len__(self) -> int: return self.nb_streets @dataclass(frozen=True, repr=True, eq=True) class Schedule: intersection_id: int green_light_streets: Dict[Street, int] @dataclass(repr=True, eq=True, unsafe_hash=True) class Intersection: id: int in_streets: List[Street] out_streets: List[Street] <file_sep>/scripts/dataset_summary.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """Dataset summary.""" import argparse from collections import defaultdict from pathlib import Path from typing import Dict, List import numpy as np from hashcode.common.base import Input, read_input from hashcode.common.model import Street parser = argparse.ArgumentParser( "hashcode", description="CLI utility for Google Hash Code. " "It assumes the input provided in stdin.", ) parser.add_argument( "--in", dest="in_file", type=str, default=None, help="provide an input data file." ) args = parser.parse_args() def print_stats(data, label): """Print statistics.""" print("Avg {}: {}".format(label, np.mean(data))) print("Std {}: {}".format(label, np.std(data))) print("Max {}: {}".format(label, np.max(data))) print("Min {}: {}".format(label, np.min(data))) print("00th {}: {}".format(label, np.percentile(data, 0))) print("25th {}: {}".format(label, np.percentile(data, 25))) print("50th {}: {}".format(label, np.percentile(data, 50))) print("75th {}: {}".format(label, np.percentile(data, 75))) print("100th {}: {}".format(label, np.percentile(data, 100))) print("-" * 50) def print_intersection_stats(i: Input): nb_input_streets = [] nb_output_streets = [] for intersection_ in i.intersections.values(): nb_input_streets.append(len(intersection_.in_streets)) nb_output_streets.append(len(intersection_.out_streets)) print(f"Avg nb input streets in intersections: {np.mean(nb_input_streets)}") print(f"Std nb input streets in intersections: {np.std(nb_input_streets)}") print(f"Max nb input streets in intersections: {np.max(nb_input_streets)}") print(f"Min nb input streets in intersections: {np.min(nb_input_streets)}") print("*"*10) print(f"Avg nb output streets in intersections: {np.mean(nb_output_streets)}") print(f"Std nb output streets in intersections: {np.std(nb_output_streets)}") print(f"Max nb output streets in intersections: {np.max(nb_output_streets)}") print(f"Min nb output streets in intersections: {np.min(nb_output_streets)}") if __name__ == "__main__": input_: Input = read_input(Path(args.in_file).open()) print(f"Nb cars: {len(input_.paths)}") print(f"Nb streets: {len(input_.streets)}") print(f"Nb intersections: {input_.nb_intersections}") print(f"Duration: {input_.duration_seconds}") print(f"Bonus: {input_.bonus_points}") print("*"*10) print(f"Avg path length: {np.mean([p.length for p in input_.paths])}") print(f"Std path length: {np.std([p.length for p in input_.paths])}") print(f"Max path length: {np.max([p.length for p in input_.paths])}") print(f"Min path length: {np.min([p.length for p in input_.paths])}") print("*" * 10) print_intersection_stats(input_) <file_sep>/hashcode/solutions/weighted_scheduling.py # -*- coding: utf-8 -*- """A minimum working example.""" from collections import defaultdict from typing import List, Dict from hashcode.common.base import Input, Output from hashcode.common.model import Schedule, Street, CarPath, Intersection # schedules: List[Schedule] = [] # paths_sorted_by_length = sorted(i.paths, key=lambda p: len(p)) # street_to_cost: Dict[Street, int] = {s: s.length for s in i.streets} # def cost_of_path(p: CarPath) -> int: # return sum([s.length for s in p.streets]) # paths_sorted_by_cost = sorted(i.paths, key=cost_of_path) def main(i: Input) -> Output: """Minimum working algorithm.""" schedules: List[Schedule] = [] counts_in_streets_by_intersection_id: Dict[int, Dict[Street, int]] = defaultdict(lambda: defaultdict(lambda: 0)) counts_by_intersection: Dict[int, int] = defaultdict(lambda: 0) for path in i.paths: for street in path.streets: counts_in_streets_by_intersection_id[street.end][street] += 1 counts_by_intersection[street.end] += 1 for intersection_id, total_counts in counts_by_intersection.items(): count_by_streets: Dict[Street, int] = counts_in_streets_by_intersection_id[intersection_id] total_period_duration = len(count_by_streets) * 2 compute_time = lambda count: int(count * total_period_duration // total_counts) green_lights: Dict[Street, int] = {s: max(1, compute_time(c)) for s, c in count_by_streets.items()} # print("-"*100) # print(total_period_duration) # print(sorted(green_lights.values())) schedule = Schedule(intersection_id=intersection_id, green_light_streets=green_lights) schedules.append(schedule) return Output(tuple(schedules))<file_sep>/scripts/zipper.sh #!/usr/bin/env bash rm solution.zip zip -r solution.zip hashcode/* \ README.md \ Pipfile \ Pipfile.lock \ .gitignore \ LICENSE \ zipper.sh \ scripts/* \ SUBMISSION \ setup.py \ data/.gitkeep \ out/.gitkeep \ -x *__pycache__* *.pyc <file_sep>/hashcode/solutions/weight_by_traffic.py # -*- coding: utf-8 -*- """All lights, 1 second.""" from typing import List from hashcode.common.model import Schedule from hashcode.common.base import Input, Output def main(i: Input) -> Output: """All lights, 1 second.""" schedules: List[Schedule] = [] used_streets = {} for path in i.paths: for street in path.streets: if street.name not in used_streets: used_streets[street.name] = 0 used_streets[street.name] += 1 for intersection_id, intersection in i.intersections.items(): green_lights = {} intersection_traffic = 0 min_traffic = 1_000_000 for street in intersection.in_streets: if street.name in used_streets: traffic = used_streets[street.name] min_traffic = min(min_traffic, traffic) intersection_traffic += traffic if intersection_traffic == 0: continue alpha = min_traffic / intersection_traffic for street in intersection.in_streets: if street.name in used_streets and used_streets[street.name] > 0: green_lights[street] = max(1, int(used_streets[street.name] * alpha)) if green_lights: schedule = Schedule(intersection_id=intersection_id, green_light_streets=green_lights) schedules.append(schedule) return Output(schedule=schedules)<file_sep>/hashcode/solutions/__init__.py # -*- coding: utf-8 -*- """ This package contains the solutions for Google HashCode. In this framework, a solution module is a Python module that contains a 'main' function that takes as unique argument an Input instance and gives an Output instance. The "hashcode" CLI tool will dynamically load these modules and make them available as choices. """ <file_sep>/hashcode/loggers.py # -*- coding: utf-8 -*- """This module contains utilities to set up loggers.""" import logging import hashcode _DEFAULT_LOG_FORMAT = "[%(asctime)s][%(name)s][%(funcName)s][%(levelname)s] %(message)s" def setup_logger(): """Set up the default logger.""" logger = logging.getLogger(hashcode.__name__) logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() formatter = logging.Formatter(_DEFAULT_LOG_FORMAT) handler.setFormatter(formatter) logger.addHandler(handler) <file_sep>/README.md # google-hashcode-2021 A framework to participate in the Google Hash Code contest. ## TL;DR When the problem specifications will be announced: - Put the input problems in `data/` as `.in` files; - Implement the stubs in `hashcode/common/base.py` - Put your solutions as Python modules in `hashcode/solutions` (one module for each solution). - Run `scripts/run.sh` to produce: - output files in `outputs/` - `solution.zip` to submit. - a `SUBMISSION` file that contains details on the solutions found. ## Usage - Clone the repo: ``` git clone https://github.com/marcofavorito/google-hashcode-2021.git ``` - Create the virtual environment. It requires [Pipenv](https://pipenv.readthedocs.io/en/latest/): ``` pipenv shell --python=python3.7 ``` - Install the dependencies and the package: ``` pipenv install --dev pip install -e . ``` - Usage of the main entrypoint: ``` python -m hashcode --alg ${ALGORITHM} < input_file > output_file ``` It expects input in `stdin` and prints output in `stdout`. - To compute the solutions for every data in `data/*.in`: ``` ./scripts/run.sh ${ALGORITHM} ``` Details about the submission in the `SUBMISSION` file, generated by the `run.sh` script. It will provide details about the chosen algorithm `alg`, which will correspond to the module::function `hashcode/sol/${alg}::main` ## Linters The `Makefile` provides several commands to run linters and code formatters. The most useful command is `make lint-all`: ``` make lint-all ``` It will run `black`, `isort`, and other lint checkers like `flake8` and `mypy` after that. You can also run them separately: ``` make black make isort make flake8 make static make bandit make safety make vulture make pylint ``` <file_sep>/hashcode/common/__init__.py # -*- coding: utf-8 -*- """Main functions and classes to handle a problem instance.""" <file_sep>/hashcode/solutions/zero.py # -*- coding: utf-8 -*- """A minimum working example.""" from hashcode.common.base import Input, Output def main(i: Input) -> Output: """Minimum working algorithm.""" return Output() <file_sep>/hashcode/__main__.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Main entrypoint of the framework. To print the usage: python -m hashcode --help """ import inspect import logging import os import re import sys from pathlib import Path import click from hashcode.common.base import Input, Output, read_input, score, write_output from hashcode.common.core import Solution logger = logging.getLogger("hashcode") PACKAGE_DIRECTORY = os.path.dirname(inspect.getfile(inspect.currentframe())) # type: ignore ALGORITHMS = sorted( [ s.stem for s in Path(PACKAGE_DIRECTORY + "/solutions").iterdir() if re.match("[^_].+.py", s.name) ] ) @click.command("hashcode", help="CLI util for Google Hash Code <year>.") @click.option( "--alg", required=True, type=click.Choice(ALGORITHMS), help="The algorithm to use for computing the solution.", ) @click.option( "-i", "--in_", default=None, type=click.Path(exists=True, dir_okay=False, readable=True), help="Provide an input data file. Defaults to stdin", ) @click.option( "-o", "--out", default=None, type=click.Path(exists=False, dir_okay=False, writable=True), help="Provide an output data file. Defaults to stdout", ) @click.option( "-s", default=False, type=bool, help="Whether to print the score or not.", ) def main(alg: str, in_, out, s): """Run a solution against a problem instance.""" input_stream = Path(in_).open() if in_ else sys.stdin output_stream = Path(out).open("w") if out else sys.stdout solution = Solution(alg) logger.debug(f"Chosen algorithm: {alg}") input_: Input = read_input(input_stream) output: Output = solution.main(input_) if s: solution_score = score(input_, output) logger.debug(f"Score of the solution: {solution_score}") write_output(output, output_stream) if __name__ == "__main__": main() <file_sep>/hashcode/common/core.py # -*- coding: utf-8 -*- """Core module of the framework.""" import importlib from hashcode.common.base import Input, Output class Solution: """ This class acts as a wrapper for solution modules in 'hashcode/solutions'. It dynamically imports the module and ensures that the solution module contains a 'main' function. """ def __init__(self, module_name: str): """ Initialize the solution wrapper. :param module_name: name of the module. """ self._module_name = module_name self._module_dotted_path = f"hashcode.solutions.{module_name}" self.module = importlib.import_module(self._module_dotted_path) self._check_consistency() def main(self, i: Input) -> Output: """Run the solution on an Input and produce an Output.""" output = self.module.main(i) # type: ignore return output def _check_consistency(self): """Check the consistency of the dynamically loaded module.""" fun = getattr(self.module, "main", None) is_callable = callable(fun) if fun else False if not is_callable: raise ValueError( f"Module {self._module_dotted_path} does not have a callable named 'main'." ) <file_sep>/scripts/run.sh #!/usr/bin/env bash if [ "$#" -ne 1 ] && [ "$#" -ne 6 ]; then echo "Illegal number of parameters."; echo "Usage: $0 [ ALG | ALG_A ALG_B ALG_C ALG_D ALG_E ]"; exit 1; fi if [ "$#" == 1 ]; then ALGS=("$1" "$1" "$1" "$1" "$1" "$1"); else ALGS=("$1" "$2" "$3" "$4" "$5" "$6"); fi count=0 echo "$(date)" > SUBMISSION echo "Algorithms used for the submission:" >> SUBMISSION for input in data/[a_,b_,c_,d_,e_,f_]*.txt; do test_name=$(echo $input | cut -d'/' -f 2 | cut -d'.' -f 1) echo "- $test_name: ${ALGS[$count]}" >&1 | tee -a SUBMISSION output_filename="outputs/${test_name}.out" echo "Processing input $input, writing output in $output_filename" python3 -m hashcode --alg ${ALGS[$count]} < $input > $output_filename if [[ $? -ne 0 ]]; then exit 1; fi (( count++ )); done echo "Zipping the solution..." ./scripts/zipper.sh #echo "The scores are:" >&1 | tee -a SUBMISSION; #total_score=0; #for f in $(find ./data/*.txt -printf "%f\n" | cut -d'.' -f1); #do # partial_score=$(./scripts/scorer --in data/$f.txt --solution out/$f.out) # total_score=$(echo "$total_score + $partial_score" | bc) # echo "- $f: $partial_score" >&1 | tee -a SUBMISSION #done echo "The total score of the submission is: ${total_score}" >&1 | tee -a SUBMISSION echo "You can find a summary in the SUBMISSION file."<file_sep>/scripts/scorer #!/usr/bin/env python3 import argparse from hashcode.common.base import Input, Output, read_input, read_output, score parser = argparse.ArgumentParser("scorer", description="Score an Hash Code solution.") parser.add_argument("--in", dest="in_file", type=str, required=True, help="Filename for the input.") parser.add_argument("--solution", dest="solution_file", type=str, required=True, help="The associated output.") def main(): args = parser.parse_args() i: Input = read_input(args.in_file) o: Output = read_output(args.solution_file) print(score(i, o)) if __name__ == '__main__': main() <file_sep>/hashcode/solutions/unused_streets_1_sec.py # -*- coding: utf-8 -*- """All lights, 1 second.""" from typing import List from hashcode.common.model import Schedule from hashcode.common.base import Input, Output def main(i: Input) -> Output: """All lights, 1 second.""" schedules: List[Schedule] = [] used_streets = set() for path in i.paths: for street in path.streets: used_streets.add(street.name) for intersection_id, intersection in i.intersections.items(): green_lights = {} for street in intersection.in_streets: if street.name in used_streets: green_lights[street] = 1 if green_lights: schedule = Schedule(intersection_id=intersection_id, green_light_streets=green_lights) schedules.append(schedule) return Output(schedule=schedules)<file_sep>/hashcode/solutions/weighted_by_most_promising.py # -*- coding: utf-8 -*- """A minimum working example.""" from collections import defaultdict from functools import partial from typing import List, Dict, Tuple from hashcode.common.base import Input, Output from hashcode.common.model import Schedule, Street, CarPath, Intersection def optimal_score_(p: CarPath, duration: int = -1, bonus: int = -1) -> int: T = sum([s.length for s in p.streets]) return bonus + (duration - T) def main(i: Input) -> Output: """Minimum working algorithm.""" schedules: List[Schedule] = [] optimal_score = partial(optimal_score_, duration=i.duration_seconds, bonus=i.bonus_points) path_and_scores: List[Tuple[CarPath, int]] = [(p, optimal_score(p)) for p in i.paths] path_and_scores = sorted(path_and_scores, key=lambda x: x[1], reverse=True) counts_in_streets_by_intersection_id: Dict[int, Dict[Street, int]] = defaultdict(lambda: defaultdict(lambda: 0)) counts_by_intersection: Dict[int, int] = defaultdict(lambda: 0) for path, score in path_and_scores: for street in path.streets: counts_in_streets_by_intersection_id[street.end][street] += score for intersection_id, score_by_street in counts_in_streets_by_intersection_id.items(): total_period_duration = len(score_by_street) * 2 total_score = sum(score_by_street.values()) compute_time = lambda count: int(count * total_period_duration // total_score) green_lights: Dict[Street, int] = {s: max(1, compute_time(c)) for s, c in score_by_street.items()} print("-"*100) print(total_period_duration) print(sorted(green_lights.values())) schedule = Schedule(intersection_id=intersection_id, green_light_streets=green_lights) schedules.append(schedule) return Output(tuple(schedules))<file_sep>/scripts/whitelist.py # type: ignore o # unused variable (hashcode/common/base.py:38) write_input # unused function (hashcode/common/base.py:59) obj # unused variable (hashcode/common/base.py:59) read_output # unused function (hashcode/common/base.py:70) obj # unused variable (hashcode/common/base.py:80) _._module_name # unused attribute (hashcode/common/core.py:22) <file_sep>/hashcode/common/base.py # -*- coding: utf-8 -*- """ Main functions and classes to handle a problem instance. This module contains: - Input class: to handle the input of a problem instance. - Output class: to handle the output of the algorithm given an input. - score function: takes as parameters an Input and an Output, and gives the score. - (read|write)_(input|output): to read/write from/to file an Input/Output object. The definitions of classes and function should be considered stubs to be implemented for the actual problem. """ import sys from dataclasses import dataclass from typing import TextIO, Set, List, Tuple, Dict from hashcode.common.model import Intersection, Street, CarPath, Schedule @dataclass class Input: """This data class manages the input of the problem.""" duration_seconds: int nb_intersections: int nb_cars: int bonus_points: int streets: Set[Street] paths: Set[CarPath] intersections: Dict[int, Intersection] def __post_init__(self): """Post-initialization.""" @dataclass(frozen=True) class Output: """This data class manages the output of the problem.""" schedule: Tuple[Schedule] = tuple() @property def nb_intersections(self): return len(self.schedule) def __post_init__(self): """Post-initialization.""" def score(i: Input, o: Output) -> int: """ Score the solution. :param i: the Input object. :param o: the Output object. :return: the score. """ raise NotImplementedError def read_input(input_stream: TextIO = sys.stdin) -> Input: """ Parse an Input object from a text stream. :param input_stream: the input text stream. :return: an Input object """ lines = [l.strip() for l in input_stream.readlines()] D, I, S, V, F = list(map(int, lines[0].split())) offset = 1 streets: Dict[Street] = {} for street_line in lines[offset: offset + S]: b, e, street_name, l = street_line.split() beginning = int(b) end = int(e) length = int(l) street = Street(street_name, beginning, end, length) streets[street_name] = street offset += S paths = [] for path in lines[offset: offset + V]: tokens = path.split() street_names = tokens[1:] path_streets = [streets[street_name] for street_name in street_names] paths.append(CarPath(path_streets)) intersections = {} for street_name, street in streets.items(): if street.beginning not in intersections: intersections[street.beginning] = Intersection(id=street.beginning, in_streets=[], out_streets=[]) if street.end not in intersections: intersections[street.end] = Intersection(id=street.end, in_streets=[], out_streets=[]) start_intersection = intersections[street.beginning] start_intersection.out_streets.append(street) end_intersection = intersections[street.end] end_intersection.in_streets.append(street) return Input(duration_seconds=D, nb_intersections=I, nb_cars=V, bonus_points=F, streets=list(streets.values()), paths=paths, intersections=intersections) def write_input(obj: Input, output_stream: TextIO = sys.stdout) -> None: """ Dump an Input object to an output stream. :param obj: the object to dump. :param output_stream: the output stream. :return: None """ raise NotImplementedError def read_output(input_stream: TextIO = sys.stdin) -> Output: """ Parse a text stream to produce an Output object. :param input_stream: the input text stream. :return: an Output object. """ raise NotImplementedError def write_output(obj: Output, output_stream: TextIO = sys.stdout) -> None: """ Dump an Output object to an output stream. :param obj: the Output object. :param output_stream: the output text stream. :return: None """ lines = [] lines.append(str(obj.nb_intersections)) for schedule in obj.schedule: lines.append(str(schedule.intersection_id)) nb_incoming_streets = len(schedule.green_light_streets) lines.append(str(nb_incoming_streets)) for street, seconds in schedule.green_light_streets.items(): lines.append(f"{street.name} {seconds}") output_stream.writelines('\n'.join(lines))<file_sep>/hashcode/solutions/naive.py # -*- coding: utf-8 -*- """A naive solution.""" from hashcode.common.base import Input, Output def main(i: Input) -> Output: """Naive solution."""
a13eaa892661697b585023e3825db7ab26c2ae40
[ "TOML", "Python", "Markdown", "Shell" ]
22
TOML
marcofavorito/google-hashcode-2021
d12ea986343d27bf531247e7e70e6bea030116fd
e315628293be65f911905e7c041c485431821d4f
refs/heads/master
<repo_name>dewabe/Jokipo-Veikkaus<file_sep>/jokipo/views.py # -*- coding: utf-8 -*- from flask import render_template, session, redirect, url_for, flash, request from main import app, login_manager, mail, auth import forms, database, common from flask.ext.bootstrap import Bootstrap from flask.ext.login import login_required, login_user, logout_user, current_user from flask.ext.mail import Message from threading import Thread bootstrap = Bootstrap(app) # Main menu items and settings main_menu = [ { 'id' : common.MainMenuID.MAIN, 'text' : u'Etusivu', 'link' : '/' }, { 'id' : common.MainMenuID.MATCHES, 'text' : u'Ottelut', 'link' : '/matches' }, { 'id' : common.MainMenuID.RANKING, 'text' : u'Ranking', 'link' : '/ranking' }, { 'id' : common.MainMenuID.MYPAGE, 'text' : u'Omasivu', 'link' : '/mypage' } ] # Submenu items and settings subpages = { common.MainMenuID.MYPAGE : { 'default' : { 'id' : None, 'text' : u'Tiedot', 'link' : '/mypage' } }, common.MainMenuID.MATCHES : { 'default' : { 'id' : None, 'text' : u'Kalenteri', 'link' : '/matches' }, 'list' : { 'id' : 'list', 'text' : u'Kaikki ottelut', 'link' : '/matches/list' } } } def send_async_email(app, msg): with app.app_context(): mail.send(msg) def send_email(to, subject, template, **kwargs): msg = Message( app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject, sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) thr = Thread(target=send_async_email, args=[app, msg]) thr.start() return thr @app.route('/') def index(): return render_template( 'index.html', main_menu_id=common.MainMenuID.MAIN, main_menu=main_menu, sub_menu=False, form=forms.Login(), rules=common.Points() ) @app.route('/user_login') def user_login(): return render_template( 'login.html', main_menu_id=common.MainMenuID.MAIN, main_menu=main_menu, sub_menu=False, form=forms.Login(), token=request.args.get('next') ) @app.route('/register', methods=['GET', 'POST']) def register(): form = forms.Register() if form.validate_on_submit(): username = form.name.data password = form.password.data email = form.email.data new_user = database.add_user(username, password, email) if new_user: flash(u'Käyttäjä lisätty! Vahvista vielä saamasi sähköpostin mukaisesti.') token = new_user.generate_confirmation_token() send_email( new_user.email, 'Vahvista rekisteröinti', 'mail/confirm', user=new_user, token=token) else: flash(u'Käyttäjätunnus ja/tai sähköposti on jo käytössä!') form.name.data = form.password.data = form.email.data = None elif request.method == 'POST': flash(u'Täytä kaikki tiedot!') return render_template( 'register.html', main_menu_id=common.MainMenuID.REGISTER, main_menu=main_menu, sub_menu=False, form=form ) @app.route('/confirm/<token>') @login_required def confirm(token): _confirm(token) def _confirm(token, user=None): if user: this_user = user else: this_user = current_user this_user.confirm(token) @app.route('/login', methods=['GET', 'POST']) def login(): form = forms.Login() if form.validate_on_submit(): token = form.token.data email = form.email.data password = form.password.data user = database.validate_user(email, password) if user: if token: _confirm(token.split('/')[2], user=user) if not user.confirmed: flash(u'Ei aktivoitu. Tarkista sähköposti.') else: login_user(user, form.remember_me.data) else: flash(u'Käyttäjätunnus tai salasana väärin') return redirect(url_for('index')) @app.route("/logout") @login_required def logout(): logout_user() return redirect(url_for('login')) @app.route('/mypage', methods=['GET', 'POST']) @app.route('/mypage/<subpage_id>') @login_required def my_page(subpage_id='default'): sub_menu = subpages[common.MainMenuID.MYPAGE] template = sub_menu[subpage_id]['link'] form = forms.ChangePassword() if form.validate_on_submit(): current_pw = form.current_pw.data new_pw = form.new_pw.data new_pw_confirm = form.new_pw_confirm.data if new_pw != new_pw_confirm: flash(u'Salasanan vaihto ei onnistunut.') elif current_user.check_password(current_pw): current_user.set_password(<PASSWORD>) database.db.session.add(current_user) database.db.session.commit() flash(u'Salasana muutettu') else: flash(u'Salasanan vaihto ei onnistunut.') return render_template( 'auth'+template+'.html', main_menu_id=common.MainMenuID.MYPAGE, main_menu=main_menu, sub_menu_id=subpage_id, sub_menu=sub_menu, form=form ) @app.route('/ranking') @login_required def ranking(): return render_template( 'auth/ranking.html', main_menu_id=common.MainMenuID.RANKING, main_menu=main_menu, ranking=database.get_ranking() ) @app.route('/matches') @app.route('/matches/<int:year>/<int:month>') @login_required def matches(year=None, month=None, subpage_id='default', filter=None): sub_menu = subpages[common.MainMenuID.MATCHES] template = sub_menu[subpage_id]['link'] if not year: year = common.timestamp().year if not month: month = common.timestamp().month return render_template( 'auth'+template+'.html', main_menu_id=common.MainMenuID.MATCHES, main_menu=main_menu, sub_menu_id=subpage_id, sub_menu=sub_menu, special=common.generate_calendar(year, month), form=None ) @app.route('/matches/list') @app.route('/matches/list/<int:team_id>') @login_required def matches_list(team_id=None): sub_menu = subpages[common.MainMenuID.MATCHES] if team_id: special = (database.get_teams(), database.get_matches_by_team(team_id)) else: special = (database.get_teams(), database.get_matches(0)) return render_template( 'auth/matches/list.html', main_menu_id=common.MainMenuID.MATCHES, main_menu=main_menu, sub_menu_id='list', sub_menu=sub_menu, special=special, form=None ) @app.route('/matches/match/<int:match_id>', methods=['POST', 'GET']) @login_required def single_match(match_id): sub_menu = subpages[common.MainMenuID.MATCHES] match = database.get_match(match_id) form = forms.Bet( match.match_id, match.home_team.team_id, match.away_team.team_id ) if form.validate_on_submit(): match_id = form.match_id.data home_goals = form.home_goals.data away_goals = form.away_goals.data if (common.timestamp() < match.match_time): database.add_bet(match_id, current_user.id, home_goals, away_goals) else: flash(u'Et voi enää veikata tätä ottelua!') return render_template( 'auth/match.html', main_menu_id=common.MainMenuID.MATCHES, main_menu=main_menu, sub_menu_id='default', sub_menu=sub_menu, match=match, allbets=database.get_all_bets(match_id), mybet=database.get_bet(match_id, current_user.id), form=form ) @app.route('/teams') def teams(): user = database.get_user(session.get("logged_username")) return render_template( 'teams.html', title='Joukkueet', teams=database.get_teams(), user=user ) @app.route('/write_my_bet', methods=['GET', 'POST']) def write_by_bet(): form = forms.Bet() user = database.get_user(session.get('logged_username')) if form.validate_on_submit(): match_id = form.match_id.data if (common.timestamp() > database.get_match(match_id).match_time): pass else: home_goals = form.home_goals.data away_goals = form.away_goals.data database.add_bet(match_id, user.id, home_goals, away_goals) return redirect(url_for('matches')) @app.route('/bet/<int:id>', methods=['GET', 'POST']) def bet(id): user = database.get_user(session.get('logged_username')) match=database.get_match(id) form = forms.Bet(id, match.home_team_id, match.away_team_id) match_id = None home_goals = None away_goals = None error = None if form.validate_on_submit(): if (common.timestamp() > match.match_time): error = 'Tapahtui virhe' else: match_id = form.match_id.data home_goals = form.home_goals.data away_goals = form.away_goals.data database.add_bet(match_id, user.id, home_goals, away_goals) return redirect(url_for('mybets')) return render_template( 'bet.html', title='Veikkaa', user=user, match=match, form=form, error=error ) @app.route('/result/<int:id>', methods=['GET', 'POST']) def result(id): user = database.get_user(session.get('logged_username')) if user.role.name != 'admin': return redirect(url_for('matches')) match=database.get_match(id) form = forms.Result(id, match.home_team_id, match.away_team_id) match_id = None home_goals = None away_goals = None error = None if form.validate_on_submit(): match_id = form.match_id.data home_goals = form.home_goals.data away_goals = form.away_goals.data played = form.played.data database.add_result(match_id, user.id, home_goals, away_goals, played) database.check_points() return redirect(url_for('matches')) return render_template( 'result.html', title='Tulos', user=user, match=match, form=form, error=error ) @app.route('/mybets') def mybets(): user = database.get_user(session.get("logged_username")) user_bets = database.get_user_bets(user.id) return render_template( 'mybets.html', title='Veikkaukseni', user=user, mybets=user_bets ) @app.route('/multibet', methods=['POST', 'GET']) @login_required def multibet(): for val in request.values.items(): print val[0].split(":")[0], val[1] return redirect(url_for('index')) @app.route('/check_points') @login_required def check_points(): if current_user.role.name == 'admin': database.check_points() return redirect(url_for('my_page')) @app.route('/autocheck') def autocheck(): if current_user.role.name == 'admin': database.add_results_auto() return redirect(url_for('matches')) @app.route('/autoinit') def autoinit(): if current_user.role.name == 'admin': database.init() return redirect(url_for('matches')) <file_sep>/jokipo/main.py # -*- coding: utf-8 -*- import os from flask import Flask, Blueprint from flask.ext.login import LoginManager from flask.ext.mail import Mail, Message login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'user_login' app = Flask(__name__) mail = Mail() auth = Blueprint('auth', __name__) import configuration, forms, database, views login_manager.init_app(app) mail.init_app(app) <file_sep>/jokipo/configuration.py # -*- coding: utf-8 -*- import os from main import app basedir = os.path.abspath(os.path.dirname(__file__)) print os.path.join(basedir, 'data.sqlite') app.config.update( SECRET_KEY = 'Monthy Python and the Super Rabbit', SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data.sqlite'), SQLALCHEMY_COMMIT_ON_TEARDOWN = False, SQLALCHEMY_TRACK_MODIFICATIONS = True, MAIL_SERVER = 'smtp.gmail.com', MAIL_PORT = 465, MAIL_USE_SSL = True, MAIL_USERNAME = os.environ.get('MAIL_USERNAME'), MAIL_PASSWORD = <PASSWORD>('<PASSWORD>'), FLASKY_MAIL_SUBJECT_PREFIX = 'JOKIPO VEIKKAUS: ', FLASKY_MAIL_SENDER = 'Jokipoveikkaus <<EMAIL>>', FLASKY_ADMIN = '<EMAIL>' ) <file_sep>/jokipo/common.py # -*- coding: utf-8 -*- import datetime import calendar import xml.etree.ElementTree as etree import database calendar.month_name = [ '', 'Tammikuu', 'Helmikuu', 'Maaliskuu', 'Huhtikuu', 'Toukokuu', u'Kesäkuu'.encode('utf8'), u'Heinäkuu'.encode('utf8'), 'Elokuu', 'Syyskuu', 'Lokakuu', 'Marraskuu', 'Joulukuu' ] calendar.day_name = [ 'Maanantai', 'Tiistai', 'Keskiviikko', 'Torstai', 'Perjantai', 'Lauantai', 'Sunnuntai' ] calendar.day_abbr = [ 'Ma', 'Ti', 'Ke', 'To', 'Pe', 'La', 'Su' ] def timestamp(): ''' Return current timestamp in local server time ''' return datetime.datetime.now() def set_timestamp(string_date): ''' Return string as datetime ''' return datetime.datetime.strptime(string_date, "%d.%m.%Y %H:%M:%S") class Points(): ''' For calculating the points ''' GOAL = 1 WIN = 1 TIE = 2 CORRECT = 1 class MainMenuID(): ''' Identify every main menu item ''' MAIN = 'MAIN' REGISTER = 'REGISTER' MATCHES = 'MATCHES' RANKING = 'RANKING' MYPAGE = 'MYPAGE' def subtract_one_month(dt): ''' Substract one month to datetime ''' return dt - datetime.timedelta(days=1) def add_one_month(dt): ''' Add one month to datetime ''' return dt + datetime.timedelta(days=31) def calendar_header(root, year, month): ''' Generate header for the calendar includes "next" and "previous" buttons for months ''' this_date = datetime.datetime.strptime(str(year) + '-' + str(month), '%Y-%m') prev_date = subtract_one_month(this_date) prev_date_str = '{}/{}'.format(prev_date.year, prev_date.month) next_date = add_one_month(this_date) next_date_str = '{}/{}'.format(next_date.year, next_date.month) for elem in root.findall("*//th"): a = etree.SubElement(elem, "a") a.set('href', '/matches/' + prev_date_str) a.text = "Edellinen " t = etree.SubElement(elem, 'span') t.text = ' | ' + elem.text + ' | ' elem.text = '' b = etree.SubElement(elem, "a") b.set('href', '/matches/' + next_date_str) b.text = " Seuraava" break return root def calendar_days(root, year, month): ''' Generate days for calendar marks "today" ''' this_date = datetime.datetime.strptime(str(year) + '-' + str(month), '%Y-%m') matches = database.get_matches_by_month(this_date) matches_by_date = dict() for match in matches: try: matches_by_date[match.match_time.day].append(match) except: matches_by_date[match.match_time.day] = list() matches_by_date[match.match_time.day].append(match) day_passed = True cur_dt = timestamp() for elem in root.findall("*//td"): _day = elem.text elem.text = '' try: for day_match in matches_by_date[int(_day)]: home_team = database.get_team(day_match.home_team_id).name[:3] away_team = database.get_team(day_match.away_team_id).name[:3] link = etree.SubElement(elem, "a") link.tail = home_team + '-' + away_team if day_match.played: overtime = ' ' if day_match.overtime: overtime += "JA" if day_match.overtime == 1 else "VL" link.tail += ' ' + str(day_match.home_goals) + '-' + str(day_match.away_goals) + overtime link.set('href', '/matches/match/' + str(day_match.match_id)) br = etree.SubElement(elem, 'br') elem.set('class', elem.get('class') + ' match_day') except: pass if _day != " ": td_day_a = etree.SubElement(elem, 'a') td_day_a.set('href', '#')#'/match_day/{}-{}-{}'.format(year, month, _day)) td_day = etree.SubElement(td_day_a, 'span') td_day.tail = _day td_day.set('class', 'day_number') if year > cur_dt.year: continue if year == cur_dt.year and month > cur_dt.month: continue if _day == str(timestamp().day): elem.set('class', elem.get('class') + ' today') day_passed = False if (month < cur_dt.month or day_passed or year < cur_dt.year) and elem.get('class') != 'noday': elem.set('class', 'day_passed') return root def generate_calendar(year, month): ''' Generate calendar ''' myCal = calendar.HTMLCalendar(calendar.MONDAY) htmlStr = myCal.formatmonth(year, month) htmlStr = htmlStr.replace("&nbsp;"," ") root = etree.fromstring(htmlStr) # Generate header root = calendar_header(root, year, month) # Generate days root = calendar_days(root, year, month) return etree.tostring(root) <file_sep>/jokipo/requirements.txt bcrypt==2.0.0 blinker==1.4 cffi==1.5.2 dominate==2.2.0 Flask==0.10.1 Flask-Bootstrap==3.3.5.7 Flask-Login==0.3.2 Flask-Mail==0.9.1 Flask-Principal==0.4.0 Flask-Script==2.0.5 Flask-Security==1.7.5 Flask-SQLAlchemy==2.1 Flask-WTF==0.12 itsdangerous==0.24 Jinja2==2.8 MarkupSafe==0.23 passlib==1.6.5 pycparser==2.14 six==1.10.0 SQLAlchemy==1.0.12 visitor==0.1.2 Werkzeug==0.11.5 WTForms==2.1 <file_sep>/jokipo/database.py # -*- coding: utf-8 -*- import datetime import bcrypt import common import gameloader from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy import or_ from flask.ext.login import UserMixin from main import app, login_manager from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask import current_app db = SQLAlchemy(app) # Database models and tables class Role(db.Model): ''' User roles table ''' __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) users = db.relationship('User', backref='role') def __repr__(self): return '<Role {}>'.format(self.name) class User(UserMixin, db.Model): ''' Users table ''' __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, nullable=False, index=True) password = db.Column(db.String(128), nullable=False) email = db.Column(db.String(64), nullable=False) date_registered = db.Column(db.DateTime) date_login = db.Column(db.DateTime) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) disabled = db.Column(db.Boolean, default=False) confirmed = db.Column(db.Boolean, default=False) def generate_confirmation_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm':self.id}) def confirm(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('confirm') != self.id: return False self.confirmed = True db.session.add(self) db.session.commit() return True def set_password(self, pw): pwhash = bcrypt.hashpw(pw.encode('utf8'), bcrypt.gensalt()) self.password = pwhash def check_password(self, pw): if self.password is not None: expected_hash = self.password actual_hash = bcrypt.hashpw(pw.encode('utf8'), expected_hash.encode('utf8')) return expected_hash == actual_hash return False def __repr__(self): return '<User {}>'.format(self.username) class Team(db.Model): ''' Teams table ''' __tablename__ = 'teams' id = db.Column(db.Integer, primary_key=True) team_id = db.Column(db.Integer, unique=True) official = db.Column(db.String(64)) name = db.Column(db.String(64), unique=True, nullable=False, index=True) logo = db.Column(db.String(64)) class Match(db.Model): ''' Table for matches ''' __tablename__ = 'matches' id = db.Column(db.Integer, primary_key=True) match_id = db.Column(db.Integer, unique=True) match_time = db.Column(db.DateTime) home_team_id = db.Column(db.Integer, db.ForeignKey('teams.team_id')) away_team_id = db.Column(db.Integer, db.ForeignKey('teams.team_id')) home_goals = db.Column(db.Integer, default=0) away_goals = db.Column(db.Integer, default=0) overtime = db.Column(db.Integer, default=0) played = db.Column(db.Boolean, default=False) points_shared = db.Column(db.Boolean, default=False) home_team = db.relationship("Team", foreign_keys=home_team_id) away_team = db.relationship("Team", foreign_keys=away_team_id) class Bet(db.Model): ''' Bet table ''' __tablename__ = 'bets' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) match_id = db.Column(db.Integer, db.ForeignKey('matches.match_id')) home_goals = db.Column(db.Integer) away_goals = db.Column(db.Integer) user = db.relationship("User", foreign_keys=user_id) match = db.relationship("Match", foreign_keys=match_id) class Points(db.Model): ''' Table for storing all the points users has got ''' __tablename__ = 'points' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) match_id = db.Column(db.Integer, db.ForeignKey('matches.match_id')) goals = db.Column(db.Integer) wins = db.Column(db.Integer) ties = db.Column(db.Integer) corrects = db.Column(db.Integer) total = db.Column(db.Integer) # Functions to retrieve or add data @login_manager.user_loader def load_user(user_id): ''' Get User from database ''' return User.query.get(int(user_id)) def get_role(role): ''' Find role from SQL ''' return Role.query.filter_by(name=role).first() def get_user_by_name(username): ''' Find user from SQL using username ''' return User.query.filter_by(username=username).first() def get_user_by_email(email): ''' Find user from SQL using email ''' return User.query.filter_by(email=email).first() def get_users(): ''' Return all users ''' return User.query.all() def add_user(username, password, email): ''' Add new user if username or password won't be found ''' if get_user_by_name(username) is None and get_user_by_email(email) is None: user = User( username=username, role=get_role('basic'), email=email, date_registered=common.timestamp() ) user.set_password(password) db.session.add(user) db.session.commit() return user else: return False def validate_user(email, password): ''' Check does email exists and is the password correct ''' user = get_user_by_email(email) print user if user and user.check_password(password): # Update the last login timestamp user.date_login = common.timestamp() db.session.add(user) db.session.commit() return user return False def get_teams(): ''' Return list of teams ''' return Team.query.all() def get_team(team_id): ''' Get team by team id ''' return Team.query.filter_by(team_id=team_id).first() def get_matches(played=None): ''' Get played, not played or all matches ''' if played is 1: return Match.query.order_by('match_time').filter_by(played=1).all() elif played is 0: return Match.query.order_by('match_time').filter_by(played=0).all() else: return Match.query.order_by('match_time').all() def get_matches_by_team(team_id): ''' Return all team matches as list ''' return db.session.query(Match).order_by('match_time').filter(or_( Match.home_team_id == team_id, Match.away_team_id == team_id )).all() def get_matches_by_month(dt): ''' Get all the matches from the selected month ''' start = str(dt) end = str(common.add_one_month(dt)) return db.session.query(Match).filter(Match.match_time.between(start, end)).all() def get_match(match_id): ''' Get Match details ''' return Match.query.filter_by(match_id=match_id).first() def get_bet(match_id, user_id): ''' Get users bet for single match ''' return Bet.query.filter_by(match_id=match_id, user_id=user_id).first() def get_all_bets(match_id): ''' Get all bets according to the match id ''' return Bet.query.filter_by(match_id=match_id).all() def get_user_bets_all(user_id): ''' Get all bets that user has been done so far ''' return db.session.query(Bet, Match).filter_by(user_id=user_id).join(Match).order_by(Match.match_time).all() def get_user_bets_with_points(user_id): ''' Get all bets of user, including points ''' all = get_user_bets_all(user_id) _return = list() for single in all: points = db.session.query(Points.total).filter_by(user_id=user_id, match_id=single.Match.id).first() if points: _s = [single[0], single[1], points[0]] else: _s = [single[0], single[1], 0] _return.append(_s) return _return def add_bet(match_id, user_id, home_goals, away_goals): ''' Adding new bet ''' old_bet = get_bet(match_id, user_id) if old_bet: old_bet.home_goals = home_goals old_bet.away_goals = away_goals new_bet = old_bet else: new_bet = Bet( match_id = match_id, user_id = user_id, home_goals = home_goals, away_goals = away_goals ) db.session.add(new_bet) db.session.commit() def get_points(match_id, user_id): ''' Get points that user has got in single match ''' return Points.query.filter_by(match_id=match_id, user_id=user_id).first() def check_points(): ''' Check what user has bet and what was the result of the game Write points to SQL ''' matches = Match.query.order_by('match_time').filter_by(played=1, points_shared=0).all() print matches for match in matches: print match for bet in get_all_bets(match.match_id): if get_points(match.match_id, bet.user_id): continue if match.overtime: match_home_goals = match.home_goals match_away_goals = match.away_goals else: match_home_goals = min(match.home_goals, match.away_goals) match_away_goals = min(match.home_goals, match.away_goals) # Bet home goals is the same as match home goals goal_home = bet.home_goals == match_home_goals # Bet away goals is the same as match away goals goal_away = bet.away_goals == match_away_goals # Bet is tie tie_bet = (bet.home_goals - bet.away_goals) == 0 # Match is tie tie_match = (match_home_goals - match_away_goals) == 0 # Which team won the game, positive = home, negative = away, 0 = tie win_bet = (bet.home_goals - bet.away_goals) win_match = (match_home_goals - match_away_goals) goal = 0 win = 0 tie = 0 correct = 0 if goal_home: goal += common.Points.GOAL if goal_away: goal += common.Points.GOAL if tie_bet and tie_match: tie += common.Points.TIE elif (win_bet > 0 and win_match > 0) or (win_bet < 0 and win_match < 0): win += common.Points.WIN if goal_home and goal_away: correct += common.Points.CORRECT total = goal + tie + win + correct db.session.add(Points( match_id=match_id, user_id=bet.user_id, goals=goal, wins=win, ties=tie, corrects=correct, total=total )) match.points_shared = 1 db.session.add(match) db.session.commit() def get_ranking(): ''' Generate ranking list ''' points = db.session.query( Points.user_id, db.func.sum(Points.goals).label('total_goals'), db.func.sum(Points.wins).label('total_wins'), db.func.sum(Points.ties).label('total_ties'), db.func.sum(Points.corrects).label('total_corrects'), db.func.sum(Points.total).label('total_total'), db.func.count(Points.user_id).label('bets') ).order_by( db.desc('total_total'), db.desc('total_corrects'), db.desc('total_ties'), db.desc('total_wins'), db.desc('total_goals') ).group_by('user_id').all() ranking = dict() nro = 1 for p in points: user = User.query.filter_by(id=p[0]).first() ranking[nro] = { 'user': user, 'goals': p[1], 'wins': p[2], 'ties': int(p[3]) / 2, 'corrects': p[4], 'total': p[5], 'bets': p[6] } nro += 1 return ranking def add_result(match_id, user_id, home_goals, away_goals, played): ''' Adding new bet ''' match = get_match(match_id) match.home_goals = home_goals match.away_goals = away_goals match.played = played db.session.add(match) db.session.commit() def add_results_auto(): loader = gameloader.Mestis(168, 425114685) matches = loader.getMatches() for match_id in matches: if Match.query.filter_by(match_id=match_id).first(): result = matches[match_id]['Result'].split()[0].split('-') played = 1 if matches[match_id]['GameStatus'] == '2' else 0 overtime = 1 if matches[match_id]['FinishedType'] != '1' else 0 thisMatch = get_match(match_id) thisMatch.home_goals=result[0] thisMatch.away_goals=result[1] thisMatch.played=played thisMatch.overtime=overtime db.session.add(thisMatch) db.session.commit() check_points() def init(): ''' Initialize the database ''' db.create_all() if not get_role('basic'): # User roles db.session.add(Role(name='basic')) db.session.add(Role(name='admin')) db.session.commit() user_master = User( username="master", role=get_role('admin'), email="<EMAIL>", date_registered=common.timestamp() ) user_master.set_password("<PASSWORD>") db.session.add(user_master) db.session.commit() loader = gameloader.Mestis(168, 425114685) for team, team_id in loader.getTeams().iteritems(): if Team.query.filter_by(name=team).first() is None: thisTeam = Team(name=team, team_id=team_id) db.session.add(thisTeam) db.session.commit() matches = loader.getMatches() for match_id in matches: if Match.query.filter_by(match_id=match_id).first() is None: dt = '{} {}'.format(matches[match_id]['GameDate'], matches[match_id]['GameTime']) result = matches[match_id]['Result'].split()[0].split('-') thisMatch = Match( match_id=match_id, home_team_id=matches[match_id]['HomeTeamID'], away_team_id=matches[match_id]['AwayTeamID'], match_time=common.set_timestamp(dt) ) db.session.add(thisMatch) db.session.commit() <file_sep>/jokipo/forms.py # -*- coding: utf-8 -*- from main import app import database from flask.ext.wtf import Form from wtforms import StringField, HiddenField, PasswordField, SubmitField, BooleanField, IntegerField from wtforms.validators import Required, Email class Register(Form): ''' Registration form ''' name = StringField(u'Nimimerkki', validators=[Required()]) password = PasswordField(u'<PASSWORD>', validators=[Required()]) email = StringField(u'Sähköposti', validators=[Email()]) submit = SubmitField(u'Rekisteröidy') class Login(Form): ''' Login form ''' email = StringField(u'Sähköposti', validators=[Required()]) password = PasswordField(u'<PASSWORD>', validators=[Required()]) remember_me = BooleanField(u'Muista minut') token = HiddenField(u'token') submit = SubmitField(u'Kirjaudu') class Bet(Form): ''' Betting form ''' match_id = HiddenField(u'match_id') home_goals = IntegerField(u'Kotijoukkueen maalit') away_goals = IntegerField(u'Vierasjoukkueen maalit') submit = SubmitField(u'Veikkaa') def __init__(self, match_id, home_id, away_id): super(Bet, self).__init__() self.match_id.data = match_id self.home_goals.description = database.get_team(home_id).name self.away_goals.description = database.get_team(away_id).name class Result(Form): ''' Result form for admin user ''' match_id = HiddenField(u'match_id') home_goals = StringField(u'Koti') away_goals = StringField(u'Vieras') overtime = BooleanField(u'Jatkoaika') played = BooleanField(u'Pelattu') submit = SubmitField(u'Lähetä') def __init__(self, match_id, home_id, away_id): super(Result, self).__init__() self.match_id.data = match_id self.home_goals.description = database.get_team(home_id).name self.away_goals.description = database.get_team(away_id).name class ChangePassword(Form): ''' Change user password ''' current_pw = PasswordField(u'<PASSWORD>') new_pw = PasswordField(u'<PASSWORD>') new_pw_confirm = PasswordField(u'<PASSWORD>') submit = SubmitField(u'Muuta') <file_sep>/readme.md # Jokipo veikkaus Guess the result of the match. Better you guess, more points you get. Not really well commented project. Uses Flask, and SQLite as default database. For Mestis (ice hockey league in Finland) matches, currently only games of Jokipojat (both home/away). There are lots of ideas how to improve the application/game, like Facebook integration (no extra registration/login required!), to all possible Mestis teams (and other leagues) and so on... <file_sep>/jokipo/gameloader.py import urllib2 import json class GameLoader(object): ''' Class for loading the games and such things ''' def _load_data(self): ''' Load data from the webpage ''' req = urllib2.Request(self.url) return urllib2.urlopen(req).read() def _json_to_dict(self, json_string): ''' Parse JSON string to dictionary ''' return json.loads(json_string) def _validate_data(self, data): ''' If data is not ready to execute right away, modify it first ''' return data def _picker(self, data, mode): ''' Pick selected data from dictionary Keyword arguments: data -- data in dictionary format mode -- selected mode or type you want to take ''' result = dict() for record in self._validate_data(data): if mode == 'teams': result[record[self.team_name]] = record[self.team_id] elif mode == 'matches': result[record[self.match_id]] = { item: record[item] for item in record } return result def getData(self): ''' Combines _load_data and _json_to_dict functions ''' return self._json_to_dict(self._load_data()) def getTeams(self): ''' Get team as dictionary ''' return self._picker(self.getData(), 'teams') def getMatches(self): ''' Get all games as dictionary ''' return self._picker(self.getData(), 'matches') class Mestis(GameLoader): def __init__(self, groupid, team_id='', rink=''): ''' For Mestis Keyword arguments: groupid -- Identification number for season team_id -- Every team has an unique ID number rink -- Rink ID of the rink where the match takes place ''' super(Mestis, self).__init__() self._url(groupid, team_id, rink) self._data() def _url(self, groupid, team_id, rink): ''' Generating URL ''' url = 'http://www.tilastopalvelu.fi' url += '/ih/modules/mod_schedule/helper' url += '/games.php' url += '?statgroupid='+str(groupid) url += '&select=' url += '&id=' url += '&teamid='+str(team_id) url += '&rinkid='+str(rink) url += '&rmd=' self.url = url def _validate_data(self, data): ''' We know the data from Mestis service is not directly accessed as default ''' return data['games'] def _data(self): ''' Some identifications for data ''' self.team_id = 'HomeTeamID' self.team_name = 'HomeTeamName' self.match_id = 'UniqueID' ''' NOTE FinishedType 1 Game finished in 60 minutes 2 Overtime 3 Shootout GameStatus 0 Not played?? 1 Running?? 2 Played 3 Cancelled?? ''' if __name__ == '__main__': gameloader = Mestis(168) matches = gameloader.getMatches() for match_id in matches: dt = '{} {}'.format(matches[match_id]['GameDate'], matches[match_id]['GameTime']) print dt <file_sep>/jokipo/runserver.py # -*- coding: utf-8 -*- from flask.ext.script import Manager from main import app manager = Manager(app) if __name__ == "__main__": manager.run() <file_sep>/jokipo/jokipo.wsgi import sys sys.path.append('/var/www/jokipo/') from main import app as application
df6162ad7a37388704339bbeecbf58bb04a14d8f
[ "Markdown", "Python", "Text" ]
11
Python
dewabe/Jokipo-Veikkaus
c34a1682673d2ae1a0d199f94c767fd88c928769
b3e6388845ba122d0a97500ceb59da04c848fee6
refs/heads/master
<repo_name>donrestarone/reinforcing-apr9-methods<file_sep>/word_counter.rb def word_counter(body_of_text) input = body_of_text word_array = input.split word_count = word_array.count return word_count.to_i end i = "this is a long string that has many words in it that we need to count" puts word_counter(i)
240a1909f2d0557adfbbbae00412cf2971bbb57a
[ "Ruby" ]
1
Ruby
donrestarone/reinforcing-apr9-methods
8ecf0b7d3ba4f514a739d897b8378bb7834471f1
2d570703640e94896e328a2d8fa5e5f11f6265d5
refs/heads/master
<file_sep> // Main functionality for Hangman-js-game. // main2.js has: // - list of possible words to guess // - choosing one word (with Math.random()) // - starting the game with startGame() // - getting the letter from input with waitForClick() // - updating game situation with updateGame() const words = ["APPLE" , "ORANGE" , "CHAIR" , "AVOCADO" , "PIZZA" , "TABLE" , "HEAD" , "SOFT" , "GROUND" , "SPACE" , "BANANA" , "MANDARIN" , "COMPUTER" , "JAVA" , "JAVASCRIPT" , "PUNISHMENT" , "CAPITOL" , "TOWN" , "PHONE" , "HANGMAN" , "EPSTEINDIDNOTKILLHIMSELF"]; // CHOOSE THE WORD const randomWord = words[Math.floor(Math.random() * words.length)]; console.log("This is randomWord: "+randomWord); const givenLetters = []; givenLetters.length=0; // How many "lives" do you want the player to have const livesLeft= 6; // Clicking the Gallows-image runs this function function startGame(){ let dumDumDum = []; for( iii=0; iii < randomWord.length ; iii++){ dumDumDum.push("_"); } // Change the game textcontents to starting values document.querySelector(".the_word").innerHTML ="The word: "+dumDumDum+" "; document.querySelector(".guesses").innerHTML ="Guesses: "; document.querySelector(".guesses_left").innerHTML ="Wrong guesses left: "+livesLeft+" "; } function waitForClick(){ let myChar = document.getElementById('myletters').value; console.log("This is myLetter in waitForClick: "+myChar); givenLetters.push(...myChar); updateGame(myChar,randomWord,givenLetters); } function updateGame(letter, word, givenLettersArray){ let myArray = [...givenLettersArray]; let secretWord = []; let correctLetter = []; // fill correctLetter[] with 'false' for(iter=0; iter < word.length ; iter++){ secretWord.push("_"); correctLetter.push(false); } let counter=0; let falseCounter = word.length; let livesDummy = livesLeft; do { falseCounter = word.length; let dummy = myArray[counter]; console.log("This is myArray[counter] in while: "+myArray[counter]+" dummy: "+dummy); for( iiii=0; iiii < word.length ; iiii++){ if(dummy === word[iiii].toLowerCase()){ secretWord[iiii] = word[iiii].toLowerCase(); correctLetter[iiii] = true; falseCounter = falseCounter - 1; } }// for if( falseCounter === word.length ){ livesDummy = livesDummy - 1; // Change the game imagecontent to game-situation if(livesDummy===5){ let imgLose1 = document.querySelector('.puu'); imgLose1.src = "../imgs/img_lose_1.png"; document.body.appendChild(imgLose1); } if(livesDummy===4){ let imgLose2 = document.querySelector('.puu'); imgLose2.src = "../imgs/img_lose_2.png"; document.body.appendChild(imgLose2); } if(livesDummy===3){ let imgLose3 = document.querySelector('.puu'); imgLose3.src = "/../imgs/img_lose_3.png"; document.body.appendChild(imgLose3); } if(livesDummy===2){ let imgLose4 = document.querySelector('.puu'); imgLose4.src = "../imgs/img_lose_4.png"; document.body.appendChild(imgLose4); } if(livesDummy===1){ let imgLose5 = document.querySelector('.puu'); imgLose5.src = "../imgs/img_lose_5.png"; document.body.appendChild(imgLose5); } if(livesDummy===0){ let imgLose6 = document.querySelector('.puu'); imgLose6.src = "../imgs/img_lose_6.png"; document.body.appendChild(imgLose6); } } // Change the game textcontents to game-situation document.querySelector(".the_word").innerHTML ="The word: "+secretWord+" "; document.querySelector(".guesses").innerHTML ="Guesses: "+givenLetters+" "; document.querySelector(".guesses_left").innerHTML ="Wrong guesses left: "+livesDummy+" "; counter++; let winner = 0; for(iter=0; iter < word.length ; iter++){ if(correctLetter[iter]===true){ winner = winner + 1; } } if(winner === word.length){ let imgWin = document.querySelector('.puu'); imgWin.src = "../imgs/img_win.png"; document.body.appendChild(imgWin); // Change the game textcontents to game-situation-WIN document.querySelector(".the_word").innerHTML ="YOU WIN!!! Word is: "+word+" "; document.querySelector(".guesses").innerHTML ="Your Guesses: "+givenLetters+" "; document.querySelector(".guesses_left").innerHTML ="Wrong guesses left: "+livesDummy+" "; } if(livesDummy < 0){ let oldImage = document.querySelector('.puu'); oldImage.src = "../imgs/img_lose.png"; document.body.appendChild(oldImage); // Change the game textcontents to game-situation-LOSE document.querySelector(".the_word").innerHTML ="YOU LOSE!!!"; document.querySelector(".guesses").innerHTML ="YOU LOSE!!!"; document.querySelector(".guesses_left").innerHTML ="YOU LOSE!!!"; } } while( myArray.length - counter > 0 ) } // function updateGame() <file_sep>// Register to member-section data checking javascript, Javascript2020 function checkRegisterData(){ let user_value = document.forms["Register"]["user_name"].value; let pw_value = document.forms["Register"]["user_pw_1"].value; let pw_value2 = document.forms["Register"]["user_pw_2"].value; let my_date = document.forms["Register"]["date of birth"].value; let year_value = Number(my_date[0]+my_date[1]+my_date[2]+my_date[3]); let current_year = new Date(); let age_value = Number( Number(current_year.getYear()+1900) - year_value ); let logInfoValid = true; console.log("Current year: "+current_year.getYear()); console.log("Birth year: "+year_value); console.log("Age: "+age_value); if (age_value < 18){ alert("You must be 18 or older to register"); logInfoValid = false; return false; } if (user_value == ""){ alert("You mus fill in username to to register"); logInfoValid = false; return false; } if (pw_value == "" || pw_value.length < 6){ alert("You must create password to register (at least six (6) characters)"); logInfoValid = false; return false; } if (pw_value2 == "" || pw_value != pw_value2){ alert("You must rewrite your password to register"); logInfoValid = false; return false; } if(logInfoValid === true){ makeDataBaseEntry(user_value, pw_value, age_value); } } function makeDataBaseEntry(user_value, pw_value, age_value){ // TODO: db connect with root-user privileges // TODO: db actions // TODO: db kill connection alert("Simulation: Given data is valid, created new entry to member database"); } <file_sep><!-- Simulated Members-section Register, Javascript2020 !--> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Register</title> <script src="../scripts/main_register.js"></script> <link href="../css/style2.css" rel="stylesheet" type="text/css"> </head> <body> <h1 align="center">(NOT REAL!!!) Register here to become a member.(NOT REAL!!!)</h1> <h2 align="center">(ONLY EXAMPLE!!!) Fill in your personal information, (*) is required.(ONLY EXAMPLE!!!)</h2> <!--action="*.php"!--> <form method="post" name="Register" onsubmit="return checkRegisterData()"> <label for="male">(*) Male</label> <input type="radio"id="male" name="gender" value="male"> <label for="male">Female</label> <input type="radio" id="female" name="gender" value="female"> <label for="male">other</label> <input type="radio" id="other" name="gender" value="other"><p></p> <label for="date of birth">date of birth:</label> <input type="date" id="date_of_birth" name="date of birth"><p></p> (*) choose username: <input type="text" name="user_name"><p></p> (*) create password: <input type="<PASSWORD>" name="<PASSWORD>"><p></p> (*) repeat password: <input type="<PASSWORD>" name="<PASSWORD>"><p></p> <input type="submit" value="Register"><p></p><p></p> <button id="cancel" ><a href="../main_index.html">Cancel</a></button> </form> <br> </body> </html> <file_sep># JavaScript-Hangman--game A main HTML page with links to a JavaScripted Hangman-game, WorldClock example and a simulated Members sign in/register section // TODO: add more descriptions about the content
2f2eb16be414c4d27492b5439655480053e2e207
[ "JavaScript", "HTML", "Markdown" ]
4
JavaScript
MirikEekkael/JavaScript-Hangman--game
afe56d7de02cf9ccc5e54cd490fea3557b6efe6a
7358e60017a3a41665fe74ec3cb6bf6f8585af52
refs/heads/master
<file_sep> public class StringManip { public static void main(String[] args) { System.out.println(ConvertToProperCase("john y cc <NAME> hEEEE")); } public static String ConvertToProperCase(String strName) { String [] names = strName.split(" "); String retVal = ""; for(int i = 0; i < names.length; i++) { if (names[i].equals("")) continue; String firstChar = names[i].substring(0, 1).toUpperCase().trim(); String restString = names[i].substring(1).toLowerCase().trim(); retVal += firstChar + restString + " "; } return retVal; } }
fbe55b82fba34453148e988b9c5d67f799c3c8b3
[ "Java" ]
1
Java
wmalquitar23/Java-Projects
472a9cea38d67b20b84bad8f6a449d7faac38e35
74e264bd4f4ba414deb851a7fdfc18cd79591831
refs/heads/master
<file_sep># Total of Emissions for Motor Vehicle Sources: Baltimore Vs. Los Angeles (Plot 5) # Compare emissions from motor vehicle sources in Baltimore City with emissions # from motor vehicle sources in Los Angeles County, California (flips="06037"). # Which city has seen greater changes over time in motor vehicle emissions? source("./src/initialise.R") library(ggplot2) NEIVBalt = NEI[(NEI$fips=="24510") & (NEI$type=="ON-ROAD"),] NEIVLA = NEI[(NEI$fips=="06037") & (NEI$type=="ON-ROAD"),] NEIVBaltYearly = aggregate(Emissions ~ year, data = NEIVBalt, FUN = sum) NEIVLAYearly = aggregate(Emissions ~ year, data = NEIVLA, FUN = sum) NEIVBaltYearly$City <- "Baltimore City" NEIVLAYearly$City <- "Los Angeles County" NEIVBatlLAYearly <- rbind(NEIVBaltYearly, NEIVLAYearly) png("./figure/plot6.png") # Using grids # ggplot(NEIVBatlLAYearly, aes(x=factor(year), y=Emissions, fill=City)) + # geom_bar(stat="identity") + # facet_grid(City ~ ., scales="free") + # xlab("Year") + # ylab(expression("Total PM"[2.5]*" emissions")) + # ggtitle("Emissions from Motor Vehicle - Baltimore Vs. Los Angeles") # Without grids (prefered: comparisons can be made using the same scale on y) ggplot(NEIVBatlLAYearly, aes(x=factor(year), y=Emissions, fill=City)) + geom_bar(stat="identity", position="dodge") + xlab("Year") + ylab(expression("Total PM"[2.5]*" emissions")) + ggtitle("Emissions from Motor Vehicle - Baltimore Vs. Los Angeles") dev.off() <file_sep># Total of Emissions per year in Baltimore City, Maryland (Plot 2) # Have total emissions from PM2.5 decreased in the Baltimore City, Maryland (flips=="24510") # from 1999 to 2008? Use the base plotting system to make a plot answering this question. source("./src/initialise.R") NEIBalt = subset(NEI, fips=="24510") NEIBaltYearly = aggregate(Emissions ~ year, data = NEIBalt, FUN = sum) png("./figure/plot2.png") barplot(NEIBaltYearly$Emissions, names.arg=NEIBaltYearly$year, xlab="Year", ylab=expression("PM"[2.5]*" emissions"), main="Total of Emissions per Year for Baltimore" ) dev.off() <file_sep># Total of Emissions per Year (Plot 1) # Have total emissions from PM2.5 decreased in the United States from 1999 to 2008? # Using the base plotting system, make a plot showing the total PM2.5 emission from all # sources for each of the years 1999, 2002, 2005, and 2008. source("./src/initialise.R") NEIYearly = aggregate(Emissions ~ year, data = NEI, FUN = sum) png("./figure/plot1.png") # Way 1: Using scattered plot # with(NEIYearly, plot(year, log10(Emissions), type="l", xlab="Year", ylab="Emissions (log scale)")) # title("Total of Emissions per Year") # Way 2: Using barplot barplot(NEIYearly$Emissions / 1000, names.arg=NEIYearly$year, xlab="Year", ylab=expression("PM"[2.5]*" emissions (x1000)"), main="Total of Emissions per Year" ) dev.off() <file_sep># Total of Emissions per year and type (Plot 3) # Of the four types of sources indicated by the type (point, nonpoint, onroad, nonroad) variable, # which of these four sources have seen decreases in emissions from 1999–2008 for Baltimore City? # Which have seen increases in emissions from 1999–2008? Use the ggplot2 plotting system to make a # plot answer this question. source("./src/initialise.R") library(ggplot2) NEIBalt = subset(NEI, fips=="24510") NEIBaltTypeYearly = aggregate(Emissions ~ year + type, data = NEIBalt, FUN = sum) png("./figure/plot3.png") # Old way: # g <- ggplot(NEIBaltTypeYearly, aes(y = log10(Emissions), x = year, color = type)) + # labs(title="Total of Emissions per Year and Type for Baltimore") + # ylab(expression("PM"[2.5]*" emissions (log scale)")) + # xlab("Year") # g + geom_line() # Nicer way: (Using grids) ggplot(NEIBaltTypeYearly, aes(x=factor(year), y=Emissions, fill=type)) + geom_bar(stat="identity") + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + facet_grid(. ~ type) + xlab("Year") + ylab(expression("Total PM"[2.5]*" emission")) + ggtitle(expression("PM"[2.5]*paste(" Emissions in Baltimore ", "City by Various Source Types", sep=""))) # Another way: (Without grids) # ggplot(NEIBaltTypeYearly, aes(x=factor(year), fill=type, y=Emissions)) + # geom_bar(stat="identity", position="dodge") + # geom_bar(stat="identity") + # facet_grid(. ~ type) + # xlab("Year") + # ylab(expression("Total PM"[2.5]*" emission")) + # ggtitle(expression("PM"[2.5]*paste(" emissions in Baltimore ", # "City by Various Source Types", sep=""))) dev.off() <file_sep># Total of Emissions for Combustion-related Sources (Plot 4) # Across the United States, how have emissions from coal combustion-related sources changed from 1999–2008? source("./src/initialise.R") library(ggplot2) # Find coal combustion-related sources is_cc <- grepl("Fuel Comb.*Coal", SCC$EI.Sector) cc_sources <- SCC[is_cc,] # Another option for subsetting: NEI[(NEI$SCC %in% cc_sources$SCC), ] NEICCC = subset(NEI, NEI$SCC %in% cc_sources$SCC) NEICCTYearly = aggregate(Emissions ~ year, data = NEICCC, FUN = sum) png("./figure/plot4.png") ggplot(NEICCTYearly, aes(x=factor(year), y=Emissions/1000)) + geom_bar(stat="identity") + xlab("Year") + ylab(expression("Total PM"[2.5]*" emissions (x1000)")) + ggtitle("Total of Emissions from Coal Combustion-related Sources") dev.off() <file_sep># INITIALISATION ## This first line will likely take a few seconds. Be patient! NEI <- readRDS("../ExData_Plotting2.data/summarySCC_PM25.rds") SCC <- readRDS("../ExData_Plotting2.data/Source_Classification_Code.rds") <file_sep># Total of Emissions for Motor Vehicle Sources (Plot 5) # How have emissions from motor vehicle sources changed from 1999–2008 in Baltimore City? source("./src/initialise.R") library(ggplot2) NEIVBalt = NEI[(NEI$fips=="24510") & (NEI$type=="ON-ROAD"),] NEIVBaltYearly = aggregate(Emissions ~ year, data = NEIVBalt, FUN = sum) png("./figure/plot5.png") ggplot(NEIVBaltYearly, aes(x=factor(year), y=Emissions)) + geom_bar(stat="identity") + xlab("Year") + ylab(expression("Total PM"[2.5]*" emissions")) + ggtitle("Total of Emissions from Motor Vehicle Sources for Baltimore") dev.off()
095ebd287979cc71c78d3eba586f4effc8e8c53e
[ "R" ]
7
R
josecarlosgt/ExData_Plotting2
c8a50dc9d21c705f42c532f2931e5e528b29ee5c
6ae2f206597d15d47b61768094ea98437059863a
refs/heads/master
<repo_name>PierpaoloLucarelli/CM4025<file_sep>/client/state/player/createPlayer.js // creating a new player const createPlayer = (x, y, game, car) => { if(car == null){ car = "car1" } const sprite = game.add.sprite(x, y, car) game.physics.p2.enable(sprite, false) return sprite } export default createPlayer<file_sep>/client/state/sockets/collision.js // when 2 payers collide const collision = (socket, win_player, loose_player) => { socket.emit('collision', { win_username: win_player.username, win_id: win_player.id, loose_id: loose_player }) } export default collision <file_sep>/server/models/car.js // Save a reference for each car in mongodb var mongoose = require("mongoose"); var Schema = mongoose.Schema; var ObjectId = Schema.ObjectId; var bcrypt = require("bcrypt"); var Car = new Schema({ id: ObjectId, model: {type: String, unique: true}, speed: Number, cost: {type: Number, default: 0} }); var carModel = mongoose.model("Car", Car, "cars"); // add a car to db exports.addCar = function(car, cb){ new carModel({ model: car.model, speed: car.speed, cost: car.cost }).save(function(err){ if(err){ cb(err); } else { cb(null); } }); } // get all cars from db exports.getAll = function(cb){ carModel.find({}, function(err, cars) { if(err){ cb(err, null); } else{ cb(null, cars); } }); } module.exports.carSchema = carModel;<file_sep>/client/config/fileloader.js // load the assests like cars and bacgrkound import { ASSETS_URL } from '.' const fileLoader = game => { game.load.crossOrigin = 'Anonymous' game.stage.backgroundColor = '#1E1E1E' game.load.image('asphalt', `${ASSETS_URL}/sprites/terrain/terrain.png`) game.load.image('background', `${ASSETS_URL}/sprites/bg/bg.png`) game.load.image('background2', `${ASSETS_URL}/sprites/bg/bg2.png`) game.load.image('car1', `${ASSETS_URL}/sprites/car1/car1.png`) game.load.image('car2', `${ASSETS_URL}/sprites/car2/car2.png`) game.load.image('car3', `${ASSETS_URL}/sprites/car3/car3.png`) } export default fileLoader<file_sep>/client/state/sockets/death.js // whena player dies const death = (socket, player) => { socket.on('death', () => { $(".popup").show(); player.sprite.destroy() player.playerName.destroy() player.speedText.destroy() }) } export default death <file_sep>/client/state/utils/index.js export const isDown = (game, key) => game.input.keyboard.isDown(key) export const createText = (game, target) => game.add.text(target.x, target.y, '', { fontSize: '12px', fill: '#FFF', align: 'center' }) // read the user cookies export const getCookie = (name) =>{ var nameEQ = name + "=" var ca = document.cookie.split(';') for(var i=0;i < ca.length;i++) { var c = ca[i] while (c.charAt(0)==' ') c = c.substring(1,c.length) if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length) } return null }<file_sep>/server/models/users.js var mongoose = require("mongoose"); var Schema = mongoose.Schema; var ObjectId = Schema.ObjectId; var bcrypt = require("bcrypt"); var User = new Schema({ id: ObjectId, name: {type: String, unique: true}, password: String, level: {type: Number, default: 0}, unlock: String, car: {type: String, default: "<PASSWORD>"} }); var userModel = mongoose.model("User", User, "users"); // create a new user exports.createUser = function(username, pass, cb){ bcrypt.hash(pass, 10, function(err, hash) { new userModel({ name: username, password: hash }).save(function(err){ if(err){ cb(err); } else { cb(null); } }); }); } // unlock level 2 exports.setUnlock = function(username, cb){ console.log("unlocking"); userModel.findOneAndUpdate({name: username}, {unlock: "2"}, cb); } // get user details exports.getUser = function(username, cb){ userModel.findOne({name: username}, function(err, user){ if(err){ cb(err, null); } else { cb(null, user); } }); } // validate user for log in exports.validateUser = function(username, pass, cb){ userModel.findOne({name: username}, function(err, user){ if(!user){ cb("password or username are wrong", null); } else { console.log(pass); bcrypt.compare(pass, user.password, function(err, res) { if(err){ cb(err, null); } else{ cb(null, user); } }); } }); } // update the users score exports.updateLevel = function(user, level, cb){ console.log("updating score of : "+ user + "to: " + level); userModel.findOneAndUpdate({name :user}, {"level": level}, function(err){ if(err) cb(err); else{ cb(null); } }); } // check if sessione existst exports.checkSession = function(username, cb){ userModel.findOne({name: username}, function(err, user){ if(!user){ cb(err, null); } else { cb(null, user); } }); } // add one point to the users score exports.addPoint = function(user, cb){ userModel.findOneAndUpdate({name :user}, {$inc : {'level' : 1}}, function(err){ if(err){ console.log("err"); cb(err) } else{ cb(null) } }) } // gets the users's score exports.getScore = function(user, cb){ userModel.findOne({name: user}, function(err, usr){ if(err){ cb(err, null) } else{ cb(null, usr.level) } }) } // adds a car to a user exports.buyCar = function(user, car, cb){ userModel.findOne({name: user}, function(err, usr){ if(err){ cb(err) } else{ var points = usr.level if(points > parseInt(car.cost)){ userModel.findOneAndUpdate({name: user}, {car: car.model}, {upsert:true}, function(err, doc){ if (err) {cb(err)} else {cb(null)} }); } else{ console.log("not enough points"); cb("Not enough points") } } }) } module.exports.userSchema = userModel;<file_sep>/README.md # CM4025 Enterprise web systems coursework This is a README intended to provide an overview of the project requirements for the MMORPG game. ## Overview of the game This section describes the main features and functionality of the game. ## link to online game: [link to game](http://cm4025.herokuapp.com/) ### Theme The chosen them was **Sports** / **racing**. The implemented game consists of a demolition-derby style multi-level game, where players can join an arena and compete against each other. ### Progression Progression is determined by the points accumulated by the player over time. Points are obtained by crashing head-on to another player's car. The player that wins the collision will receive points and the player that looses the collision will not receive any points. Points can be used in this game in two ways: - To **upgrade** the player's car: The players can enter a marketplace where it is possible to purchase and upgrade the player's car using the points accumulated during gameplay. Each car has a price to be paid in points. When a player buys a car the cost of the car is deducted form the points of the player. ![Game market](https://raw.githubusercontent.com/PierpaoloLucarelli/CM4025/master/screens/market.png) - To **upgrade** to another level: Once the player has reached a total of 60pts, the player can chose to unlock another level. Different levels have different arenas where the players can compete. ### Social interaction ![example of cars](https://raw.githubusercontent.com/PierpaoloLucarelli/CM4025/master/screens/1.png?token=<PASSWORD>%3D) As the game is a real-time multiplayer game, the players can directly with each other simply by playing the game. There is no limit to the numbers of concurrent players that can join, but the performance of the server may be affected by too may concurrent connections. ![chat of the game](https://raw.githubusercontent.com/PierpaoloLucarelli/CM4025/master/screens/chat.png?token=AMA<PASSWORD>%3D%3D) To add another level of social interaction, a chat was implemented were the players can broadcast their messages to every other player in the game. ## Technology used ### front-end The game part of the project was implemented using the JavaScript Game framework **Phaser.js**. The code for driving a car in Phaser.js was taken from an online tutorial, but it was extended to the multi-player case. In addition the collision detection system was created by me along with all the front-end functionality such as **points**, **cars** and **levels** management. How the collision detection systems works The collision detection systems was implemented by checking wether the front-point of a car was in contact with any point of the other cars. The front-point of the car can be calculated using the formula: ``` x = carX + (Cos(θ) + LengthOfCar / 2) y = cary + (Sin(θ) + LengthOfCar / 2) ``` Example of how the X point of the tip of the car is calculated: ![cos of car](https://raw.githubusercontent.com/PierpaoloLucarelli/CM4025/master/screens/coscar.png?token=AMA<PASSWORD>%3D%3D) The functionality of the pages like **market** and **levels** were implemented using JQuery, as there was only a need of simple AJAX calls to the server. The project was developed using **webpack** and the modular JavaScript ES6 syntax ### Backend The server of the game uses the following technologies: - Nodejs + Express: these technologies were used to implement a simple HTTP server that is able to respond to client requests and API calls. - Socket.io: Used to implement the real-time client-to-client communication for the driving of the cars. - MongoDB and Mongoose ORM: used for storing information such as: User accounts, car details, levels and points. ### API specification | End point | Description | Method | Response| |------------|--------|------------|-------------| |/| Returns main page |GET | HTML |/ | Logs a user in | POST |JSON | |/register | Registers a user |POST| JSON | |/game | Sends the main game |GET| HTML | |/levels | Sends the level page |GET| HTML | |/user/:userID | Gets details of a user |GET| JSON | |/set_level | Unlocks a level for the logged in user |GET| JSON | |/market | Sends the market page |GET| HTML| |/market | Buys a car |POST| JSON | ## Future work and improvements - Make the cars more customisable by adding car parts like: Engine, Wheels, etc. to the market. - I wasn't able to separate the levels by players, meaning that players on level 1 can still see the players in level2. To separate the players by level I would have to implement Socket.io rooms and keep a reference for each user that shows which socket room it belongs in. - Add more levels to add further progress. - The workings of the collision detection when two cars collide head-to-head is a bit unstable, producing random results in deciding which player wins and which loses the collision. One solution might be to penalise both players. <file_sep>/client/state/sockets/newPlayer.js // When a new player connects const newPlayer = (socket, player, car) => { socket.on('connect', () => { socket.emit('new-player', { x: player.sprite.body.x, y: player.sprite.body.y, car: car, angle: player.sprite.rotation, playerName: { name: player.playerName.text, x: player.playerName.x, y: player.playerName.y }, speed: { value: player.speed, x: player.speed.x, y: player.speed.y } }) }) } export default newPlayer <file_sep>/client/state/world/createWorld.js import { WORLD_SIZE } from './../../config' const { width, height } = WORLD_SIZE const worldCreator = game => { game.physics.startSystem(Phaser.Physics.P2JS) game.stage.disableVisibilityChange = true game.physics.p2.setImpactEvents(true); game.world.setBounds(0, 0, width, height) // load differetn backgrounds based on level if(game.l == "2"){ game.bg = game.add.tileSprite(0, 0, width, height, 'background2'); }else{ game.bg = game.add.tileSprite(0, 0, width, height, 'background'); } } const createMap = game => { let groundTiles = [] for (let i = 0; i <= width / 64 + 1; i++) { for (let j = 0; j <= height / 64 + 1; j++) { const groundSprite = game.add.sprite(i * 64, j * 64, 'asphalt') groundTiles.push(groundSprite) } } } export default worldCreator
7fde63bbd0ec6c8772f27f31d2359b1d99b6e186
[ "JavaScript", "Markdown" ]
10
JavaScript
PierpaoloLucarelli/CM4025
46b322b1b409393e7b21a5a8fe04d9b50f65ed78
0b42b737f88f258ccb118b30bf6f1cbdfdbe156b
refs/heads/master
<repo_name>Sanmoo/activerecord-postgres-earthdistance<file_sep>/spec/act_as_geolocated_spec.rb require 'spec_helper' describe "ActiveRecord::Base.act_as_geolocated" do describe 'ActiveRecord::Base' do context "when using .where with a model instance as a placeholder" do let(:place) { Place.create! } subject { Place.where('id = ?', place).first } after { place.destroy! } it { should == place } end end describe "#within_box" do let(:test_data) { { lat: nil, lng: nil, radius: nil } } subject { Place.within_box(test_data[:radius], test_data[:lat], test_data[:lng]) } before(:all) { @place = Place.create!(:lat => -30.0277041, :lng => -51.2287346) } after(:all) { @place.destroy } context "when query with null data" do it { should be_empty } end context "when query for the exact same point with radius 0" do let(:test_data) { { lat: -30.0277041, lng: -51.2287346 , radius: 0 } } it { should == [@place] } end context "when query for place within the box" do let(:test_data) { { radius: 4000000, lat: -27.5969039, lng: -48.5494544 } } it { should == [@place] } end context "when query for place within the box, but outside the radius" do let(:test_data) { { radius: 300000, lat: -27.5969039, lng: -48.5494544 } } it "the place shouldn't be within the radius" do Place.within_radius(test_data[:radius], test_data[:lat], test_data[:lng]).should be_empty end it { should == [@place] } end context "when query for place outside the box" do let(:test_data) { { radius: 1000, lat: -27.5969039, lng: -48.5494544 } } it { should be_empty } end context "when joining tables that are also geoloacted" do let(:test_data) { { radius: 1000, lat: -27.5969039, lng: -48.5494544 } } subject { Place.within_box(test_data[:radius], test_data[:lat], test_data[:lng]) } it "should work with objects having columns with the same name" do expect { Place.joins(:events).within_radius(test_data[:radius], test_data[:lat], test_data[:lng]).to_a }.to_not raise_error end it "should work with nested associations" do expect { Event.joins(:events).within_radius(test_data[:radius], test_data[:lat], test_data[:lng]).to_a }.to_not raise_error end end end describe "#within_radius" do let(:test_data){ {lat: nil, lng: nil, radius: nil} } subject{ Place.within_radius(test_data[:radius], test_data[:lat], test_data[:lng]) } before(:all) do @place = Place.create!(:lat => -30.0277041, :lng => -51.2287346) end after(:all) do @place.destroy end context "when query with null data" do it{ should == [] } end context "when query for the exact same point with radius 0" do let(:test_data){{lat: -30.0277041, lng: -51.2287346 , radius: 0}} it{ should == [@place] } end context "when query for place within radius" do let(:test_data){ {radius: 4000000, lat: -27.5969039, lng: -48.5494544} } it{ should == [@place] } end context "when query for place outside the radius" do let(:test_data){ {radius: 1000, lat: -27.5969039, lng: -48.5494544} } it{ should == [] } end end describe "#order_by_distance" do let(:current_location){ {lat: nil, lng: nil, radius: nil} } subject{ Place.order_by_distance(current_location[:lat], current_location[:lng]) } before(:all) do @place_1 = Place.create!(:lat => 52.370216, :lng => 4.895168) #Amsterdam @place_2 = Place.create!(:lat => 52.520007, :lng => 13.404954) #Berlin end after(:all) do @place_1.destroy @place_2.destroy end context "when sorting on distance" do let(:current_location){{lat: 51.511214, lng: 0.119824}} #London it{ should == [@place_1, @place_2] } end context "when sorting on distance from another location" do let(:current_location){{lat: 52.229676, lng: 21.012229}} #Warsaw it{ should == [@place_2, @place_1] } end end describe "#selecting_distance_from" do let(:current_location){ {lat: nil, lng: nil, radius: nil} } subject do Place. order_by_distance(current_location[:lat], current_location[:lng]). selecting_distance_from(current_location[:lat], current_location[:lng]). first. try{|p| [p.data, p.distance.to_f] } end before(:all) do @place = Place.create!(:data => 'Amsterdam', :lat => 52.370216, :lng => 4.895168) #Amsterdam end after(:all) do @place.destroy end context "when selecting distance" do let(:current_location){{lat: 52.229676, lng: 21.012229}} #Warsaw it{ should == ["Amsterdam", 1095013.87438311] } end end end
8d8a357633555cadcd234c504d537e31c89d9e83
[ "Ruby" ]
1
Ruby
Sanmoo/activerecord-postgres-earthdistance
484e9174bf2cad113baead9d10e241c7dc83cd20
765cdb1992aa54cd6282e538b057ebf1b378c505
refs/heads/main
<repo_name>kimihiro-abe/Reverse_Order_Generator<file_sep>/README.md # Reverse_Order_Generator ## 自作「Reverse_Order_Generator - 入力された文字を逆から並べる」 <img src="https://github.com/kimihiro-abe/Reverse_Order_Generator/blob/main/Reverse_Order_Generator_01.png" width="50%"> <br> ### - 序文 - 5月後半の訓練課程でList/Set/Mapやpackageなど学んだので、 「これで何かを作れないか?」と考え、 その時点の技術で制作したプログラムです。 <br> 制作してから二か月、 当時を振り返ってみると。 5月の本訓練開始時に教室が変更され、 そちらの教室ではプログラム関連書籍が数多く開架されていました。 <br> まず、この環境変化が大きかったのと、 それらの書籍をパラパラ見ては気になる箇所を写経して分析したこと、 この2点の効果が出てきた時期であったように思います。 <br> <hr> ### - このプログラムを作るにあたり考えたこと - 以下の3点を基本設計として進めることとした。 1,テキストを入力。 2,基礎となる配列をつくって、それをもとに他のパターンを捻りだす。 3,『変なロジックで結果を出力』というのを最低1つは入れる。 2個入れました。やろうと思えばもっとできるはず。 <br> どんなものが出力されるのか? 参考として以下の画像をご参照ください。 <img src="https://github.com/kimihiro-abe/Reverse_Order_Generator/blob/main/Reverse_Order_Generator_02.png" width="50%"> <br> ### - ファイルについて - 以下のパッケージの中に... package orihimik.eba; <br> 下記の4つを入れてあります。ROG_main.javaから実行してください。 - ROG_main.java メインとなるクラス。 - OrderLogic.java 入力ソースから基礎配列を作り、それを元に色々いじる処理をするクラス。 - InputIF.java 入力処理だけをするクラス。 - Function.java 表示するテキストをまとめたクラスになりました。 <hr> ### - 工夫したこと - 1, メイン部分はなるべくメソッドだけで処理することを試してみる! 前回(https://github.com/kimihiro-abe/Car_Test )でも試みてはみたものの、 あまり上手くは出来なかったので再挑戦してみました。 <br> 2, 実処理部分を別クラスにする。 これについても前回で挑戦した部分ではありますが、 幾つかのクラスで構成されたプログラムを組む方法に慣れたいので、 クラスを小分けして組むことにしました。 <br> 3, Listのremoveにrandom処理をしてランダムに文字列を取り出す。 OrderLogic.javaのpublic void srcOrder_enigma() の中で試した部分です。 結果が表示されるまでは「たぶん、出来るはず」と不安でしたが、 意図した通りの出力を確認できた時はホッとしました。 <br> ### - 苦しんだ点 - 今回、一番苦しんだ点は、 様々な順序をアレコレするロジック部分ではありませんでした。 <br> 一番悩んだ部分...それは、 OrderLogic.java内に記述内されたピリオドで分割する部分です。 public OrderLogic(String srcTxt) { //文字列受け取ってセットして基礎となる配列作る this.srcTxt = srcTxt; srcOrder = srcTxt.split("\\."); //ピリオドで分割する時は、こうしないと出来ない。 } 検索で調べてみたら割とすぐに解決したのですが、 「ピリオドが原因?」という考えにいたるまでに少々時間がかかりました。 <br> そして、私と同様の点で躓いた方のサイトの記載に、 「正規表現をきちんと理解している人ならこんな間違いをしないんだろうなあ…。」 とあったのが、自分の心にも深くささりました。 <br> とはいえ、 『こういうケースもある』という知見が得られたのは大きいので、 同じミスを犯さないよう、この経験を生かそうと思います。 <br> <hr> ### - 今回の挑戦で得られた物 - 1, List機能を使用したコードを設計出来たこと。 2, 正規表現についての知識の重要性。 3, 機能ごとのクラス分け。 4, エラーが出なくなるまでトライ&エラーしたこと。 5, 仕様通りに動くまでのものに仕上げたきったこと。 上記の5点が今回得られた物になります。 <br> 作っているものは、技術レベルもJavaの基礎部分ではあると思います。 しかし、自分で取り組んで対峙してから見えてくる問題が確かにあり、 世間的には既知ではあっても、自分が解決すべき問題として真摯に取り組むことが、 自身の成長にとって何より重要だという思いをあらたにしました。 <br> 今回は、このへんで...<file_sep>/orihimik/eba/ROG_main.java package orihimik.eba; public class ROG_main { //Reverse_Order_Generator static int count; public static void main(String[] args) { //メイン部分はなるべくメソッドだけで処理することを試してみる Function.title(); //タイトル画面表示 // 入力機構:打ち込んだものを、全部文字列としてStringに格納 InputIF iIF = new InputIF(); //入力機構を使うためのインスタンス生成 while(Function.ctrl_true()) { //試しにメソッドでtrueを返して貰うのをテスト String srcTxt = iIF.inputIF(); //入力機構で入力した結果をsrcTxtに代入 // 今回のミッションとしてコンストラクタ使う OrderLogic oLogic = new OrderLogic(srcTxt); //System.out.println(); // ■順おーダァー : kominato.amaariki srcOrder System.out.println("■順おーダァー : 今、入力したそのものダァー "); //表示部分の文章は遊び心で oLogic.srcOrder(); //ソースをまんま表示するダァー // ■逆おーダァー : amaariki.kominato rOrder_01 ikiraama.otanimoki System.out.println("■逆おーダァー : "); oLogic.rOrder_01(); // ■順逆おーダァー :otanimok.ikirama rOrder_02 System.out.println("■順逆おーダァー : "); oLogic.rOrder_02(); // ■逆逆おーダァー : ikirama.otanimok rOrder_03 System.out.println("■逆逆おーダァー : "); oLogic.rOrder_03(); // ■順おーダァーCbyC : 順おーダァーを1文字ずつカンマで区切る(Character by character) System.out.println("■順おーダァーCbyC : CbyCとは「一文字ずつ」をGoogle翻訳した結果の略ダァー"); oLogic.srcOrder_CbC(); // ■順乱おーダァー : ソースのランダム並び替え enigma_01 System.out.println("■順乱おーダァー : 順おーダァーの中身をランダムしたダァー"); oLogic.srcOrder_enigma(); // ■継続促しテキストの表示 count++; if (count % 2 ==0) { Function.loop_txt2(); } else if (count % 7 ==0){ Function.loop_txt3(); } else { Function.loop_txt1(); } } //デバッグ用エンド確認処理 Function.end(); } }
3fa01b319dd06b292db38ed0a25c39f2ab925500
[ "Markdown", "Java" ]
2
Markdown
kimihiro-abe/Reverse_Order_Generator
714574973904c90fa2e532531721e6ea2572d4c3
6d46a3247c6c26ff59e748f8f7d008b27526980c
refs/heads/main
<repo_name>vibhug507/Graduate-Admission-Prediction<file_sep>/README.md # Graduate-Admission-Prediction A ML model to predict the chances of graduate admission of a candidate in US based on his/her CGPA,GRE Score,TOEFL Score,University Rating,SOP Strength,LOR Strength and Research Work. Models Checked : 1) Linear Regression 2) Ridge Regression 3) Lasso Regression 4) Support Vector Machines (SVM) 5) Random Forest 6) Decision Trees 7) K Nearest Neighbors (KNN) <file_sep>/app/app.py from flask import Flask,render_template,request import numpy as np from joblib import load model = load('model.joblib') app = Flask(__name__) @app.route("/",methods = ['GET','POST']) def hello_world(): if request.method == 'GET': return render_template('index.html') else: cgpa = float(request.form['CGPA']) toeflScore = float(request.form['TOEFL Score']) greScore = float(request.form['GRE Score']) universityRating = float(request.form['University Rating']) sop = float(request.form['SOP']) lor = float(request.form['LOR']) research = float(request.form['Research']) chanceOfAdmit = model.predict([[universityRating,sop,lor,cgpa,research]]) if chanceOfAdmit[0] < 0.0: return ("Sorry, but your chances of admission are very low.\n") elif chanceOfAdmit > 1.0: return ("You might have entered incorrect data.\n") else: return ("Your chances of admission are " + str(chanceOfAdmit[0]) + ".\n")
a5222840abb4ea574438054c8b5cf79fbb4eba02
[ "Markdown", "Python" ]
2
Markdown
vibhug507/Graduate-Admission-Prediction
ad3f12231a054b5981db1e2a7ace53e4889f3b17
1770ea3104968f2e412c7fb696529c159ed49e4a
refs/heads/master
<file_sep>gstreamer-scripts ================= Some gstreamer test scripts 09/07/2014 - The linux_rtp_{streamer,player} scripts are the most up to date and current, tested working on ubuntu 14.04 LTS with gstreamer 1.2.3 Can be used by specifying the ip address of the other host as only argument <file_sep>#!/bin/sh if [ $# -ne 3 ]; then echo "Usage: $0 <ip> <port> <mountpoint>" exit 1 fi stty -echo printf "Password:" read ICECAST_PASSWORD stty echo printf "\n" gst-launch-1.0 v4l2src do-timestamp=true ! video/x-raw,width=\(int\)320,height=\(int\)240,framerate=\(fraction\)10/1 ! queue leaky=1 !\ theoraenc bitrate=400 quality=32 ! queue leaky=1 ! oggmux name=mux \ alsasrc ! queue leaky=1 ! audioconvert ! vorbisenc quality=0.1 ! mux. \ mux. ! queue leaky=1 ! shout2send ip=${1} port=${2} mount=/${3} password=${<PASSWORD>} sync=true async=true <file_sep>#!/bin/bash DST=$1 gst-launch-1.0 -v\ rtpbin name=rtpbin \ udpsrc caps="application/x-rtp,media=(string)video, clock-rate=(int)90000, encoding-name=(string)MP4V-ES" \ port=5000 ! rtpbin.recv_rtp_sink_0 \ rtpbin. ! rtpmp4vdepay ! mpeg4videoparse ! avdec_mpeg4 max-threads=1 ! videoconvert ! videoscale ! xvimagesink sync=true async=true \ udpsrc port=5001 ! rtpbin.recv_rtcp_sink_0 \ rtpbin.send_rtcp_src_0 ! udpsink port=5005 sync=false async=false \ udpsrc caps="application/x-rtp,media=(string)audio, clock-rate=(int)90000, encoding-name=(string)MPA, encoding-params=(string)1" \ port=5002 ! rtpbin.recv_rtp_sink_1 \ rtpbin. ! rtpmpadepay ! mad ! audioresample ! audioconvert ! alsasink sync=true async=true \ udpsrc port=5003 ! rtpbin.recv_rtcp_sink_1 \ rtpbin.send_rtcp_src_1 ! udpsink host=$DST port=5007 sync=false async=false <file_sep>#!/bin/bash DST=$1 gst-launch-1.0 -v rtpbin name=rtpbin \ v4l2src ! video/x-raw,width=\(int\)320,height=\(int\)240,framerate=\(fraction\)30/1 ! tee name="t" ! videoconvert ! \ videoscale ! videorate ! avenc_mpeg4 max-key-interval=1 max-bframes=2 ! rtpmp4vpay ! rtpbin.send_rtp_sink_0 \ rtpbin.send_rtp_src_0 ! udpsink host=$DST port=5000 sync=false async=false \ rtpbin.send_rtcp_src_0 ! udpsink host=$DST port=5001 sync=false async=false \ udpsrc port=5005 ! rtpbin.recv_rtcp_sink_0 \ alsasrc device="default" ! audio/x-raw ! audiorate ! audioresample ! \ lamemp3enc bitrate=128 target=0 quality=5 encoding-engine-quality=1 mono=true ! rtpmpapay ! rtpbin.send_rtp_sink_1 \ rtpbin.send_rtp_src_1 ! udpsink host=$DST port=5002 sync=false async=false \ rtpbin.send_rtcp_src_1 ! udpsink host=$DST port=5003 sync=false async=false \ udpsrc port=5007 ! rtpbin.recv_rtcp_sink_1 \ t. ! xvimagesink sync=true async=true <file_sep>#!/bin/bash DST=$1 gst-launch-1.0 -v rtpbin name=rtpbin \ v4l2src ! video/x-raw,width=320,height=240,framerate=10/1 ! autovideoconvert ! \ x264enc pass=qual quantizer=20 tune=zerolatency ! rtph264pay ! rtpbin.send_rtp_sink_0 \ rtpbin.send_rtp_src_0 ! udpsink host=$DST port=5000 sync=false async=false \ rtpbin.send_rtcp_src_0 ! udpsink host=$DST port=5001 sync=false async=false \ udpsrc port=5005 ! rtpbin.recv_rtcp_sink_0 \ alsasrc do-timestamp=true ! audio/x-raw,rate=24000 ! speexenc vbr=true quality=10 ! rtpspeexpay ! rtpbin.send_rtp_sink_1 \ rtpbin.send_rtp_src_1 ! udpsink host=$DST port=5002 sync=false async=false \ rtpbin.send_rtcp_src_1 ! udpsink host=$DST port=5003 sync=false async=false \ udpsrc port=5007 ! rtpbin.recv_rtcp_sink_1 <file_sep>#!/bin/bash DST=${1:-pair07} scp sender* receiver* $DST:. <file_sep>#!/bin/bash DST=$1 gst-launch-0.10 -v gstrtpbin name=rtpbin \ v4l2src ! video/x-raw-yuv,width=\(int\)320,height=\(int\)240,framerate=\(fraction\)30/1 ! ffmpegcolorspace ! \ x264enc pass=qual quantizer=20 tune=zerolatency ! rtph264pay ! rtpbin.send_rtp_sink_0 \ rtpbin.send_rtp_src_0 ! udpsink host=$DST port=5000 sync=false async=false \ rtpbin.send_rtcp_src_0 ! udpsink host=$DST port=5001 sync=false async=false \ udpsrc port=5005 ! rtpbin.recv_rtcp_sink_0 \ alsasrc device="default" ! audio/x-raw-int ! audiorate ! audioresample ! \ ffenc_mp2 ! rtpmpapay ! rtpbin.send_rtp_sink_1 \ rtpbin.send_rtp_src_1 ! udpsink host=$DST port=5002 sync=false async=false \ rtpbin.send_rtcp_src_1 ! udpsink host=$DST port=5003 sync=false async=false \ udpsrc port=5007 ! rtpbin.recv_rtcp_sink_1 <file_sep>#!/bin/bash VIDEO_DATA_PORT=5000 VIDEO_CTRL_PORT=5001 AUDIO_DATA_PORT=5002 AUDIO_CTRL_PORT=5003 VIDEO_RETC_PORT=5004 AUDIO_RETC_PORT=5005 IP=${1} gst-launch-1.0 -v rtpbin name=bin latency=80\ udpsrc port=${VIDEO_DATA_PORT} ! application/x-rtp,media=\(string\)video,clock-rate=\(int\)90000,encoding-name=\(string\)MP4V-ES,encoding-params=\(string\)1 ! bin.recv_rtp_sink_0 \ udpsrc port=${VIDEO_CTRL_PORT} ! bin.recv_rtcp_sink_0 \ bin.send_rtcp_src_0 ! udpsink host=${IP} port=${VIDEO_RETC_PORT} sync=false async=false \ udpsrc port=${AUDIO_DATA_PORT} ! application/x-rtp,media=\(string\)audio,clock-rate=\(int\)90000,encoding-name=\(string\)MPA ! bin.recv_rtp_sink_1 \ udpsrc port=${AUDIO_CTRL_PORT} ! bin.recv_rtcp_sink_1 \ bin.send_rtcp_src_1 ! udpsink host=${IP} port=${AUDIO_RETC_PORT} sync=false async=false \ bin. ! rtpmpadepay ! mpegaudioparse ! mad ! audioconvert ! audioresample ! alsasink sync=true async=true \ bin. ! rtpmp4vdepay ! avdec_mpeg4 ! videoconvert ! xvimagesink sync=false async=false <file_sep>#!/bin/bash VIDEO_DATA_PORT=5000 VIDEO_CTRL_PORT=5001 AUDIO_DATA_PORT=5002 AUDIO_CTRL_PORT=5003 VIDEO_RETC_PORT=5004 AUDIO_RETC_PORT=5005 IP=${1} gst-launch-1.0 -v rtpbin name=rtpbin latency=80\ v4l2src ! video/x-raw,format=\(string\)YUY2,width=\(int\)320,height=\(int\)240,framerate=\(fraction\)30/1 !\ videoconvert ! videoscale ! avenc_mpeg4 max-key-interval=1 max-bframes=2 ! rtpmp4vpay config-interval=2 ! rtpbin.send_rtp_sink_0\ rtpbin.send_rtp_src_0 ! udpsink host=${IP} port=${VIDEO_DATA_PORT} sync=false async=false\ rtpbin.send_rtcp_src_0 ! udpsink host=${IP} port=${VIDEO_CTRL_PORT} sync=false async=false\ udpsrc port=${VIDEO_RETC_PORT} ! rtpbin.recv_rtcp_sink_0\ alsasrc device=\"hw:0,0\" ! audio/x-raw,format=\(string\)S16LE ! audiorate ! audioresample ! volume volume=4.0 ! lamemp3enc bitrate=128 target=0 quality=5 encoding-engine-quality=1 mono=true ! rtpmpapay ! rtpbin.send_rtp_sink_1\ rtpbin.send_rtp_src_1 ! udpsink host=${IP} port=${AUDIO_DATA_PORT} sync=false async=false\ rtpbin.send_rtcp_src_1 ! udpsink host=${IP} port=${AUDIO_CTRL_PORT} sync=false async=false\ udpsrc port=${AUDIO_RETC_PORT} ! rtpbin.recv_rtcp_sink_1
95f4aa6fa19ede8b16d2ea1937679898cbe9138a
[ "Markdown", "Shell" ]
9
Markdown
uovobw/gstreamer-scripts
bb23d72a3f6d5286c1b8be251ead438da0653ef8
06b58f1a1172831015dfa2c0ccf5a39d5a7843ed
refs/heads/master
<repo_name>phaneven/moodle-crawler<file_sep>/README.md # moodle-crawler scraping lecture links from UNSW moodle ## commond line command line: casper moodle.js ## use put username and password into code <file_sep>/moodle.js var fs = require('fs'); var casper = require('casper').create({ verbose: true, pageSettings: { webSecurityEnabled: false } // logLevel: "debug" }); var username = ''; var password = ''; var url = 'https://moodle.telt.unsw.edu.au/login/'; var course_titles = []; var course_links = []; var video_links = []; var course = {}; function getCourses() { var courses = document.querySelectorAll('h2.title a'); return [Array.prototype.map.call(courses, function(e) { return e.getAttribute('title'); }), Array.prototype.map.call(courses, function(e) { return e.getAttribute('href'); })] } function getVideoPages() { var page = document.querySelector('div.activityinstance a'); return page.getAttribute('href'); } function getVideos() { var videos = document.querySelectorAll('div.menu-opener'); } function getClassNumber() { return document.querySelectorAll('.menu-opener div').length; } function clickVideoButtons(i) { document.querySelectorAll('.menu-opener')[i].click(); } casper.start(); casper.thenOpen(url); casper.then(function(){ casper.echo('crawling ' + this.getTitle() + ' ... '); casper.waitForSelector('iframe', function () { casper.withFrame(0, function() { casper.echo('login ...'); casper.sendKeys('input#username', username); casper.sendKeys('input#password', password); casper.thenClick('div.visible-xs input#submit'); }); }, function () { casper.echo ('cannot load frame').die(); }, 1000); }) casper.then(function(){ casper.echo('crawling ' + this.getTitle() + ' ... '); casper.waitForSelector('.course_list', function () { course_titles = casper.evaluate(getCourses)[0]; course_links = casper.evaluate(getCourses)[1]; casper.echo("\nCOURSES: "); for (i in course_titles) { casper.echo(course_titles[i] + ' : ' + course_links[i]); } }); }) // use thenOpen to go to the next link casper.then(function() { casper.echo("\nCOURSES: "); for (i in course_titles) { casper.thenOpen(course_links[i]); casper.waitForSelector('.activityinstance', function () { casper.echo('Jump to ' + this.getTitle() + ' ... ' + 'get video page link'); // video_links.push(casper.evaluate(getVideoPages)); if (this.exists('div.activityinstance a')) { //check whether has video button // this.echo('debug...'); this.click('div.activityinstance a span'); } // casper.then(function() {this.back()}); // go back to dashboard // casper.then(function() {casper.echo('Jump back to ' + this.getTitle() + ' ... ');}); }); break; } }) casper.waitForPopup(0, null, null, 100000); casper.withPopup(0, function() { var classNum = 0; this.waitForSelector('.main-content', function(){ classNum = this.evaluate(getClassNumber); this.echo(classNum); var count = 1; this.repeat(classNum, function() { this.waitForSelector('.content',function(){ this.viewport(1600,1000); // this.echo(this.exists('div.class-row:nth-child('+ count +')')); // this.echo(this.exists('div.class-row:nth-child('+ count +') div.menu-opener')); this.click('div.class-row:nth-child('+ count +') div.menu-opener div'); this.capture('click'+count+'.png'); // this.echo(this.exists('.menu-items')); this.then(function() { this.wait(1000, function() { this.capture('download'+count+'.png'); this.clickLabel('Download original', 'a'); }); }); this.then(function() { // this.click('select'); // this.capture('hd.png'); // this.echo(this.exists('div.select-wrapper select option:nth-child(2)')); // this.click('div.select-wrapper select option:nth-child(2)'); //hd // this.click('.right a'); // this.echo(this.getCurrentUrl()); // this.echo(this.evaluate(function(){ // return 'https://echo360.org.au' + document.querySelector('.right a').getAttribute('href'); // })); this.wait(3000, function(){ var downloadUrl = this.evaluate(function(){ return 'https://echo360.org.au' + document.querySelector('.right a').getAttribute('href'); }); this.echo('lecture ' + count + ': ' + downloadUrl); this.click('.right a') //click download button count ++; }) }); }); }); }) }); casper.run(function () { casper.echo('Done.').exit(); });
3d76d44e4362c26a4035aed68917a58e4322c871
[ "Markdown", "JavaScript" ]
2
Markdown
phaneven/moodle-crawler
d7c5b9ff3122157aeb150e34057f2851c4d1484f
05538e8d40b6141a111b2745744046a49554cc58
refs/heads/master
<file_sep>package com.org.codingexercise.uptake; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import com.uptake.codingexercise.pages.Careers; import com.uptake.codingexercise.pages.Home; import junit.framework.Assert; public class PageTest { WebDriver driver; @Before public void setup() { // using chrome // please update chromedriver.exe path while testing System.setProperty("webdriver.chrome.driver", "D:\\Chrome\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://www.uptake.com/"); } @Test public void clickCareer() { Home home = new Home(driver); home.clickCareers(); Careers career = new Careers(driver); Assert.assertTrue(career.isPageOpened()); career.clickJoinus(); } @After public void quit() { driver.quit(); } } <file_sep>package com.uptake.codingexercise.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class Careers { private WebDriver driver; @FindBy(xpath ="/html/body/div[2]/div[1]/div[2]/div/h1") private WebElement heading; @FindBy(linkText = "JOIN US") private WebElement joinus; public Careers(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } public boolean isPageOpened(){ return heading.getText().toString().contains("OUR TEAM"); } public void clickJoinus(){ joinus.click(); } }
ad8515d3a5b48f6dc033f66493162f37b3c67c23
[ "Java" ]
2
Java
saideepak18/uptakeexercise
b536ba003939108d67538e2ab765588f1f63fc90
fbd04e21df0f31ee2b70093061222cb1ae7811dc
refs/heads/master
<repo_name>mauroere/upload-files-node-react-formidable<file_sep>/README.md # Upload de imágenes y archivos en React y NodeJs _Sistema de Upload de archivos utilizando tecnologías React, NodeJs y Formidble. _ ## Comenzando 🚀 _Estas instrucciones te permitirán obtener una copia del proyecto en funcionamiento en tu máquina local para propósitos de desarrollo y pruebas._ Mira **Deployment** para conocer como desplegar el proyecto. ### Pre-requisitos 📋 _Nodejs_ _React_ ### Instalación 🔧 _Descarga el GIT_ _Ejecutá "npm i" para instalar los módulos dentro de la carpeta "app" y la carpeta "server"_ _Ejecutá npm start_ ## Construido con 🛠️ _Menciona las herramientas que utilizaste para crear tu proyecto_ - [NODE](https://nodejs.org/es/) - [REACT](https://es.reactjs.org/) - [FORMIDABLE](https://www.npmjs.com/package/formidable) ## Contribuyendo 🖇️ ## Licencia 📄 Este proyecto está bajo la Licencia MIT - mira el archivo [LICENSE.md](LICENSE.md) para detalles ## Expresiones de Gratitud 🎁 - Comenta a otros sobre este proyecto 📢 - Invita una cerveza 🍺 o un café ☕ a alguien del equipo. - Da las gracias públicamente 🤓. - etc. --- ⌨️ con ❤️ por [<NAME>](https://github.com/mauroere) 😊 <file_sep>/server/upload.js const IncomingForm = require("formidable").IncomingForm; const fs = require("fs"); var path = require("path"); module.exports = function upload(req, res) { var form = new IncomingForm(); var curTime = new Date(); var curTime2 = curTime.getTime(); form.multiples = true; form.uploadDir = path.join(__dirname, "../server/upload"); form.on("file", (field, file) => { var fileName = curTime2 + "__" + file.name; fs.rename(file.path, path.join(form.uploadDir, fileName), function (err) { if (!err) { return res.send(fileName); } }); console.log(fileName); }); // log any errors that occur form.on("error", function (err) { console.log("An error has occured: \n" + err); }); // parse the incoming request containing the form data form.parse(req); };
d226748fb4519ec44e2e940d362d3d8f2721d1aa
[ "Markdown", "JavaScript" ]
2
Markdown
mauroere/upload-files-node-react-formidable
e88698eddb39e1965a77e6cc597b98ebbc31945d
953ecb199358bcc4fdc80ac1e49924bcf9e8049d
refs/heads/main
<repo_name>adelek0726/adelek0726<file_sep>/README.md # sync_interns_task_2 Face Mask Detection <file_sep>/mask_images.py # Collect Images Wearing A Mask # import libraries import cv2 import numpy as np #import front face detector face_classifer = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # open camera cap = cv2.VideoCapture(0) # initialize empty array to store mask images dataset = [] # use camera to capture images while cap.isOpened(): ret, frame = cap.read() if ret: gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # images without dimensions face_detect = face_classifer.detectMultiScale(gray_img, 1.05, 6) # draw rectangle on the image for x, y,w ,h in face_detect: cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), thickness=3) # collect each individual detected images face = frame[y: y+h, x:x+w, : ] # resize all images to the same size face = cv2.resize(face, (50, 50)) # number of detected images print(len(dataset)) # collect 350 faces if len(dataset) < 350: dataset.append(face) cv2.imshow('Frame', frame) # press ESC to stop or collect 350 pics if cv2.waitKey(1) == 27 or len(dataset ) == 350: break # save the collected data np.save('mask.npy', dataset) cap.release() cv2.destroyAllWindows() <file_sep>/mask_detector.py # Mask Detection Live Demo # import all libraries needed import cv2 import numpy as np from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA from sklearn.linear_model import LogisticRegression # load the dataset with_mask = np.load('mask.npy') without_mask = np.load('no_mask.npy') # reshape the data with_mask = with_mask.reshape(350, 50*50*3) without_mask = without_mask.reshape(350, 50*50*3) # concatenate using numpy combine_set = np.r_[with_mask, without_mask] # make zeros array of the combined data labels = np.zeros(combine_set.shape[0]) # assign 1 to tag images without a mask labels[350: ] = 1 # split the data, to train and test sets x_train, x_test, y_train, y_test = train_test_split(combine_set, labels, test_size=0.20) # reduce the colors using PCA pca = PCA(n_components=3) x_train = pca.fit_transform(x_train) # use classification model to train data lr = LogisticRegression() lr.fit(x_train, y_train) # reduce the size of x_test x_test = pca.transform(x_test) # check the predictions of x_test y_pred = lr.predict(x_test) # evaluate the model class_rep = classification_report(y_test, y_pred) print('Report', class_rep) ##### Use camera # import front face detector face_Classifer = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") # open the camera cap = cv2.VideoCapture(0) # check dictionary, 0 = mask and 1 = no mask names = {0: "Mask", 1: "No Mask"} while cap.isOpened(): ret, frame = cap.read() if ret: gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face_detect = face_Classifer.detectMultiScale(gray_img, 1.1, 4) # draw rectangle on images for x, y,w ,h in face_detect: cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), thickness=3) # copying the images face = frame[y:y+h, x: x+w, :] # resize images to 50 by 50 face = cv2.resize(face, (50, 50)) # reshape images face = face.reshape(1, -1) # size reduction face = pca.transform(face) # make predictions prediction = lr.predict(face) # 0 is mask, 1 is no mask to word_preds word_preds = names[int(prediction)] print(word_preds) # put text on the rectangle font = cv2.FONT_HERSHEY_PLAIN cv2.putText(frame, word_preds, (x, y), font, 1, (0, 255, 0), 2) cv2.imshow('Frame', frame) # press ESC to stop live capture if cv2.waitKey(1) == 27: break cap.release() cv2.destroyAllWindows()
4af205d600c0965208ac56f193d247d959b88f51
[ "Markdown", "Python" ]
3
Markdown
adelek0726/adelek0726
e9384e2b885d8381a62dc53e3f0dbfec47a544c2
a603fbb38c0f500718374f6294b4e6a7ae32b397
refs/heads/master
<file_sep># Blockchain Data Blockchain has the potential to change the way that the world approaches data. Develop Blockchain skills by understanding the data model behind Blockchain by developing your own simplified private blockchain. ## Getting Started ### Prerequisites Installing Node and NPM is pretty straightforward using the installer package available from the (Node.js® web site)[https://nodejs.org/en/]. ### Deploy your project - Use NPM to install the dependencies. ``` npm install . ``` - Run ``` npm start ``` ### Testing ``` npm test ``` ## Web Services ### Framework [express.js](https://expressjs.com/) ### API - GET Block Information Endpoint ``` http://localhost:8000/block/{blockHeight} ``` Request: None Response: application/json Block ``` Response Example: {"hash":"49cce61ec3e6ae664514d5fa5722d86069cf981318fc303750ce66032d0acff3","height":0,"body":"First block in the chain - Genesis block","time":"1530311457","previousBlockHash":""} ``` - POST add Block Endpoint ``` http://localhost:8000/block ``` Request: {"body":"block body contents"} Response: application/json Created Block ``` Response Example: {"hash":"9327355aa9523e3e41ffc8b9cdb566591b259fd5ed017a16450c22f4b6a2c258","height":2,"body":"block body contents","time":"1531787866","previousBlockHash":"ffaffeb2330a12397acc069791323783ef1a1c8aab17ccf2d6788cdab0360b90"} ```<file_sep>const express = require('express'); const router = express.Router(); const simpleChain = require('../app/simpleChain'); router.get('/block/:blockHeight', function (req, res, next) { const blockHeight = req.params.blockHeight; simpleChain.Blockchain.getBlock(blockHeight).then((jsonStr) => { res.send(jsonStr); }); }); router.post('/block', function (req, res, next) { const body = req.body.body; simpleChain.Blockchain.addBlock(new simpleChain.Block(body)).then((jsonStr) => { res.send(jsonStr); }); }); module.exports = router;
41c82686e42776d4c0fb5be9d00659cea85560f6
[ "Markdown", "JavaScript" ]
2
Markdown
linxinzhe/udacity-BDND-web-services
e92647d2e9fe3d741a4d126672982f9e4fe35764
a0f616b61c42c8ca6a080c7030b0c73c9c9b30d5
refs/heads/master
<repo_name>mrkirkmorgan/personal-website<file_sep>/scripts/animations.js // Ensures that the bobbing arrow disappears when the user isn't at the top of the page $(document).on("scroll", function() { var pageTop = $(document).scrollTop() if(pageTop === 0) { $(".arrow").fadeIn("slow"); } else { $(".arrow").fadeOut("slow"); } }) // Adds listeners to the outer-halo buttons so the active state can be switched on click $(document).ready(function() { // Click action handler $(".resume-button").click(function(e) { // Remove active class from the old button and section (effectively hides them) $(".active").removeClass("active"); // Add active class to the new button and section (effectively displays them) $("#" + e.currentTarget.id + "-section").addClass("active"); $(this).addClass("active"); }); $(".comment-button").click(function(e) { $(".dissappear-box").slideToggle(); }); // Handles the submission of "Leave a Comment" form $("#submit-button").on("click", function(e) { e.preventDefault(); var data = {Sender : $("#email-box").val(), Message: $("#message-box").val()}; if ($("#subject-box").val().length == 0) { $.ajax({ url: "//formspree.io/mvooeglp/", method: "POST", data: data, dataType: "json", }).done(() => { $(".dissappear-box").slideToggle(); $(".comment-button").fadeTo("fast", 0); $(".success-msg").fadeIn("slow"); setTimeout(() => { $(".comment-button").fadeTo("slow",1); $(".success-msg").fadeOut("fast"); }, 7000); $("#email-box").val(""); $("#message-box").val(""); }).fail(() => { alert('This request failed, please try again.') }); return false; } }); })<file_sep>/design/background-design.md # Background Design ### General Design With respect to the background, I wanted to stay way from using images, and would like the background to primarily use colors and abstract shapes. I believe this looks more modern and allows for use of subtle animations that will make the background seem more dynamic and intriguing. With later iterations of the website I'll probably introduce more dynamic and less abstrat themes, but for now given my limited knowledge of CSS & JS animations, I'll stick to abstract and simpler. ### Wave Design One of the designs I thought of that could fill larger blank spaces on the webpage is a wave animation that can serve as interesting way to transition color changes of the background. These waves will be generated dynamically and utilize HTML Canvases to render the animations. Placing two or three waves together could be an interesting graphic that can create a changing "middle" line that changes between them. Waves will have to be drawn in parts that utilize one sin or cos curve per section. Wave object will need to be smart enough to know when it needs to generate new curves and when to delete the ones that have already passed through the banner. In this sense the waves can move in a given direction giving them a flow property. Additionally, I plan on implementing functionality that will allow the waves to oscillate giving them movement on an extra dimension. ### Block Move Design Another design I'm thinking of, is having various colored rectangles (fitting within the color scheme) that move in various random directions across the screen. They will sit on a lower z-index than the waves and will appear to move out of sight underneath them. The blocks on creation will have a random number generated between 1 and 4 and each option will correspond to a given side of the body. When this number is determined, another number between 1 and 3 will be generated determining the possible options of the blocks in that they can go directional in either way or straight down the path. Once the starting position and direction is assigned to the block, the block will have the corresponding @keyframe CSS animation assigned to it. There are 8 CSS animations for block movement, one for each direction. Another random number will be generated determining the speed of the animation which will be used when the animation property is assgined to the dynamically created block. Colors will also need to be randomly generated. The number of generated blocks will be limited however as I don't want too many simultaneously moving blocks on the screen. <file_sep>/README.md # personal-website A personal website to showcase skills and hobbies to potential employers or every day passerby's. <file_sep>/design/design.md # My Personal Website ### Game Plan This is a project that I've been developing on and off over the last few years and I feel as though its time to finally put the whole thing together. I'm going to keep the design rather simple and only have a navigational map and a descrpiton for each corresponding page. I'll establish a kind of "versioning" system for the site and as versions are incremented, I'll add larger parts to the website. I'm going to use the previous codebase as a starting point since the DNS and CNAME is already set up as well as the certificate for the https:// connection. Not to mention the code is not that far along and it already consists of some of the basic components for the site. ### Purpose This website is simply meant to showcase my projects to the world. It's a window into what I work on and a way to market what I do to people who are curious. These projects primarily pretain to Computer Science and maybe some Finance projects, but I'd also like to use it as a way to showcase some of my more astistically oriented projects. Perhaps this could eventually include things like music I write/make, photography I do, game development projects I work on, writing I work on, lesson sets I work on, and maybe even a blog of sorts. Consider it a personal brand of sorts. I recoginze this is a wide and varying set of subjects, but if I can find an intuitive way to string it all together, then it could be a great resource for potential employers, collaborators, and curious passerbys. ### Versions ##### Version 1.0 The first version I'm aiming to just be a static single-page website. It will consist of index.html which will contain a section based page that will include a general landing area, an about section, a projects section, and a contact section. The reason I'm keeping the website so small in the beginning is because I don't yet have a lot of content to put in it. I have barely any projects to list and as of the moment, have no photography to put up, nothing to say for a blog, and no music. This way I can get a basic version up for potential employers so that they can see at least I have pending projects and naturally a personal website is also a cool addition to a portfolio. Finally, I don't have a lot of photos to use that are super high quality for a website. ### Tech to Be Used I'm going to build this website as plainly and simply as I can. No confusing/fancy frameworks or crazy libraries. I'll stick to regular ol' HTML, CSS, and JavaScript. The only library I'll likely use is JQuery. I'll use a CDN for JQuery. The website will be hosted using GitHub pages and the DNS is managed by NameCheap. The website uses a custom domain and it can be found at https://www.mrkirkmorgan.com.
d3eb77a851c0372e0c64f118f969ec833e9e7b2d
[ "JavaScript", "Markdown" ]
4
JavaScript
mrkirkmorgan/personal-website
7a93803b23bcdd62bd5e757aed932266374fe124
441d5d4866abec001fd22982f59090e9a4e9426a
refs/heads/master
<file_sep>--- title: "Missing value Imputation" author: <NAME> date: 29/Nov/2019 output: html_document: theme: paper highlight: tango toc: true toc_depth: 3 number_sections: true --- ```{r global_options, include=FALSE} knitr::opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE) library(tidyverse) library(knitr) library(readxl) ``` # Import Data ```{r} baseline_30NA <- read_excel("~/Desktop/datasets/processed/Filtered Attributes Baseline.xlsx", sheet = 'updated_folup_NA30_baseline') ``` ```{r} admission_30NA <- read_excel("~/Desktop/datasets/processed/Filtered Attributes Admission.xlsx", sheet = 'NA2030_filtered_admission') ``` admission_lab: only attributes related to lab measurements ```{r Create admission_lab dataframe} names(admission_30NA)[names(admission_30NA) == "READMISSION_DAYS"] <- "DAYS_READMISSION" admission_lab <- select(admission_30NA, -ends_with("_DAYS")) %>% select(rID, DAYS_READMISSION, WBC:GLUCOSE) names(admission_lab)[names(admission_lab) == "NA"] <- "N_A" admission_lab$DAYS_READMISSION[which(is.na(admission_lab$DAYS_READMISSION))] <- 0 ``` ```{r} summary(admission_lab) ``` # Remove Outliers ```{r Deal with outliers} remove_outliers <- function(admission_lab) { for (measure in names(admission_lab)[seq(3,9)]){ # eliminate outliers iqr <- IQR(admission_lab[[measure]], na.rm = TRUE) Q <- quantile(admission_lab[[measure]], probs=c(0.25, 0.75), na.rm = TRUE) admission_lab[[measure]][which((admission_lab[[measure]] < (Q[1] - 1.5*iqr)) | (admission_lab[[measure]] > (Q[2]+1.5*iqr)))] <- NA_real_ } return(admission_lab) } ``` ```{r} admission_lab <- remove_outliers(admission_lab) ``` ```{r} summary(admission_lab) ``` # Impute Measurements ```{r Mean value imputation} imput_wbc <- admission_lab %>% group_by(rID) %>% summarise(Mean = mean(WBC, na.rm = TRUE)) imput_hgb <- admission_lab %>% group_by(rID) %>% summarise(Mean = mean(HGB, na.rm = TRUE)) imput_cr <- admission_lab %>% group_by(rID) %>% summarise(Mean = mean(CR, na.rm = TRUE)) imput_egfr <- admission_lab %>% group_by(rID) %>% summarise(Mean = mean(EGFR, na.rm = TRUE)) imput_k <- admission_lab %>% group_by(rID) %>% summarise(Mean = mean(K, na.rm = TRUE)) imput_na <- admission_lab %>% group_by(rID) %>% summarise(Mean = mean(N_A, na.rm = TRUE)) imput_glucose <- admission_lab %>% group_by(rID) %>% summarise(Mean = mean(GLUCOSE, na.rm = TRUE)) for (val in seq(1, dim(imput_glucose)[1])) { if(dim(admission_lab[(admission_lab$rID == imput_wbc$rID[val]) & (is.na(admission_lab$WBC)),])[1]!=0){ admission_lab$WBC[which((admission_lab$rID == imput_wbc$rID[val]) & (is.na(admission_lab$WBC)))] <- imput_wbc$Mean[val] }else{ next } } for (val in seq(1, dim(imput_glucose)[1])) { if(dim(admission_lab[(admission_lab$rID == imput_hgb$rID[val]) & (is.na(admission_lab$HGB)),])[1]!=0){ admission_lab$HGB[which((admission_lab$rID == imput_hgb$rID[val]) & (is.na(admission_lab$HGB)))] <- imput_hgb$Mean[val] }else{ next } } for (val in seq(1, dim(imput_glucose)[1])) { if(dim(admission_lab[(admission_lab$rID == imput_cr$rID[val]) & (is.na(admission_lab$CR)),])[1]!=0){ admission_lab$CR[which((admission_lab$rID == imput_cr$rID[val]) & (is.na(admission_lab$CR)))] <- imput_cr$Mean[val] }else{ next } } for (val in seq(1, dim(imput_glucose)[1])) { if(dim(admission_lab[(admission_lab$rID == imput_egfr$rID[val]) & (is.na(admission_lab$EGFR)),])[1]!=0){ admission_lab$EGFR[which((admission_lab$rID == imput_egfr$rID[val]) & (is.na(admission_lab$EGFR)))] <- imput_egfr$Mean[val] }else{ next } } for (val in seq(1, dim(imput_glucose)[1])) { if(dim(admission_lab[(admission_lab$rID == imput_k$rID[val]) & (is.na(admission_lab$K)),])[1]!=0){ admission_lab$K[which((admission_lab$rID == imput_k$rID[val]) & (is.na(admission_lab$K)))] <- imput_k$Mean[val] }else{ next } } for (val in seq(1, dim(imput_glucose)[1])) { if(dim(admission_lab[(admission_lab$rID == imput_na$rID[val]) & (is.na(admission_lab$N_A)),])[1]!=0){ admission_lab$N_A[which((admission_lab$rID == imput_na$rID[val]) & (is.na(admission_lab$N_A)))] <- imput_na$Mean[val] }else{ next } } for (val in seq(1, dim(imput_glucose)[1])) { if(dim(admission_lab[(admission_lab$rID == imput_glucose$rID[val]) & (is.na(admission_lab$GLUCOSE)),])[1]!=0){ admission_lab$GLUCOSE[which((admission_lab$rID == imput_glucose$rID[val]) & (is.na(admission_lab$GLUCOSE)))] <- imput_glucose$Mean[val] }else{ next } } ``` ```{r} imputed.labs <- admission_lab summary(imputed.labs) ``` *Generate an original admission_lab* ```{r} admission_lab <- select(admission_30NA, -ends_with("_DAYS")) %>% select(rID, DAYS_READMISSION, WBC:GLUCOSE) names(admission_lab)[names(admission_lab) == "NA"] <- "N_A" admission_lab$DAYS_READMISSION[which(is.na(admission_lab$DAYS_READMISSION))] <- 0 admission_lab <- remove_outliers(admission_lab) ``` # Remove patients with missing values Based on the imputed admission labs data: ```{r} na.rid.1 <- dplyr::union(imputed.labs[which(is.na(imputed.labs$WBC)),]$rID, imputed.labs[which(is.na(imputed.labs$HGB)),]$rID) na.rid.2 <- dplyr::union(imputed.labs[which(is.na(imputed.labs$CR)),]$rID, na.rid.1) na.rid.3 <- dplyr::union(imputed.labs[which(is.na(imputed.labs$EGFR)),]$rID, imputed.labs[which(is.na(imputed.labs$K)),]$rID) na.rid.4 <- dplyr::union(imputed.labs[which(is.na(imputed.labs$N_A)),]$rID, imputed.labs[which(is.na(imputed.labs$GLUCOSE)),]$rID) na.rid.1 <- dplyr::union(na.rid.3, na.rid.4) na.rid <- dplyr::union(na.rid.1, na.rid.2) complete.imputed.labs <- imputed.labs[-which(imputed.labs$rID %in% na.rid),] ``` Based on the non-imputed admission labs data: ```{r} na.rid.1 <- dplyr::union(admission_lab[which(is.na(admission_lab$WBC)),]$rID, admission_lab[which(is.na(admission_lab$HGB)),]$rID) na.rid.2 <- dplyr::union(admission_lab[which(is.na(admission_lab$CR)),]$rID, na.rid.1) na.rid.3 <- dplyr::union(admission_lab[which(is.na(admission_lab$EGFR)),]$rID, admission_lab[which(is.na(admission_lab$K)),]$rID) na.rid.4 <- dplyr::union(admission_lab[which(is.na(admission_lab$N_A)),]$rID, admission_lab[which(is.na(admission_lab$GLUCOSE)),]$rID) na.rid.1 <- dplyr::union(na.rid.3, na.rid.4) na.rid <- dplyr::union(na.rid.1, na.rid.2) complete.labs <- admission_lab[-which(admission_lab$rID %in% na.rid),] ``` `complete.labs` contains `dim(complete.labs)[1]` admission records of `length(unique(complete.labs$rID))` patients. `complete.imputed.labs` contains `dim(complete.imputed.labs)[1]` admission records of `length(unique(complete.imputed.labs$rID))` patients. ```{r} panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...) { usr <- par("usr"); on.exit(par(usr)) par(usr = c(0, 1, 0, 1)) r <- abs(cor(x, y)) txt <- format(c(r, 0.123456789), digits = digits)[1] txt <- paste0(prefix, txt) if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt) text(0.5, 0.5, txt, cex = cex.cor * r) } pairs(~WBC + HGB + CR + EGFR + K + N_A + GLUCOSE, data = complete.labs, lower.panel = panel.cor) ``` # consider only patients with >=3 readmissions ```{r} readmission_counts <- complete.labs %>% group_by(rID) %>% tally() subset_rID <- readmission_counts[which(readmission_counts$n>2),]$rID complete.labs.3to15 <- complete.labs[which(complete.labs$rID %in% subset_rID),] ``` # save two dataset into excel file ```{r} library(openxlsx) write.xlsx(complete.labs.3to15, '~/Desktop/datasets/processed/admission_labs_3to15.xlsx', sheetName = "No_imputation_3to15", col.names = TRUE, row.names = FALSE) write.xlsx(complete.labs, '~/Desktop/datasets/processed/imputed_admission_labs.xlsx', sheetName = "Mean_imputations", col.names = TRUE, row.names = FALSE) ``` # Reshape the dataset for GBTM in STATA ```{r} library(data.table) ``` ```{r} patients_id <- unique(complete.labs.3to15$rID) generate_col_names <- function(measure_name, patients_id){ col_names <- c() for (val in patients_id){ col_names <- append(col_names, paste(measure_name, val, sep="_")) } return(col_names) } measurement_df <- function(orginial_df, new_df, measure_name){ col.names <- generate_col_names(measure_name, patients_id) names(new_df) <- col.names for (val in seq(1, length(unique(complete.labs.3to15$rID)))){ temp_c <- orginial_df[[measure_name]][which(orginial_df$rID == patients_id[val])] new_df[[col.names[val]]] <- c(temp_c, rep(NA, nrow(new_df)-length(temp_c))) } return(new_df) } ``` *generate column names after transpose* ```{r} change_col_names <- function(measure_name){ col_names <- c() for (val in seq(1,15)){ col_names <- append(col_names, paste(measure_name, val, sep="_")) } return(col_names) } ``` ## WBC ```{r} # wbc_ob <- complete.labs.3to15 %>% select(rID, WBC) wbc.df <- data.frame(matrix(ncol = length(unique(complete.labs.3to15$rID)), nrow = 15)) wbc.df <- measurement_df(orginial_df = complete.labs.3to15, new_df = wbc.df, measure_name = 'WBC') wbc.df.t <- transpose(wbc.df) names(wbc.df.t) <- change_col_names('WBC') ``` ```{r} wbc.df.t.3to8 <- wbc.df.t temp_list <- c("WBC_10","WBC_11","WBC_12","WBC_13","WBC_14","WBC_15") for (val in temp_list){ wbc.df.t.3to8[[val]] <- NULL } ``` ## K ```{r} k.df <- data.frame(matrix(ncol = length(unique(complete.labs.3to15$rID)), nrow = 15)) k.df <- measurement_df(orginial_df = complete.labs.3to15, new_df = k.df, measure_name = 'K') k.df.t <- transpose(k.df) names(k.df.t) <- change_col_names('K') ``` *DAYS_READMISSION* ```{r} days.df <- data.frame(matrix(ncol = length(unique(complete.labs.3to15$rID)), nrow = 15)) days.df <- measurement_df(orginial_df = complete.labs.3to15, new_df = days.df, measure_name = 'DAYS_READMISSION') days.df.t <- transpose(days.df) names(days.df.t) <- change_col_names('days') ``` *# of times of readmission* ```{r} time.df <- data.frame(matrix(ncol = length(unique(complete.labs.3to15$rID)), nrow = 15)) names(time.df) <- generate_col_names('T', patients_id) for (val in seq(1, length(unique(complete.labs.3to15$rID)))){ time.df[[names(time.df)[val]]] <- seq(1,15) } time.df.t <- transpose(time.df) names(time.df.t) <- change_col_names('T') ``` ```{r} time.df.t.3to8 <- time.df.t temp_list <- c("T_10","T_11","T_12","T_13","T_14","T_15") for (val in temp_list){ time.df.t.3to8[[val]] <- NULL } ``` ```{r} library(openxlsx) ``` *Combine data to save together as 1 dataframe* ```{r} combined.df.1 <- cbind(wbc.df.t, time.df.t) write.xlsx(combined.df.1, '~/Desktop/datasets/processed/combined times for gbtm.xlsx', col.names = TRUE, row.names = FALSE) ``` ```{r} combined.df.2 <- cbind(k.df.t, time.df.t) write.xlsx(combined.df.2, '~/Desktop/datasets/processed/combined times for gbtm.xlsx', col.names = TRUE, row.names = FALSE) ``` ```{r} write.xlsx(wbc.df, '~/Desktop/datasets/processed/wbc for gbtm.xlsx', col.names = TRUE, row.names = FALSE) write.xlsx(days.df, '~/Desktop/datasets/processed/readmission_days for gbtm.xlsx',col.names = TRUE, row.names = FALSE) ``` # Transform data to censored normal ```{r} ggplot(data = complete.labs.3to15, aes(K)) + geom_histogram() ``` ```{r} summary(complete.labs.3to15$K) complete.labs.3to15$K <- log10(complete.labs.3to15$K) temp.labs.3to15 <- complete.labs.3to15 ``` ```{r} complete.labs.3to15$K[which(temp.labs.3to15$K < 0.5)] <- 0 complete.labs.3to15$K[which(temp.labs.3to15$K >= 0.5 & temp.labs.3to15$K <= 0.55)] <- 1 complete.labs.3to15$K[which(temp.labs.3to15$K >= 0.55 & temp.labs.3to15$K <= 0.6)] <- 2 complete.labs.3to15$K[which(temp.labs.3to15$K >= 0.6 & temp.labs.3to15$K <= 0.65)] <- 3 complete.labs.3to15$K[which(temp.labs.3to15$K >= 0.65 & temp.labs.3to15$K <= 0.7)] <- 4 complete.labs.3to15$K[which(temp.labs.3to15$K > 0.7)] <- 5 ``` <file_sep>--- title: "HMM in R" output: html_notebook --- This is an [R Markdown](http://rmarkdown.rstudio.com) Notebook. When you execute code within the notebook, the results appear beneath the code. Try executing this chunk by clicking the *Run* button within the chunk or by placing your cursor inside it and pressing *Cmd+Shift+Enter*. Add a new chunk by clicking the *Insert Chunk* button on the toolbar or by pressing *Cmd+Option+I*. When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the *Preview* button or press *Cmd+Shift+K* to preview the HTML file). The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike *Knit*, *Preview* does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed. ```{r} library("readxl") library('dplyr') ``` ## Import Datasets ```{r} # import admission dataset baseline_noNA_attris <- read_excel("~/Desktop/datasets/processed/Data_noNA.xlsx", sheet = 'baseline') admission_noNA_attris <- read_excel("~/Desktop/datasets/processed/Data_noNA.xlsx", sheet = 'admission') baseline_30NA <- read_excel("~/Desktop/datasets/processed/Filtered Attributes Baseline.xlsx", sheet = 'updated_folup_NA30_baseline') admission_30NA <- read_excel("~/Desktop/datasets/processed/Filtered Attributes Admission.xlsx", sheet = 'NA2030_filtered_admission') ``` ```{r} static <- read_excel("~/Desktop/datasets/processed/Static Characteristics.xlsx") static['...1'] <- NULL ``` We want to extract a subset of patients with no missing values as for experimenting with models. ```{r} # drop columns ends with _DAYS admission_2 <- select(admission_30NA, -ends_with("_DAYS") ) baseline_2 <- select(baseline_30NA, -ends_with("_DAYS") ) baseline_complete <- baseline_2[complete.cases(baseline_2), ] admission_complete <- admission_2[complete.cases(admission_2), ] data.frame(table(admission_2$rID)) data.frame(table(admission_complete$rID)) ``` ```{r} data.frame(table(admission_complete$rID)) patients_complete <- intersect(basesline_complete$rID, unique(admission_complete$rID)) baseline_complete <- baseline_complete %>% filter(rID %in% patients_complete) admission_complete <- admission_2 %>% filter(rID %in% patients_complete) ``` ```{r} summary(admission_complete) data.frame(table(mydf$MONTH.YEAR)) ``` ## depmixS4 toy model ```{r} library('depmixS4') ``` ```{r} data("speed") ``` ```{r} admission_noNA_attris %>% filter(rID == 16) ``` ```{r} set.seed(1) temp_df <- admission_30NA %>% filter(rID == 16) %>% select(LOS_DAYS, I_STROKEFLAG, AGE_ADMISSION, CARDIACFLAG, HFFLAG, K, "NA", HCT, readmission_days_btw, AFIBFLAG) mod1 <- depmix(list(LOS_DAYS ~ 1, K~ 1, CARDIACFLAG ~ 1, HFFLAG ~ 1, AFIBFLAG ~ 1), data = temp_df, nstates = 2, family = list(gaussian(), gaussian(), binomial(), binomial(), binomial()), instart = runif(2)) fm1 <- fit(mod1, verbose = FALSE, emc=em.control(rand=FALSE)) mod2 <- depmix(list(LOS_DAYS ~ 1, K~ 1, CARDIACFLAG ~ 1, HFFLAG ~ 1, AFIBFLAG ~ 1), data = temp_df, nstates = 3, family = list(gaussian(), gaussian(), binomial(), binomial(), binomial()), instart = runif()) fm2 <- fit(mod2, verbose = FALSE, emc=em.control((maxit=1000))) ``` ```{r} plot(1:2,c(BIC(fm1),BIC(fm2)),ty="b") ``` <file_sep>--- title: "R Notebook" output: html_notebook --- ```{r} library(tidyverse) library(VennDiagram) library(RColorBrewer) ``` # EGFR single traj ```{r} egfr.no.tcov <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/traj_results/egfr_single.xlsx") ``` In EGFR single trajectory, Group 1 is the highest risk group. In Multi-traj, Group 2 is the highest risk group. We would like to examine how many patients are in the highest risk group for both of them. ```{r} multi.risky <- multitraj.no.tcov[which(multitraj.no.tcov$`_traj_Group`==2),] egfr.risky <- egfr.no.tcov[which(egfr.no.tcov$`_traj_Group`==1),] risky1 <- multi.risky[which(multi.risky$patients_id %in% egfr.risky$patients_id),] dim(risky1)[1]/dim(multi.risky)[1] ``` There are 259 patients in the highest risk group in multi-traj who are also in the highest risk group for single egfr traj. ```{r} egfr.single.outcomes<- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/egfr_single_withoutcome.xlsx") ``` ```{r} egfr.single.outcomes$CTB_predicted <- 0 egfr.single.outcomes[which(egfr.single.outcomes$`_traj_Outcome`>0.5),]$CTB_predicted <- 1 summary(egfr.single.outcomes$CTB_predicted) dim(egfr.single.outcomes[which(egfr.single.outcomes$GC == egfr.single.outcomes$CTB_predicted),])[1]/1653 ``` # Multi-traj model result ```{r} cohort.ids <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/datasets/subset1653.xlsx") # multitraj.no.tcov <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/traj_results/multi_no_tcov.xlsx") multi.full <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/traj_results/multi_full.xlsx") ``` ## VAD `group.1` is the dataframe that contains all GBTM results of Group 1. `vad.ids` is the patient ids of patient who got VAD intervention. `no.vad.ids` is the patient ids of patient who didn't get VAD intervention. ```{r} group.1 <- multi.full[which(multi.full$`_traj_Group` == 5),] # group.1 <- multi.full ids <- group.1$patients_id group.1.vad <- group.1 %>% select(patients_id, starts_with("POST_VAD")) group.1.vad$POST_VAD <- group.1.vad %>% select(starts_with("POST_VAD")) %>% rowSums(na.rm=TRUE) group.1.vad[which(group.1.vad$POST_VAD > 0),]$POST_VAD <- 1 ``` ```{r} vad.ids <- group.1.vad[which(group.1.vad$POST_VAD > 0),]$patients_id no.vad.ids <- group.1.vad[which(group.1.vad$POST_VAD == 0),]$patients_id length(vad.ids) length(no.vad.ids) no.vad.ave <- group.1[which(group.1$patients_id %in% no.vad.ids),] %>% select(starts_with('EGFR_')) %>% colMeans(na.rm=TRUE) %>% as.data.frame() no.vad.ave$type <- "no vad" no.vad.ave$adm <- 1:10 # vad.df <- no.vad.ave # colnames(vad.df) <- vad.ave <- group.1[which(group.1$patients_id %in% vad.ids),] %>% select(starts_with('EGFR_')) %>% colMeans(na.rm=TRUE) %>% as.data.frame() vad.ave$type <- "with vad" vad.ave$adm <- 1:10 vad.total.ave <- group.1[which((group.1$patients_id %in% vad.ids) | (group.1$patients_id %in% no.vad.ids)),] %>% select(starts_with('EGFR_')) %>% colMeans(na.rm=TRUE) %>% as.data.frame() vad.total.ave$type <- "total" vad.total.ave$adm <- 1:10 ``` ```{r} df.plot <- rbind(no.vad.ave, vad.ave, vad.total.ave) colnames(df.plot) <- c("val", "type", "adm") ggplot(df.plot, aes(x=adm, y=val, color=type)) + geom_line() + scale_color_discrete(name = "Groups") + scale_x_continuous(breaks=1:10) + ylab("Average EGFR Level") ggsave("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 20/tcov_g5_vad_egfr_plot.png", width = 7, height = 4) ``` ## HTX ```{r} group.1 <- multi.full[which(multi.full$`_traj_Group` == 5),] ids <- group.1$patients_id group.1.htx <- group.1 %>% select(patients_id, starts_with("POST_HTX")) group.1.htx$POST_HTX <- group.1.htx %>% select(starts_with("POST_HTX")) %>% rowSums(na.rm=TRUE) group.1.htx[which(group.1.htx$POST_HTX > 0),]$POST_HTX <- 1 ``` ```{r} htx.ids <- group.1.htx[which(group.1.htx$POST_HTX > 0),]$patients_id no.htx.ids <- group.1.htx[which(group.1.htx$POST_HTX == 0),]$patients_id length(htx.ids) length(no.htx.ids) no.htx.ave <- group.1[which(group.1$patients_id %in% no.htx.ids),] %>% select(starts_with('EGFR_')) %>% colMeans(na.rm=TRUE) %>% as.data.frame() no.htx.ave$type <- "no htx" no.htx.ave$adm <- 1:10 # htx.df <- no.htx.ave # colnames(htx.df) <- htx.ave <- group.1[which(group.1$patients_id %in% htx.ids),] %>% select(starts_with('EGFR_')) %>% colMeans(na.rm=TRUE) %>% as.data.frame() htx.ave$type <- "with htx" htx.ave$adm <- 1:10 htx.total.ave <- group.1[which((group.1$patients_id %in% htx.ids) | (group.1$patients_id %in% no.htx.ids)),] %>% select(starts_with('EGFR_')) %>% colMeans(na.rm=TRUE) %>% as.data.frame() htx.total.ave$type <- "total" htx.total.ave$adm <- 1:10 df.plot <- rbind(no.htx.ave, htx.ave, htx.total.ave) colnames(df.plot) <- c("val", "type", "adm") ggplot(df.plot, aes(x=adm, y=val, color=type)) + geom_line() + scale_color_discrete(name = "Groups") + scale_x_continuous(breaks=1:10) + ylab("Average EGFR Level") # ggsave("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 20/tcov_g5_htx_egfr_plot.png", width = 7, height = 4) ``` ## Either Interventions ```{r} group.1 <- multi.full[which(multi.full$`_traj_Group` == 5),] ids <- group.1$patients_id group.1.inter <- group.1 %>% select(patients_id, starts_with("POST_HTX"), starts_with("POST_VAD")) group.1.inter$POST_HTX <- group.1.inter %>% select(starts_with("POST_HTX")) %>% rowSums(na.rm=TRUE) group.1.inter$POST_VAD <- group.1.inter %>% select(starts_with("POST_VAD")) %>% rowSums(na.rm=TRUE) group.1.inter$POST_INTER <- 0 group.1.inter[which(group.1.inter$POST_HTX > 0),]$POST_INTER <- 1 group.1.inter[which(group.1.inter$POST_VAD > 0),]$POST_INTER <- 1 ``` ```{r} inter.ids <- group.1.inter[which((group.1.inter$POST_HTX > 0)|(group.1.inter$POST_VAD > 0)),]$patients_id no.inter.ids <- group.1.inter[which((group.1.inter$POST_HTX == 0)&(group.1.inter$POST_VAD == 0)),]$patients_id length(inter.ids) length(no.inter.ids) no.inter.ave <- group.1[which(group.1$patients_id %in% no.inter.ids),] %>% select(starts_with('EGFR_')) %>% colMeans(na.rm=TRUE) %>% as.data.frame() no.inter.ave$type <- "no intervention" no.inter.ave$adm <- 1:10 # htx.df <- no.htx.ave # colnames(htx.df) <- inter.ave <- group.1[which(group.1$patients_id %in% inter.ids),] %>% select(starts_with('EGFR_')) %>% colMeans(na.rm=TRUE) %>% as.data.frame() inter.ave$type <- "with intervention" inter.ave$adm <- 1:10 inter.total.ave <- group.1[which((group.1$patients_id %in% inter.ids) | (group.1$patients_id %in% no.inter.ids)),] %>% select(starts_with('EGFR_')) %>% colMeans(na.rm=TRUE) %>% as.data.frame() inter.total.ave$type <- "total" inter.total.ave$adm <- 1:10 ``` ```{r} df.plot <- rbind(no.inter.ave, inter.ave, inter.total.ave) colnames(df.plot) <- c("val", "type", "adm") ggplot(df.plot, aes(x=adm, y=val, color=type)) + geom_line() + scale_color_discrete(name = "Groups") + scale_x_continuous(breaks=1:10) + ylab("Average EGFR Level") ggsave("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 20/tcov_g5_inter_egfr_plot.png", width = 7, height = 4) ``` # Comparisons between EGFR single and multi-traj analysis ```{r} multitraj.no.tcov <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/traj_results/multi_no_tcov.xlsx") egfr.no.tcov <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/traj_results/egfr_single.xlsx") ``` ```{r} high.1.egfr <- egfr.no.tcov[which(egfr.no.tcov$`_traj_Group`==1),]$patients_id high.2.egfr <- egfr.no.tcov[which(egfr.no.tcov$`_traj_Group`==2),]$patients_id high.3.egfr <- egfr.no.tcov[which(egfr.no.tcov$`_traj_Group`==5),]$patients_id high.4.egfr <- egfr.no.tcov[which(egfr.no.tcov$`_traj_Group`==3),]$patients_id high.5.egfr <- egfr.no.tcov[which(egfr.no.tcov$`_traj_Group`==4),]$patients_id high.1.multi <- multitraj.no.tcov[which(multitraj.no.tcov$`_traj_Group`==2),]$patients_id high.2.multi <- multitraj.no.tcov[which(multitraj.no.tcov$`_traj_Group`==1),]$patients_id high.3.multi <- multitraj.no.tcov[which(multitraj.no.tcov$`_traj_Group`==5),]$patients_id high.4.multi <- multitraj.no.tcov[which(multitraj.no.tcov$`_traj_Group`==3),]$patients_id high.5.multi <- multitraj.no.tcov[which(multitraj.no.tcov$`_traj_Group`==4),]$patients_id ``` ```{r} myCol <- brewer.pal(2, "Pastel2") # for highest risk group graph1 <- venn.diagram( list(high.5.egfr, high.5.multi), category.names = c("EGFR single" , "Multi-trajectory"), # filename = 'high5_venn_diagramm.png', filename = '/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 20/high5_venn_diagramm.png', output = FALSE, # Output features imagetype="png", height = 480, width = 580, resolution = 300, # compression = "lzw", # Circles lwd = 2, lty = 'blank', fill = myCol[1:2], cex = .6, cat.cex = 0.6, cat.just = list(c(0.8, 0) , c(0.2, 0)) ) graph1 ``` <file_sep># HF_project_code This repository contains the code for HF research study code. ---------------------------------------------------------------------------------------------------- Advanced_Therapy_Candidates_Cohort.ipynb: Filtered the whole dataset to data of patients who are potential candidates for advanced therapy (VAD). Cohort_Mortality_Admissions_baseline.ipynb: Examine the mortality rate and readmission rate of the cohort. Especially 30-day readmission rate and all-time mortality rate vs. number of admission the patients had. Still having trouble with the attribute "FOLLOWUP_DAYS" in order to compute 30-day/60-day/1-year mortality. baseline_attributes_NA_filter.ipynb: Filtered attributes with large portion of missing valuesin baseline dataset. Decided to use 20% and 30% NA tolerance. Baseline dataset with 20% and 30% NA tolerance were saved separately. admission_attributes_NA_filter.ipynb: Filtered attributes with large portion of missing valuesin admission dataset. There was no difference between 20% and 30% NA tolerance. Admission dataset with 20/30% NA tolerance were saved. Baseline_risk_stratification.ipynb: Attemped to predict 30-day readmission and all-time mortality using only static features. Poor performance. <file_sep>########## F-CAP version 1.1.0 ########### #### (c) <NAME>, February 2015 #### ############# USER SETTINGS ############## sas_path <- '"C:/Program Files/SASHome2/SASFoundation/9.4/sas.exe"' # path to SAS (mind the quotes), e.g. '"C:/SASHome/SASFoundation/9.3/sas.exe"' excel_template <- "C:/mydocuments/Traj/F-CAP/fcap_template.xlsx" # path to F-CAP template, e.g. "C:/myfiles/fcap_template.xlsx" input_directory <- "C:/mydocuments/Traj/F-CAP/" # path to data directory, e.g. "C:/myfiles/study-A/" input_file <- "kevin_qol_centered.sas7bdat" output_directory <- "C:/mydocuments/Traj/F-CAP/output/" # folder to which results are written, e.g. "C:/myfiles/output/" # proc traj variables, also check: http://www.andrew.cmu.edu/user/bjones/ # additional parameters can be included in the model variable as follows: # model <- "CNORM; MIN 3; MAX 42" id <- "id" # variable name of the identifier, e.g. participant number var <- "o1-o3" # dependent outcome variables indep <- "t1-t3" # independent variables model <- "CNORM" # model: "CNORM", "ZIP", or "LOGIT" groups_min <- 3 # minimum number of groups (k) to test in a model, absolute minimum: 1 groups_max <- 10 # maximum number of groups (k) to test in a model, absolute maximum: 20 poly_order <- 2 # polynomial order: minimum 0, maximum 5 mode <- "ANALYSIS" # "FULL": Automatically create the F-CAP without need for user interaction # "SAS": Run the proc traj procedures in SAS, stores results in the output-directory # "ANALYSIS": Uses SAS results in the output-directory to create the F-CAP open_file <- TRUE # automatically open the file with the resulting F-CAP: TRUE or FALSE # Note: in case Java is not available, the F-CAP results are written to a .txt-file # These can be manually copied to the the Excel-template to display the F-CAP graphs ########## END OF USER SETTINGS ########## # analyse AIC, BIC and L analyse_bic <- function(){ # create dataframe for storage bic_df <- data.frame("AIC"=numeric(length(groups)), "BIC"=numeric(length(groups)), "L"=numeric(length(groups)), "Convergence"=numeric(length(groups)), row.names=groups) for (group in groups){ # read data bic_file <- paste0(output_directory, "fcap_bic_", group, ".csv") df <- read.csv(bic_file) # get AIC, BIC and L aic_col <- grep("_AIC_", colnames(df), fixed=TRUE)[1] aic <- df[1, aic_col] bic_col <- grep("_BIC1_", colnames(df), fixed=TRUE)[1] bic <- df[1, bic_col] l_col <- grep("_LOGLIK_", colnames(df), fixed=TRUE)[1] l <- df[1, l_col] conv_col <- grep("_CONVERGE_", colnames(df), fixed=TRUE)[1] conv <- df[1, conv_col] # store data bic_df[toString(group),] <- c(aic, bic, l, conv) } bic_df } # analyse APPA (avePP), OCC, mismatch, SD and smallest group analyse_prob <- function(){ # create dataframe for storage prob_df <- data.frame("avePP"=numeric(length(groups)), "avePPm"=numeric(length(groups)), "OCC"=numeric(length(groups)), "OCCm"=numeric(length(groups)), "mis"=numeric(length(groups)), "mism"=numeric(length(groups)), "SD"=numeric(length(groups)), "SDm"=numeric(length(groups)), "smallAss"=numeric(length(groups)), "smallEst"=numeric(length(groups)), row.names=groups) for (group in groups){ # read data prob_file <- paste0(output_directory, "fcap_prob_", group, ".csv") df <- read.csv(prob_file) # find posterior probabilities for each group group_probs <- vector("list", group) for (row in 1:nrow(df)){ g <- df[row, "GROUP"] group_probs[[g]] <- c(group_probs[[g]], df[row, paste0("GRP", g, "PRB")]) } # calculate APPA group_prob_means <- vector() for (i in 1:group){ if (!is.null(group_probs[[i]])){ group_prob_means <- c(group_prob_means, mean(group_probs[[i]], na.rm=TRUE)) } else{ # emtpy group group_prob_means <- c(group_prob_means, NA) } } prob_df[toString(group), "avePP"] <- mean(group_prob_means, na.rm=TRUE) prob_df[toString(group), "avePPm"] <- min(group_prob_means, na.rm=TRUE) # calculate mismatch and smallest group prob_cols <- grep("GRP", colnames(df), fixed=TRUE) if (group == 1){ estimated <- mean(df[,prob_cols]) } else{ estimated <- colMeans(df[, prob_cols], na.rm=TRUE) } assigned <- vector() mismatch <- vector() for (i in 1:group){ if (!is.null(group_probs[[i]]) > 0){ assigned <- c(assigned, length(group_probs[[i]]) / nrow(df)) } else{ assigned <- c(assigned, 0) } mismatch <- c(mismatch, abs(estimated[i] - assigned[i])) } prob_df[toString(group), "mis"] <- mean(mismatch, na.rm=TRUE) prob_df[toString(group), "mism"] <- max(mismatch, na.rm=TRUE) prob_df[toString(group), "smallAss"] <- max(1e-4, min(assigned, na.rm=TRUE)) prob_df[toString(group), "smallEst"] <- max(1e-4, min(estimated, na.rm=TRUE)) # calculate OCC if (group == 1){ prob_df[toString(group), "OCC"] <- 999 prob_df[toString(group), "OCCm"] <- 999 } else{ occs <- vector() for (i in 1:group){ numer <- group_prob_means[i] / (1 - group_prob_means[i]) denom <- estimated[i] occs <- c(occs, numer/denom) } occ <- mean(occs, na.rm=TRUE) if (occ > 999){ occ <- 999 } occm <- min(occs, na.rm=TRUE) if (occm > 999){ occm <- 999 } prob_df[toString(group), "OCC"] <- occ prob_df[toString(group), "OCCm"] <- occm } # calculate SD sd <- vector() for (i in 1:group){ sd <- c(sd, sd(group_probs[[i]])) } prob_df[toString(group), "SD"] <- mean(sd, na.rm=TRUE) prob_df[toString(group), "SDm"] <- max(sd, na.rm=TRUE) } prob_df } # write output create_excel <- function(bic_df, prob_df){ # create copy of template file file.copy(excel_template, output_file) # read excel file workbook <- loadWorkbook(output_file) sheet <- getSheets(workbook)[[2]] # insert data cells <- CellBlock(sheet, groups_min + 2, 2, length(groups), 13) for(col in 1:10){ CB.setColData(cells, prob_df[,col], col) } for(col in 1:3){ CB.setColData(cells, bic_df[,col], col+10) } # save excel file workbook$setForceFormulaRecalculation(TRUE) saveWorkbook(workbook, output_file) } # create instructions for SAS create_sas <- function(){ # automatically determine MIN and MAX for CNORM models, if not defined if (grepl("CNORM", model, ignore.case=TRUE)){ min <- TRUE max <- TRUE if (!grepl("MIN", model, ignore.case=TRUE)){ min <- FALSE } if (!grepl("MAX", model, ignore.case=TRUE)){ max <- FALSE } if (!(min && max)){ # find column names vars <- strsplit(var, " ", fixed=TRUE) cols <- vector() for (v in vars[[1]]){ if (v == ""){ next } if (grepl("-", v)){ sub <- strsplit(v, "-", fixed=TRUE) sub_low <- as.numeric(gsub("\\D", "", sub[[1]][1])) sub_high <- as.numeric(gsub("\\D", "", sub[[1]][2])) sub_text <- gsub("\\d", "", sub[[1]][1]) for (i in sub_low:sub_high){ cols <- c(cols, paste0(sub_text, i)) } } else{ cols <- c(cols, v) } } # find minimum and/or maximum df <- read.sas7bdat(paste0(input_directory, input_file)) col_match <- vector(length=length(colnames(df))) for (col in cols){ col_match <- grepl(col, colnames(df), ignore.case=TRUE) | col_match } if (!min){ min <- as.integer(min(df[,col_match], na.rm=TRUE)) if(min(df[,col_match], na.rm=TRUE) < min){ min <- min - 1 } model <- paste0(model, "; MIN ", min) cat("Automatically determined MIN:", min, "\n") } if (!max){ max <- as.integer(max(df[,col_match], na.rm=TRUE)) if(max(df[,col_match], na.rm=TRUE) > max){ max <- max + 1 } model <- paste0(model, "; MAX ", max) cat("Automatically determined MAX:", max, "\n") } } } # instructions fcap_sas <- "options nonotes nosource nosource2 errors=0;\n" fcap_sas <- paste0(fcap_sas, "libname fcap '", input_directory, "';\n\n") for (group in groups){ # proc traj procedure fcap_sas <- paste0(fcap_sas, "PROC TRAJ DATA=fcap.", input_filename, " OUTPLOT=OP OUTSTAT=OS OUT=OF OUTEST=OE;\n") fcap_sas <- paste0(fcap_sas, "ID ", id, "; VAR ", var, "; INDEP ", indep, ";\n") order <- gsub(",", "", toString(rep.int(poly_order, group))) fcap_sas <- paste0(fcap_sas, "MODEL ", model, "; NGROUPS ", group, "; ORDER ", order, ";\n") fcap_sas <- paste0(fcap_sas, "RUN;\n") # export probabilities table fcap_sas <- paste0(fcap_sas, "PROC EXPORT DATA=Work.Oe OUTFILE='", output_directory, "fcap_bic_", group, ".csv' DBMS=CSV;\n") fcap_sas <- paste0(fcap_sas, "PROC EXPORT DATA=Work.Of OUTFILE='", output_directory, "fcap_prob_", group, ".csv' DBMS=CSV;\n") fcap_sas <- paste0(fcap_sas, "RUN;\n\n") } # save to SAS programme file output_file <- paste0(output_directory, "fcap.sas") write(fcap_sas, file=output_file) } # write output create_txt <- function(bic_df, prob_df){ # create copy of template file file.copy(excel_template, output_file) # merge dataframes total <- merge(prob_df, bic_df, by=0, all=TRUE, sort=FALSE) total <- total[, 2:ncol(total)] # write dataframe to txt file write.table(total, output_txt, sep="\t", row.names=FALSE, col.names=FALSE) } # controller hub main <- function(mode='FULL'){ # check what needs to be done do_sas <- FALSE do_analysis <- FALSE step <- 0 if (mode == 'FULL'){ total <- "4" do_sas <- TRUE do_analysis <- TRUE } else if (mode == 'SAS'){ total <- "2" do_sas <- TRUE } else{ #if (mode == 'ANALYSIS') total <- "2" do_analysis <- TRUE } pre_process(do_sas, do_analysis) if (do_sas){ step <- step + 1 cat(paste0("[", step, "/", total, "] Creating instructions for SAS\n")) create_sas() step <- step + 1 cat(paste0("[", step, "/", total, "] Running proc traj in SAS (this can take long)\n")) system(paste0(sas_path, " -nosplash -nolog -noprint -nostepchkpt -nosyntaxcheck -noverbose -SYSIN ", output_directory, "fcap.sas")) } if (do_analysis){ step <- step + 1 cat(paste0("[", step, "/", total, "] Analysing proc traj outcomes\n")) bic_df <- analyse_bic() prob_df <- analyse_prob() step <- step + 1 cat(paste0("[", step, "/", total, "] Writing output file\n")) if (xlsx_output){ create_excel(bic_df, prob_df) if (open_file){ shell.exec(output_file) } } else{ create_txt(bic_df, prob_df) if (open_file){ shell.exec(output_file) shell.exec(output_txt) } } } cat("Finished") } # convert input data pre_process <- function(do_sas, do_analysis){ library(tools) if (do_sas){ if (!"sas7bdat" %in% rownames(installed.packages())){ install.packages("sas7bdat") } suppressMessages(suppressWarnings(library(sas7bdat))) if (substr(model, nchar(model), nchar(model)) == ";"){ assign("model", substr(model, 1, nchar(model) - 1), .GlobalEnv) } } time <- strftime(Sys.time(), format="%Y_%m_%d_%H_%M_%S") if (do_analysis){ if (!"xlsx" %in% rownames(installed.packages())){ install.packages("xlsx") } tryCatch({ suppressMessages(suppressWarnings(library(xlsx))) assign("xlsx_output", TRUE, .GlobalEnv) }, error=function(condition){ # (correct version of) java is probably not available assign("xlsx_output", FALSE, .GlobalEnv) assign("output_txt", paste0(output_directory, "FCAP_", time, ".txt"), .GlobalEnv) }) } assign("input_filename", file_path_sans_ext(input_file), .GlobalEnv) assign("groups", max(1, groups_min) : min(20, groups_max), .GlobalEnv) assign("poly_order", min(4, max(0, poly_order)), .GlobalEnv) assign("output_file", paste0(output_directory, "FCAP_", time, ".xlsx"), .GlobalEnv) } main(mode) <file_sep>--- title: "R Notebook" output: html_notebook --- This is an [R Markdown](http://rmarkdown.rstudio.com) Notebook. When you execute code within the notebook, the results appear beneath the code. Try executing this chunk by clicking the *Run* button within the chunk or by placing your cursor inside it and pressing *Cmd+Shift+Enter*. ```{r} library(depmixS4) library(cluster) library(factoextra) library(tidyverse) ``` ```{r} lab.temp <- labs %>% select(starts_with('PLATELETS_')) lab.vector <- as.vector(t(lab.temp)) # labs.df <- data.frame(EGFR = lab.vector) labs.df <- cbind(labs.df, PLATELETS=lab.vector) ``` # Impute labs for forward-backward computation ```{r} egfr.labs <- labs %>% select(starts_with('EGFR_')) imp.egfr <- longitudinalData::imputation(as.matrix(egfr.labs), method='linearInterpol.locf') imp.egfr <- imp.egfr[complete.cases(imp.egfr), ] ``` ```{r} lab.vector <- as.vector(t(imp.egfr)) egfr.df <- data.frame(EGFR = lab.vector) ``` ```{r} hmm.mod <- depmix(EGFR~1, data=egfr.df, nstates=3, family=gaussian(), ntimes=rep(10, 1647)) hmm.egfr <- fit(hmm.mod) dens.egfr <- depmixS4::forwardbackward(hmm.egfr) egfr.alpha <- as.data.frame(dens.egfr[["alpha"]]) ``` ```{r} # id <- c() # for (i in seq(1:1647)){ # id <- append(id, rep(i, 10)) # } # egfr.alpha <- cbind(egfr.alpha, id=id) alpha.values <- as.vector(t(egfr.alpha)) alpha.matrix <- matrix(alpha.values, nrow=1647, byrow = TRUE) ``` ```{r} # ProbMatrix <- rbind(1:10/sum(1:10), 20:29/sum(20:29), 30:39/sum(30:39), 30:39/sum(30:39)) distance.matrix <- philentropy::distance(alpha.matrix, method = "euclidean") pam.clust <- pam(distance.matrix, 5) View(pam.clust$medoids) View(pam.clust$clustering) cluster.results <- as.data.frame(pam.clust$clustering) colnames(cluster.results) <- c('group') table(cluster.results) fviz_cluster(pam.clust) ``` ```{r} hmm.df <- data.frame(id=labs.cld@idFewNA, group=cluster.results) write_xlsx(hmm.df,"/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 25/egfr_hmm_groups.xlsx") ``` ```{r} cluster.results[cluster.results==1] <- 'A' cluster.results[cluster.results==2] <- 'B' cluster.results[cluster.results==3] <- 'C' cluster.results[cluster.results==4] <- 'D' cluster.results[cluster.results==5] <- 'E' cluster.hmm <- as.factor(cluster.results$group) part.2 <- partition(cluster.hmm) plotTrajMeans(longDataFrom3d(labs.ld, variable="EGFR"), part.2, xlab='Time', ylab='EGFR', parTraj=parTRAJ(type="n"), ylim=c(0, 100)) ``` todo: - use 6 labs - use KL divergence for distance matrix instead of euclidean distance ```{r} lab.temp <- labs %>% select(starts_with('PLATELETS_')) lab.vector <- as.vector(t(lab.temp)) # labs.df <- data.frame(EGFR = lab.vector) labs.df <- cbind(labs.df, PLATELETS=lab.vector) ``` # Impute labs for forward-backward computation ```{r} six.labs <- labs %>% select(starts_with('EGFR_'), starts_with('N_A_'), starts_with('K_'), starts_with('HGB_'), starts_with('WBC_'), starts_with('PLATELETS_')) imp.labs <- longitudinalData::imputation(as.matrix(six.labs), method='linearInterpol.locf') imp.labs <- imp.labs[complete.cases(imp.labs), ] ``` ```{r} egfr.vector <- as.vector(t(imp.labs)) egfr.df <- data.frame(EGFR = lab.vector) ``` ```{r} hmm.mod <- depmix(EGFR~1, data=egfr.df, nstates=3, family=gaussian(), ntimes=rep(10, 1647)) hmm.egfr <- fit(hmm.mod) dens.egfr <- depmixS4::forwardbackward(hmm.egfr) egfr.alpha <- as.data.frame(dens.egfr[["alpha"]]) ``` ```{r} # id <- c() # for (i in seq(1:1647)){ # id <- append(id, rep(i, 10)) # } # egfr.alpha <- cbind(egfr.alpha, id=id) alpha.values <- as.vector(t(egfr.alpha)) alpha.matrix <- matrix(alpha.values, nrow=1647, byrow = TRUE) ``` ```{r} # ProbMatrix <- rbind(1:10/sum(1:10), 20:29/sum(20:29), 30:39/sum(30:39), 30:39/sum(30:39)) distance.matrix <- philentropy::distance(alpha.matrix, method = "Kullback-Leibler") pam.clust <- pam(distance.matrix, 5) View(pam.clust$medoids) View(pam.clust$clustering) cluster.results <- as.data.frame(pam.clust$clustering) colnames(cluster.results) <- c('group') table(cluster.results) fviz_cluster(pam.clust) ``` <file_sep>--- title: "Relaxed Selection of Cohort - GBTM Data Processing" output: html_notebook --- # library ```{r global_options, include=FALSE} knitr::opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE) library(tidyverse) library(knitr) library(data.table) #for transpose() function library(reshape2) library(openxlsx) # library(Hmisc) ``` # DATA import ```{r} admission_30NA <- readxl::read_excel("~/Desktop/HF_Research/datasets/processed/Filtered Attributes Admission v2.xlsx", sheet = 'Sheet 1') baseline.df <- readxl::read_excel('~/Desktop/HF_research/datasets/processed/Filtered Baseline imputed.xlsx', sheet = 'Sheet 1') # baseline.profile.df is combined with one-hot encoded categorical variables baseline.profile.df <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/datasets/processed/All Baseline Attributes combined.xlsx", sheet = 'Sheet 1') raw.baseline <- readxl::read_excel("/Users/jinchenxie/Desktop/datasets/processed/Filtered Attributes Baseline.xlsx") raw.admission <- readxl::read_excel("/Users/jinchenxie/Desktop/datasets/HF-Admissions.xlsx") vad.baseline <- readxl::read_excel("/Users/jinchenxie/Desktop/datasets/processed/VAD potential cohort admissions V2.xlsx") ``` ```{r} temp <- vad.baseline %>% group_by(rID) %>% summarise(count = n()) temp[temp$count>15,] ``` ## preprocessing ```{r} names(admission_30NA)[names(admission_30NA) == "READMISSION_DAYS"] <- "DAYS_READMISSION" admission_lab <- select(admission_30NA, -ends_with("_DAYS")) %>% select(rID, admission_count, WBC:HCT) admission_procedure <- admission_30NA %>% select(rID, admission_count, POST_VAD, POST_TRANSPLANT, CABG, PCI, IABP, ABLATION, PACEMAKER_IMPLANT, ICD_IMPLANT, BIV_ICD_IMPLANT) names(admission_lab)[names(admission_lab) == "NA"] <- "N_A" # admission_lab$DAYS_READMISSION[which(is.na(admission_lab$DAYS_READMISSION))] <- 0 ``` **We only consider admissions upto the 15th admission of each patient. And only patients who had at least 3 admissions.** # functions ```{r functions} generate_col_names <- function(measure_name, patients_id){ col_names <- c() for (val in patients_id){ col_names <- append(col_names, paste(measure_name, val, sep="_")) } return(col_names) } measurement_df <- function(original_df, new.df, measure_name, patients_id){ col.names <- generate_col_names(measure_name, patients_id) names(new.df) <- col.names for (val in seq(1, length(patients_id))){ temp_c <- original_df[[measure_name]][which(original_df$rID == patients_id[val])] new.df[[col.names[val]]] <- c(temp_c, rep(NA, nrow(new.df)-length(temp_c))) } return(new.df) } change_col_names <- function(prefix, num_adms){ col_names <- c() for (val in seq(1, num_adms)){ col_names <- append(col_names, paste(prefix, val, sep="_")) } return(col_names) } shape_transformation <- function(measure_name, original_df, num_adms, prefix){ patients_id <- unique(original_df$rID) new.df <- data.frame(matrix(ncol = length(patients_id), nrow = num_adms)) new.df <- measurement_df(original_df, new.df, measure_name, patients_id) new.df.t <- data.table::transpose(new.df) names(new.df.t) <- change_col_names(prefix, num_adms) new.df.t <- cbind(patients_id, new.df.t) return(new.df.t) } numreadings_criteria <- function(measure_name, original_df){ list_remove <- c() rid.list <- unique(original_df$rID) for (id in rid.list){ sub.df <- original_df[which(original_df$rID == id),] num.exist <- dim(sub.df[-which(is.na(sub.df[[measure_name]])),])[1] num.na <- dim(sub.df[which(is.na(sub.df[[measure_name]])),])[1] if (((num.exist<3) & (num.na!=0)) | (dim(sub.df)[1]<3)){ list_remove <- c(list_remove, id) }else{ next } } after.df <- original_df[-which(original_df$rID %in% list_remove),] return(after.df) } T_transform <- function(num_adms, df){ time.df <- data.frame(matrix(ncol = dim(df)[1], nrow = num_adms)) for (val in seq(1, dim(df)[1])){ time.df[[names(time.df)[val]]] <- seq(1, num_adms) } time.df.t <- data.table::transpose(time.df) names(time.df.t) <- change_col_names('T', num_adms) return(time.df.t) } generate_gbtm_df <- function(measure_name, prefix, original_df, num_adms){ criteria.admission <- numreadings_criteria(measure_name, original_df) lab.t <- shape_transformation(measure_name, criteria.admission, num_adms, prefix) time.t <- T_transform(num_adms, lab.t) combined <- cbind(lab.t, time.t) returnList <- list("labs" = lab.t, "combined" = combined) return(returnList) } generate_gbtm_df_2 <- function(measure_name, prefix, original_df, num_adms){ lab.t <- shape_transformation(measure_name, original_df, num_adms, prefix) time.t <- T_transform(num_adms, lab.t) combined <- cbind(lab.t, time.t) returnList <- list("labs" = lab.t, "combined" = combined) return(returnList) } ``` **Update: we don't need to remove values that are very small or big comparing to others (outliers). We only need to remove values that are highly likely to be small or big due to recording errors. The cnorm model in STATA can censored outliers.** # HGB ```{r set measurement name} measure = "HGB" ``` *Decide if remove any abnormal values* ```{r} # summary(admission_lab$HGB) # ggplot(data = admission.hgb, aes(HGB)) + geom_histogram() admission.hgb <- admission_lab ``` ## upto 15th admission ```{r} # output <- generate_gbtm_df(measure, measure, admission.hgb, num_adms = 15) # hgb.df.t.15 <- output$combined # hgb.15 <- output$labs ``` ## upto 10th admission ```{r} admission.hgb <- admission.hgb[which(admission.hgb$admission_count <= 10),] output <- generate_gbtm_df(measure, measure, admission.hgb, num_adms = 10) hgb.df.t.10 <- output$combined hgb.10 <- output$labs # data availability # In total, the data availability 1-sum(is.na(hgb.10))/prod(dim(hgb.10)) # On average, each patient we have ___% of measurements of all of his or her relevant quarters. 1-mean(colMeans(is.na(data.table::transpose(hgb.10[,-1])))) ``` ## upto 8th admission ```{r} # admission.hgb <- admission.hgb[which(admission.hgb$admission_count <= 8),] # output <- generate_gbtm_df(measure, measure, admission.hgb, num_adms = 8) # hgb.df.t.8 <- output$combined # hgb.8 <- output$labs ``` ```{r} # hgb.dfs <- list("adms_15"=hgb.df.t.15, "adms_10" = hgb.df.t.10, "adms_8"=hgb.df.t.8) # write.xlsx(hgb.dfs, '~/Desktop/datasets/processed/GBTM_data/HGB data.xlsx', col.names = TRUE, row.names = FALSE) rm(output, admission.hgb) ``` # eGFR ```{r} measure <- "EGFR" ``` *Decide if remove any abnormal data* ```{r} admission.egfr <- admission_lab # summary(admission.egfr$EGFR) # ggplot(data = admission.egfr, aes(EGFR)) + geom_histogram() admission.egfr[[measure]][which(admission_lab[[measure]]> 400)] <- NA_real_ ``` ## upto 15th admission ```{r} # output <- generate_gbtm_df(measure, measure, admission.egfr, num_adms = 15) # egfr.df.t.15 <- output$combined # egfr.15 <- output$labs ``` ## upto 10th admission ```{r} admission.egfr <- admission.egfr[which(admission.egfr$admission_count <= 10),] output <- generate_gbtm_df(measure, measure, admission.egfr, num_adms = 10) egfr.df.t.10 <- output$combined egfr.10 <- output$labs # data availability # In total, the data availability 1-sum(is.na(egfr.10))/prod(dim(egfr.10)) # On average, each patient we have ___% of measurements of all of his or her relevant quarters. 1-mean(colMeans(is.na(data.table::transpose(egfr.10[,-1])))) ``` ## upto 8th admission ```{r} # admission.egfr <- admission.egfr[which(admission.egfr$admission_count <= 8),] # output <- generate_gbtm_df(measure, measure, admission.egfr, num_adms = 8) # egfr.df.t.8 <- output$combined # egfr.8 <- output$labs ``` ```{r} # egfr.dfs <- list("adms_15"=egfr.df.t.15, "adms_10" = egfr.df.t.10, "adms_8"=egfr.df.t.8) # write.xlsx(egfr.dfs, '~/Desktop/datasets/processed/GBTM_data/EGFR data.xlsx', col.names = TRUE, row.names = FALSE) rm(output, admission.egfr) ``` # NA Sodium ```{r} measure <- "N_A" ``` *Decide if remove any outlier* ```{r} admission.na <- admission_lab # summary(admission_lab$N_A) # ggplot(data = admission.na, aes(N_A)) + geom_histogram() # admission.egfr[[measure]][which(admission_lab[[measure]]> 150)] <- NA_real_ ``` ## upto 15th admission ```{r} # output <- generate_gbtm_df(measure, measure, admission.na, num_adms = 15) # na.df.t.15 <- output$combined # na.15 <- output$labs ``` ## upto 10th admission ```{r} admission.na <- admission.na[which(admission.na$admission_count <= 10),] output <- generate_gbtm_df(measure, measure, admission.na, num_adms = 10) na.df.t.10 <- output$combined na.10 <- output$labs # data availability # In total, the data availability 1-sum(is.na(na.10))/prod(dim(na.10)) # On average, each patient we have ___% of measurements of all of his or her relevant quarters. 1-mean(colMeans(is.na(data.table::transpose(na.10[1:4,-1])))) ``` ## upto 8th admission ```{r} # admission.na <- admission.na[which(admission.na$admission_count <= 8),] # output <- generate_gbtm_df(measure, measure, admission.na, num_adms = 8) # na.df.t.8 <- output$combined # na.8 <- output$labs ``` ```{r} # na.dfs <- list("adms_15"=na.df.t.15, "adms_10" = na.df.t.10, "adms_8"=na.df.t.8) # write.xlsx(na.dfs, '~/Desktop/datasets/processed/GBTM_data/NA data.xlsx', col.names = TRUE, row.names = FALSE) rm(output, admission.na) ``` # Glucose ```{r} measure <- "GLUCOSE" ``` *Decide if remove any outlier* ```{r} admission.glucose <- admission_lab # summary(admission.glucose$GLUCOSE) # ggplot(data = admission.glucose, aes(GLUCOSE)) + geom_histogram() admission.glucose[[measure]][which(admission.glucose[[measure]] > 750)] <- NA_real_ ``` ## upto 15th admission ```{r} # output <- generate_gbtm_df(measure, measure, admission.glucose, num_adms = 15) # glucose.df.t.15 <- output$combined # na.15 <- output$labs ``` ## upto 10th admission ```{r} admission.glucose <- admission.glucose[which(admission.glucose$admission_count <= 10),] output <- generate_gbtm_df(measure, measure, admission.glucose, num_adms = 10) glucose.df.t.10 <- output$combined glucose.10 <- output$labs # data availability # In total, the data availability 1-sum(is.na(glucose.10))/prod(dim(glucose.10)) # On average, each patient we have ___% of measurements of all of his or her relevant quarters. 1-mean(colMeans(is.na(data.table::transpose(glucose.10[,-1])))) ``` ## upto 8th admission ```{r} # admission.glucose <- admission.glucose[which(admission.glucose$admission_count <= 8),] # output <- generate_gbtm_df(measure, measure, admission.glucose, num_adms = 8) # # glucose.df.t.8 <- output$combined # glucose.8 <- output$labs ``` ```{r} # glucose.dfs <- list("adms_15"=glucose.df.t.15, "adms_10" = glucose.df.t.10, "adms_8" = glucose.df.t.8) # write.xlsx(glucose.dfs, '~/Desktop/datasets/processed/GBTM_data/GLUCOSE data.xlsx', col.names = TRUE, row.names = FALSE) rm(output, admission.glucose) ``` # Platelets ```{r} measure = "PLATELETS" admission.platelets <- admission_lab summary(admission_lab$PLATELETS) # ggplot(data = admission.platelets, aes(PLATELETS)) + geom_histogram() # admission.platelets[[measure]][which(admission.platelets[[measure]] > 600)] <- NA_real_ ``` ## upto 15th admission ```{r} # output <- generate_gbtm_df(measure, measure, admission.platelets, num_adms = 15) # platelets.df.t.15 <- output$combined # na.15 <- output$labs ``` ## upto 10th admission ```{r} admission.platelets <- admission.platelets[which(admission.platelets$admission_count <= 10),] output <- generate_gbtm_df(measure, measure, admission.platelets, num_adms = 10) platelets.df.t.10 <- output$combined platelets.10 <- output$labs # data availability # In total, the data availability 1-sum(is.na(platelets.10))/prod(dim(platelets.10)) # On average, each patient we have ___% of measurements of all of his or her relevant quarters. 1-mean(colMeans(is.na(data.table::transpose(platelets.10[,-1])))) ``` ```{r} # platelets.dfs <- list("adms_15"=platelets.df.t.15, "adms_10" = platelets.df.t.10) # write.xlsx(platelets.dfs, '~/Desktop/datasets/processed/GBTM_data/PLATELETS data.xlsx', col.names = TRUE, row.names = FALSE) rm(output, admission.platelets) ``` # K ```{r} measure = "K" admission.k <- admission_lab # summary(admission_lab$K) # ggplot(data = admission.k, aes(K)) + geom_histogram() # admission.k[[measure]][which(admission.k[[measure]] > 7.5)] <- NA_real_ ``` ## upto 15th admission ```{r} # output <- generate_gbtm_df(measure, measure, admission.k, num_adms = 15) # k.df.t.15 <- output$combined # na.15 <- output$labs ``` ## upto 10th admission ```{r} admission.k <- admission.k[which(admission.k$admission_count <= 10),] output <- generate_gbtm_df(measure, measure, admission.k, num_adms = 10) k.df.t.10 <- output$combined k.10 <- output$labs # data availability # In total, the data availability 1-sum(is.na(k.10))/prod(dim(k.10)) # On average, each patient we have ___% of measurements of all of his or her relevant quarters. 1-mean(colMeans(is.na(data.table::transpose(k.10[,-1])))) ``` ```{r} # k.dfs <- list("adms_15"=k.df.t.15, "adms_10" = k.df.t.10) # write.xlsx(k.dfs, '~/Desktop/datasets/processed/GBTM_data/K data.xlsx', col.names = TRUE, row.names = FALSE) rm(output, admission.k) ``` # WBC ```{r} measure = "WBC" admission.wbc <- admission_lab # summary(admission_lab$PLATELETS) # ggplot(data = admission.wbc, aes(WBC)) + geom_histogram() admission.wbc[[measure]][which(admission.wbc[[measure]] > 50)] <- NA_real_ # ggplot(data = admission.wbc, aes(WBC)) + geom_histogram() ``` ## upto 15th admission ```{r} # output <- generate_gbtm_df(measure, measure, admission.wbc, num_adms = 15) # wbc.df.t.15 <- output$combined # na.15 <- output$labs ``` ## upto 10th admission ```{r} admission.wbc <- admission.wbc[which(admission.wbc$admission_count <= 10),] output <- generate_gbtm_df(measure, measure, admission.wbc, num_adms = 10) wbc.df.t.10 <- output$combined wbc.10 <- output$labs # data availability # In total, the data availability 1-sum(is.na(wbc.10))/prod(dim(wbc.10)) # On average, each patient we have ___% of measurements of all of his or her relevant quarters. 1-mean(colMeans(is.na(data.table::transpose(wbc.10[,-1])))) ``` ```{r} # wbc.dfs <- list("adms_15"=wbc.df.t.15, "adms_10" = wbc.df.t.10) # write.xlsx(wbc.dfs, '~/Desktop/datasets/processed/GBTM_data/WBC data.xlsx', col.names = TRUE, row.names = FALSE) rm(output, admission.wbc) ``` # Save a combined dataset ```{r} combined.labs.rids <- union(hgb.df.t.10$patients_id, union(union(egfr.10$patients_id, na.10$patients_id), union(wbc.10$patients_id, k.10$patients_id))) combined.labs.rids <- union(combined.labs.rids, union(platelets.10$patients_id, glucose.df.t.10$patients_id)) admission.union <- admission_lab[which(admission_lab$rID %in% combined.labs.rids),] admission.union <- admission.union[which(admission.union$admission_count <= 10),] admission.union[["EGFR"]][which(admission.union[["EGFR"]]> 400)] <- NA_real_ # admission.union[["PLATELETS"]][which(admission.union[["PLATELETS"]] > 600)] <- NA_real_ # admission.union[["K"]][which(admission.union[["K"]] > 7.5)] <- NA_real_ admission.union[["WBC"]][which(admission.union[["WBC"]] > 50)] <- NA_real_ admission.union[["GLUCOSE"]][which(admission.union[["GLUCOSE"]] > 750)] <- NA_real_ measure.list <- c("EGFR", "HGB", "N_A", "K", "PLATELETS", "WBC", "GLUCOSE") k <- 1 for (m in measure.list){ output <- generate_gbtm_df_2(m, m, admission.union, num_adms = 10) if (k==1){ combined.labs.df <- output$combined } else{ temp.labs.df <- output$labs %>% select(-patients_id) combined.labs.df <- cbind(combined.labs.df, temp.labs.df) } k <- k+1 } ``` ```{r} write.xlsx(combined.labs.df, '~/Desktop/datasets/processed/GBTM_data/combined 7 labs data_v2.xlsx', col.names = TRUE, row.names = FALSE) ``` ```{r} # combined.labs.df <- readxl:: read_excel('~/Desktop/datasets/processed/GBTM_data/combined 7 labs data_v2.xlsx') ``` # Add 5 attris of lab measurements Min, Max, Mean, Median, Std ```{r} last_ave_labs <- function(measure_name, admission_lab, combined.labs.df){ last.list <- c() ave.list <- c() min.list <- c() max.list <- c() std.list <- c() for (i in unique(combined.labs.df$patients_id)){ tp.data <- admission_lab[which(admission_lab$rID==i),-c(1, 2, 5, 11)][measure_name] goodIdx <- !is.na(tp.data) # if there's no non-NA value for this measurement/this patient if (length(tp.data[goodIdx])==0){ last.list <- c(last.list, NA_real_) ave.list <- c(ave.list, NA_real_) min.list <- c(min.list, NA_real_) max.list <- c(max.list, NA_real_) std.list <- c(std.list, NA_real_) } else if (length(tp.data[goodIdx])==1){ last.list <- c(last.list, tp.data[goodIdx][length(tp.data[goodIdx])]) ave.list <- c(ave.list, mean(tp.data[goodIdx])) min.list <- c(min.list, min(tp.data[goodIdx])) max.list <- c(max.list, max(tp.data[goodIdx])) std.list <- c(std.list, 0) } else { last.list <- c(last.list, tp.data[goodIdx][length(tp.data[goodIdx])]) ave.list <- c(ave.list, mean(tp.data[goodIdx])) min.list <- c(min.list, min(tp.data[goodIdx])) max.list <- c(max.list, max(tp.data[goodIdx])) std.list <- c(std.list, sd(tp.data[goodIdx])) } } returnList <- list("last" = last.list, "average" = ave.list, "min" = min.list, "max" = max.list, "sd" = std.list) return(returnList) } updated.admission.lab <- admission_lab updated.admission.lab[["EGFR"]][which(updated.admission.lab[["EGFR"]]> 300)] <- NA_real_ updated.admission.lab[["WBC"]][which(updated.admission.lab[["WBC"]] > 50)] <- NA_real_ updated.admission.lab[["GLUCOSE"]][which(updated.admission.lab[["GLUCOSE"]] > 750)] <- NA_real_ updated.admission.lab[["EGFR"]][which(updated.admission.lab[["EGFR"]]> 200)] <- 200 updated.admission.lab[["PLATELETS"]][which(updated.admission.lab[["PLATELETS"]] > 600)] <- 600 updated.admission.lab[["N_A"]][which(updated.admission.lab[["N_A"]] > 160)] <- 160 updated.admission.lab[["GLUCOSE"]][which(updated.admission.lab[["GLUCOSE"]] > 550)] <- 550 ggplot(data = updated.admission.lab, aes(GLUCOSE)) + geom_histogram() labs.ave.last <- combined.labs.df for (val in names(admission_lab)[-c(1, 2, 5, 11)]){ output <- last_ave_labs(val, updated.admission.lab, combined.labs.df) labs.ave.last <- cbind(labs.ave.last, output$last) labs.ave.last <- cbind(labs.ave.last, output$average) labs.ave.last <- cbind(labs.ave.last, output$min) labs.ave.last <- cbind(labs.ave.last, output$max) labs.ave.last <- cbind(labs.ave.last, output$sd) names(labs.ave.last)[names(labs.ave.last) == "output$last"] <- paste(val, "last", sep="_") names(labs.ave.last)[names(labs.ave.last) == "output$average"] <- paste(val, "average", sep="_") names(labs.ave.last)[names(labs.ave.last) == "output$min"] <- paste(val, "min", sep="_") names(labs.ave.last)[names(labs.ave.last) == "output$max"] <- paste(val, "max", sep="_") names(labs.ave.last)[names(labs.ave.last) == "output$sd"] <- paste(val, "sd", sep="_") } # fill the NA value in egfr with average value labs.ave.last$EGFR_last[is.na(labs.ave.last$EGFR_last)] <- mean(labs.ave.last$EGFR_last, na.rm = TRUE) labs.ave.last$EGFR_average[is.na(labs.ave.last$EGFR_average)] <- mean(labs.ave.last$EGFR_average, na.rm = TRUE) labs.ave.last$EGFR_min[is.na(labs.ave.last$EGFR_min)] <- mean(labs.ave.last$EGFR_min, na.rm = TRUE) labs.ave.last$EGFR_max[is.na(labs.ave.last$EGFR_max)] <- mean(labs.ave.last$EGFR_max, na.rm = TRUE) labs.ave.last$EGFR_sd[is.na(labs.ave.last$EGFR_sd)] <- mean(labs.ave.last$EGFR_sd, na.rm = TRUE) ``` ```{r} openxlsx::write.xlsx(labs.ave.last, '~/Desktop/datasets/processed/GBTM_data/last and average labs data.xlsx', col.names = TRUE, row.names = FALSE) ``` # Add covariates and labels ## Add outcome labels ```{r} labs7.df <- readxl::read_excel("~/Desktop/datasets/processed/GBTM_data/combined 7 labs data.xlsx", sheet = 'Sheet 1') labels.df <- baseline.df %>% select("rID", "CTB", "30_day_CTB", "60_day_CTB", "90_day_CTB", "1_year_CTB") names(labels.df) <- c("rID", "CTB", "_30_day_CTB", "_60_day_CTB", "_90_day_CTB", "_1_year_CTB") labels.df <- labels.df[which(labels.df$rID %in% labs7.df$patients_id),] labs.label <- cbind(labs7.df, labels.df) ``` ```{r} write.xlsx(labs.label, '~/Desktop/datasets/processed/GBTM_data/combined 7 labs_labels.xlsx', col.names = TRUE, row.names = FALSE) ``` ## Add time-varying covariates POST_VAD and POST_TRANSPLANT in admission dataset We would like to know their enduring effects. So, we make the all indicators = 1 after the VAD or HTx event. ```{r} labs7.df.2 <- readxl::read_excel("~/Desktop/HF_Research/datasets/processed/GBTM_data/combined 7 labs_labels.xlsx", sheet = 'Sheet 1') ``` ```{r generate tcov var for VAD and HTx} admission.subdf <- admission_30NA[which((admission_30NA$rID %in% labs7.df.2$patients_id)&(admission_30NA$admission_count<=10)),] %>% select(rID, POST_VAD, POST_TRANSPLANT, admission_count) for (i in unique(admission.subdf$rID)){ temp.df <- admission.subdf[which(admission.subdf$rID==i),] if ((1 %in% temp.df$POST_VAD) & (1 %in% temp.df$POST_TRANSPLANT)) { temp.df$POST_VAD[seq(which(temp.df$POST_VAD==1)[1], which(temp.df$POST_TRANSPLANT==1)[1])-1] <- 1 admission.subdf[which(admission.subdf$rID==i),]$POST_VAD <- temp.df$POST_VAD }else if (1 %in% temp.df$POST_VAD){ temp.df$POST_VAD[seq(which(temp.df$POST_VAD==1)[1],dim(temp.df)[1])] <- 1 admission.subdf[which(admission.subdf$rID==i),]$POST_VAD <- temp.df$POST_VAD } if (1 %in% temp.df$POST_TRANSPLANT){ temp.df$POST_TRANSPLANT[seq(which(temp.df$POST_TRANSPLANT==1)[1],dim(temp.df)[1])] <- 1 admission.subdf[which(admission.subdf$rID==i),]$POST_TRANSPLANT <- temp.df$POST_TRANSPLANT } } post.vad.df <- reshape2::dcast(admission.subdf, rID ~ admission_count, value.var="POST_VAD", fill= NA_real_ ) names(post.vad.df) <- c("rID", generate_col_names("POST_VAD", seq(1,10))) post.htx.df <- reshape2::dcast(admission.subdf, rID ~ admission_count, value.var="POST_TRANSPLANT", fill = NA_real_) names(post.htx.df) <- c("rID", generate_col_names("POST_HTX", seq(1,10))) labs7.lab.vary <- cbind(labs7.df.2, cbind(post.vad.df[,-1], post.htx.df[-1])) labs7.lab.vary$rID <- NULL ``` ```{r} write.xlsx(labs7.lab.vary, '~/Desktop/HF_Research/datasets/processed/GBTM_data/labs_labels_tvarycov.xlsx', col.names = TRUE, row.names = FALSE) ``` Other procedures that have > 1% positive rate: PCI, IABP, ABLATION, ICD_IMPLANT, BIV_ICD_IMPLANT ```{r gen tcov var for other procedure} admission.subdf <- admission_30NA[which((admission_30NA$rID %in% labs7.df.2$patients_id) & (admission_30NA$admission_count<=10)),] %>% select(rID, PCI, IABP, ABLATION, ICD_IMPLANT, BIV_ICD_IMPLANT, admission_count) procedure.list <- c("PCI", "IABP", "ABLATION", "ICD_IMPLANT", "BIV_ICD_IMPLANT") for (i in unique(admission.subdf$rID)){ temp.df <- admission.subdf[which(admission.subdf$rID==i),] for (val in procedure.list){ if (1 %in% temp.df[val]){ temp.df[val][which(temp.df[val]==1)] <- 1 admission.subdf[which(admission.subdf$rID==i),][val] <- temp.df[val] } } } procedures.df <- labs7.lab.vary for (val in procedure.list){ temp.proc.df <- reshape2::dcast(admission.subdf, rID ~ admission_count, value.var=val, fill= NA_real_ ) names(temp.proc.df) <- c("rID", generate_col_names(val, seq(1,10))) procedures.df <- cbind(procedures.df, temp.proc.df[,-1]) } ``` ```{r} write.xlsx(procedures.df, '~/Desktop/datasets/processed/GBTM_data/labs_proc_cov.xlsx', col.names = TRUE, row.names = FALSE) ``` ## Add baseline covariates ```{r} labs7.lab.vary <- readxl::read_excel("~/Desktop/HF_Research/datasets/processed/GBTM_data/labs_labels_tvarycov.xlsx", sheet = 'Sheet 1') ``` ```{r} baseline.attris.df <- baseline.profile.df %>% select("rID", "AGE_ADMISSION", "FEMALE", "RACE_White", starts_with("TOBACCO_"), starts_with("INSUR_"), starts_with("BP_"), "PULSE", "BMI", ends_with("_HST"), starts_with("HX_"), starts_with("PRIOR_"), "CCI_TOTAL_SCORE", starts_with("CCI_"), ends_with("_00"), "CTB", ends_with("_CTB")) baseline.attris.df$TOBACCO_STATUS_LABEL <- NULL baseline.attris.df <- baseline.attris.df[which(baseline.attris.df$rID %in% labs7.lab.vary$patients_id), -1] labs7.lab.vary.sta <- cbind(labs7.lab.vary, baseline.attris.df) write.xlsx(labs7.lab.vary.sta, '~/Desktop/HF_Research/datasets/processed/GBTM_data/labs_labels_tvarycov.xlsx', col.names = TRUE, row.names = FALSE) ``` # identify patients in each traj group ```{r} df <- read_excel("~/Desktop/trial save.xlsx", sheet="Sheet1") groups <- sort(unique(df$`_traj_Group`)) pat.membership <- vector(mode="list", length = length(groups)) for (group in groups){ pat.membership[[group]] <- df$patients_id[which(df$`_traj_Group`==group)] } ``` ```{r} # hgb.membership <- pat.membership # egfr.membership <- pat.membership # na.membership <- pat.membership # platelets.membership <- pat.membership # k.membership <- pat.membership # wbc.membership <- pat.membership ``` ```{r} num_exist_check <- function(gbtm.df, membership.df, measure){ df <- gbtm.df %>% select( patients_id, starts_with(measure)) periods <- length(names(df))-1 exist.list <- vector(mode="list", length = length(membership.df)) for (i in (1:length(membership.df))){ sub.df <- df[which(df$patients_id %in% membership.df[[i]]),] df.temp <- sub.df %>% select(starts_with(paste(measure, "_", sep=""))) %>% select(c(1:periods)) %>% summarise_all(funs(sum(!is.na(.)))) exist.list[[i]] <- df.temp[1,] } return(exist.list) } ``` ```{r} exist.l <- num_exist_check(combined.labs.df, pat.membership, "K") # tmp <- exist.l[1] # write.xlsx(tmp, '~/Desktop/temp.xlsx', col.names = TRUE, row.names = FALSE) exist.l ``` ```{r} tmp <- admission_30NA[which((admission_30NA$rID %in% pat.membership[[3]]) & (admission_30NA$admission_count==1)),] %>% select(rID, admission_count, WBC) summary(tmp) ``` ```{r} row.names(temp.tab.filtered) ``` <file_sep>--- title: "APP, OCC, Mismatch analysis" output: html_notebook --- ```{r global_options, include=FALSE} knitr::opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE) library(readxl) library(openxlsx) library(data.table) ``` # import data ```{r} df <- read_excel("~/Desktop/trial save.xlsx", sheet="Sheet1") ``` # extract BIC ```{r} bic <- df$bic[1] groups <- sort(unique(df$`_traj_Group`)) # create dataframe for storage prob_df <- data.frame("avePP"=numeric(length(groups)), row.names=groups) # "avePPm"=numeric(length(groups)), # "OCC"=numeric(length(groups)), "OCCm"=numeric(length(groups)), # "mis"=numeric(length(groups)), "mism"=numeric(length(groups)), # "SD"=numeric(length(groups)), "SDm"=numeric(length(groups)), # "smallAss"=numeric(length(groups)), # "smallEst"=numeric(length(groups)), prob_df.2 <- data.frame("XinGroup"=numeric(length(groups)), row.names=groups) group_probs <- vector(mode="list", length(groups)) # group_probs <- rep(0, length(groups)) # n_members <- rep(0, length(groups)) # find posterior probabilities for each group for (row in 1:nrow(df)){ g <- df[[row, "_traj_Group"]] group_probs[[g]] <- c(group_probs[[g]], df[[row, paste0("_traj_ProbG", g)]]) # n_members[g] <- n_members[g] + 1 } for (group in groups){ # calculate APPA prob_df[group, "avePP"] <- mean(group_probs[[group]], na.rm=TRUE) prob_df.2[group, "XinGroup"] <- length(group_probs[[group]])/nrow(df) # prob_df[toString(group), "avePPm"] <- min(group_probs[[group]], na.rm=TRUE) } prob_df <- t(prob_df) prob_df.2 <- t(prob_df.2) prob_df <- cbind(bic, prob_df, prob_df.2) prob_df <- as.data.frame(prob_df) names(prob_df) <- c("BIC", rep("AvePP", length(groups)), rep("Real%", 5)) row.names(prob_df) <- NULL ``` ```{r} write.xlsx(prob_df, '~/Desktop/app_occ.xlsx', col.names = TRUE, row.names = FALSE) ``` ```{r} traj.na.1 <- c() traj.na.5 <- c() traj.na.8 <- c() traj.na.9 <- c() traj.na.10 <- c() mem <- vector("list", length = length(unique(df$`_traj_Group`))) for (group in groups){ mem[[group]] <- df$patients_id[which(df$`_traj_Group`== group)] group.lab <- combined.labs.df[which(combined.labs.df$patients.id %in% mem[[group]]),] traj.na.1 <- c(traj.na.1, dim(group.lab[which(is.na(group.lab$HGB_1)),])[1]/length(mem[[group]])) traj.na.2 <- c(traj.na.5, dim(group.lab[which(is.na(group.lab$EGFR_2)),])[1]/length(mem[[group]])) traj.na.3 <- c(traj.na.8, dim(group.lab[which(is.na(group.lab$EGFR_3)),])[1]/length(mem[[group]])) traj.na.13 <- c(traj.na.9, dim(group.lab[which(is.na(group.lab$EGFR_13)),])[1]/length(mem[[group]])) traj.na.14 <- c(traj.na.10, dim(group.lab[which(is.na(group.lab$EGFR_14)),])[1]/length(mem[[group]])) } cat(traj.na.1,"\n\n", traj.na.2, "\n\n", traj.na.3, "\n\n", traj.na.13, "\n\n", traj.na.14, "\n\n", traj.na.15) ``` <file_sep>--- title: "GBTM_data_processing2" author: "<NAME>" date: "6/12/2020" output: html_document --- ```{r global_options, include=FALSE} knitr::opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE) library(tidyverse) library(knitr) library(readxl) library(openxlsx) library(data.table) library(Hmisc) ``` # import admission dataset The dataset used is admission withou 30% NA tolerance. ```{r} admission_30NA <- read_excel("~/Desktop/datasets/processed/Filtered Attributes Admission v2.xlsx", sheet = 'Sheet 1') baseline.df <- read_excel('~/Desktop/datasets/processed/Filtered Baseline imputed.xlsx', sheet = 'Sheet 1') ``` REMOVE admission that the lab measurements were taken after the VAD procedure was done. --> 752 9438 10540 ```{r} # temp1 <- admission_30NA[which((admission_30NA$POST_VAD == 1) &(admission_30NA$POST_VAD_DAYS <admission_30NA$WBC_DAYS)),]$rID # # order.inv.rid <- intersect(patients_id, temp1) # order.inv.rid <- c(752, 9438, 10540) # # admission_30NA <- admission_30NA[-which((admission_30NA$rID %in% order.inv.rid) & (admission_30NA$POST_VAD == 1)),] # View(admission_lab[which(admission_lab$rID %in% order.inv.rid.2),]) # order.inv.rid.2 <- order.inv.rid.2[-4] # admission_30NA <- admission_30NA[-which((admission_30NA$rID %in% order.inv.rid.2) & (admission_30NA$POST_TRANSPLANT == 1)),] ``` We are only interested in the continuous lab measurements here. **New dataset: admission_lab** ```{r} names(admission_30NA)[names(admission_30NA) == "READMISSION_DAYS"] <- "DAYS_READMISSION" admission_lab <- select(admission_30NA, -ends_with("_DAYS")) %>% select(rID, DAYS_READMISSION, WBC:HCT) admission_procedure <- admission_30NA %>% select(rID, admission_count, POST_VAD, POST_TRANSPLANT, CABG, PCI, IABP, ABLATION, PACEMAKER_IMPLANT, ICD_IMPLANT, BIV_ICD_IMPLANT) names(admission_lab)[names(admission_lab) == "NA"] <- "N_A" admission_lab$DAYS_READMISSION[which(is.na(admission_lab$DAYS_READMISSION))] <- 0 ``` ```{r} # summary(admission_lab) # summary(baseline.df$POST_VAD) ``` # Data Transformation ## WBC **Normal range of WBC is 4-11. ** *We remove WBC > 40 as outliers. There are 44 admissions with WBC > 50 that got removed.* ```{r} measure = "WBC" admission.wbc <- admission_lab summary(admission_lab[[measure]]) print(dim(admission_lab[which(admission_lab$WBC > 40),])) admission.wbc[[measure]][which(admission_lab[[measure]]> 40)] <- NA_real_ # ggplot(data = admission.wbc, aes(WBC)) + geom_histogram(binwidth = 1) ``` ```{r} admission_lab <- admission.wbc ``` ## HGB ```{r} measure = "HGB" admission.hgb <- admission_lab summary(admission_lab[[measure]]) # ggplot(data = admission.hgb, aes(HGB)) + geom_histogram() ``` ```{r} admission_lab <- admission.hgb ``` ## EGFR ```{r} measure = "EGFR" admission.egfr <- admission_lab summary(admission_lab[[measure]]) # ggplot(data = admission.egfr, aes(EGFR)) + geom_histogram() dim(admission_lab[which(admission_lab$EGFR > 200),]) admission.egfr[[measure]][which(admission_lab[[measure]]> 200)] <- NA_real_ # ggplot(data = admission.egfr, aes(EGFR)) + geom_histogram() ``` ```{r} admission_lab <- admission.egfr ``` ```{r} View(admission_lab[which(admission_lab$EGFR<30),]) ``` ## K ```{r} measure = "K" admission.k <- admission_lab # summary(admission_lab[[measure]]) # ggplot(data = admission.k, aes(K)) + geom_histogram() ``` ```{r} admission_lab <- admission.k ``` ## N_A ```{r} measure = "N_A" admission.na <- admission_lab # summary(admission_lab[[measure]]) # ggplot(data = admission.na, aes(N_A)) + geom_histogram() ``` ```{r} admission_lab <- admission.na ``` ## GLUCOSE ```{r} measure = "GLUCOSE" admission.glucose <- admission_lab summary(admission_lab[[measure]]) ggplot(data = admission.glucose, aes(GLUCOSE)) + geom_histogram() ``` ```{r} dim(admission_lab[which(admission_lab$GLUCOSE > 500),]) admission.glucose[[measure]][which(admission_lab[[measure]]> 500)] <- NA_real_ ``` ```{r} admission.glucose[[measure]] <- log10(admission.glucose[[measure]]) # # ggplot(data = admission.glucose, aes(GLUCOSE)) + geom_histogram() + xlab("log10(glucose)") ``` ```{r} # normalize <- function(x) { # return ((x - min(x, na.rm = TRUE)) / (max(x, na.rm = TRUE) - min(x, na.rm = TRUE))) # } # admission.glucose[[measure]] <- normalize(admission.glucose[[measure]]) # ggplot(data = admission.glucose, aes(GLUCOSE)) + geom_histogram() ``` ```{r} admission_lab <- admission.glucose ``` ## PLATELETS ```{r} measure = "PLATELETS" admission.platelet <- admission_lab # summary(admission_lab[[measure]]) # ggplot(data = admission.platelet, aes(PLATELETS)) + geom_histogram() ``` ```{r} dim(admission_lab[which(admission_lab$PLATELETS > 750),]) admission.platelet[[measure]][which(admission_lab[[measure]]> 750)] <- NA_real_ ``` ```{r} admission_lab <- admission.platelet ``` ## HCT ```{r} measure = "HCT" admission.hct <- admission_lab # summary(admission_lab[[measure]]) # ggplot(data = admission.hct, aes(HCT)) + geom_histogram() ``` ```{r} admission_lab <- admission.hct ``` # ------- ```{r} rm(admission.wbc, admission.egfr, admission.hgb, admission.k, admission.na, admission.glucose, admission.platelet, admission.hct) rm(measure) ``` # only >=3 readmissions ```{r} readmission_counts <- admission_lab %>% group_by(rID) %>% tally() sub_3to15_rID <- readmission_counts[which((readmission_counts$n>2) & (readmission_counts$n<16)),]$rID admission_lab.3to15 <- admission_lab[which(admission_lab$rID %in% sub_3to15_rID),] ``` # allow missing at random ```{r} list_remove <- c() mea.rm <- vector(mode="list", length=7) # for each patient exist in the admission_lab.3to5 subset: for (id in sub_3to15_rID){ sub.df <- admission_lab.3to15[which(admission_lab.3to15$rID == id),] num_wbc <- dim(sub.df[-which(is.na(sub.df$WBC)),])[1] na_wbc <- dim(sub.df[which(is.na(sub.df$WBC)),])[1] num_hgb <- dim(sub.df[-which(is.na(sub.df$HGB)),])[1] na_hgb <- dim(sub.df[which(is.na(sub.df$HGB)),])[1] num_egfr <- dim(sub.df[-which(is.na(sub.df$EGFR)),])[1] na_egfr <- dim(sub.df[which(is.na(sub.df$EGFR)),])[1] num_k <- dim(sub.df[-which(is.na(sub.df$K)),])[1] na_k <- dim(sub.df[which(is.na(sub.df$K)),])[1] num_na <- dim(sub.df[-which(is.na(sub.df$N_A)),])[1] na_na <- dim(sub.df[which(is.na(sub.df$N_A)),])[1] num_glucose <- dim(sub.df[-which(is.na(sub.df$GLUCOSE)),])[1] na_glucose <- dim(sub.df[which(is.na(sub.df$GLUCOSE)),])[1] num_platelets <- dim(sub.df[-which(is.na(sub.df$PLATELETS)),])[1] na_platelets <- dim(sub.df[which(is.na(sub.df$PLATELETS)),])[1] if ((num_wbc<3) & (na_wbc!=0)){ mea.rm[[1]] <- c(mea.rm[[1]], id) } if ((num_hgb<3) & (na_hgb!=0)){ mea.rm[[2]] <- c(mea.rm[[2]], id) } if ((num_egfr<3) & (na_egfr!=0)){ mea.rm[[3]] <- c(mea.rm[[3]], id) } if ((num_k<3) & (na_k!=0)){ mea.rm[[4]] <- c(mea.rm[[4]], id) } if ((num_na<3) & (na_na!=0)){ mea.rm[[5]] <- c(mea.rm[[5]], id) } if ((num_glucose<3) & (na_glucose!=0)){ mea.rm[[6]] <- c(mea.rm[[6]], id) } if ((num_platelets<3) & (na_platelets!=0)){ mea.rm[[7]] <- c(mea.rm[[7]], id) } if (((num_wbc<3) & (na_wbc!=0)) | ((num_hgb<3) & (na_hgb!=0)) | ((num_egfr<3) & (na_egfr!=0)) | ((num_k<3) & (na_k!=0)) | ((num_na<3) & (na_na!=0)) | ((num_glucose<3) & (na_glucose!=0)) | ((num_platelets<3) & (na_platelets!=0))){ list_remove <- append(list_remove, id) }else{ next } } inter.id <- c() for (i in sub_3to15_rID){ if ((i %in% mea.rm[[1]]) & (i %in% mea.rm[[2]]) & (i %in% mea.rm[[3]]) & (i %in% mea.rm[[4]]) & (i %in% mea.rm[[5]]) & (i %in% mea.rm[[6]]) & (i %in% mea.rm[[7]])){ inter.id <- c(inter.id, i) } } admission_lab.NArandom <- admission_lab.3to15[-which(admission_lab.3to15$rID %in% list_remove),] patients_id <- unique(admission_lab.NArandom$rID) ``` | ((num_hct<3) & (na_hct!=0)) if ((num_hct<3) & (na_hct!=0)){ mea.rm[[8]] <- c(mea.rm[[8]], id) } ```{r} rm(num_wbc,na_wbc,num_hgb ,na_hgb,num_egfr,na_egfr,num_k,na_k, num_na, na_na, num_glucose, na_glucose, na_platelets, num_platelets) rm(id, i, inter.id, sub_3to15_rID, sub.df, readmission_counts, list_remove) ``` **1558 patients left in the cohort.** # transform procedure attributes ```{r} admission_procedure <- admission_procedure[which(admission_procedure$rID %in% patients_id),] admission_procedure.updated <- admission_procedure for (id in patients_id){ temp.df <- admission_procedure[which(admission_procedure$rID == id),] for (val in names(temp.df)[-c(1,2)]){ if (max(temp.df[val])==1) { count <- temp.df[which(temp.df[val]==1),]$admission_count if (length(count)>1){ count <- count[1] } admission_procedure.updated[which(admission_procedure.updated$rID==id & admission_procedure.updated$admission_count>=count), val] <- 1 } } } ``` # ------- # Reshape for traj model input *Functions used to transform the shape of dataset:* ```{r} generate_col_names <- function(measure_name, patients_id){ col_names <- c() for (val in patients_id){ col_names <- append(col_names, paste(measure_name, val, sep="_")) } return(col_names) } measurement_df <- function(orginial_df, new_df, measure_name){ col.names <- generate_col_names(measure_name, patients_id) names(new_df) <- col.names for (val in seq(1, length(unique(admission_lab.NArandom$rID)))){ temp_c <- orginial_df[[measure_name]][which(orginial_df$rID == patients_id[val])] new_df[[col.names[val]]] <- c(temp_c, rep(NA, nrow(new_df)-length(temp_c))) } return(new_df) } change_col_names <- function(measure_name){ col_names <- c() for (val in seq(1,15)){ col_names <- append(col_names, paste(measure_name, val, sep="_")) } return(col_names) } ``` *WBC* ```{r} # wbc_ob <- complete.labs.3to15 %>% select(rID, WBC) wbc.df <- data.frame(matrix(ncol = length(unique(admission_lab.NArandom$rID)), nrow = 15)) wbc.df <- measurement_df(orginial_df = admission_lab.NArandom, new_df = wbc.df, measure_name = 'WBC') wbc.df.t <-data.table::transpose(wbc.df) names(wbc.df.t) <- change_col_names('WBC') ``` *HGB* ```{r} # wbc_ob <- complete.labs.3to15 %>% select(rID, WBC) hgb.df <- data.frame(matrix(ncol = length(unique(admission_lab.NArandom$rID)), nrow = 15)) hgb.df <- measurement_df(orginial_df = admission_lab.NArandom, new_df = hgb.df, measure_name = 'HGB') hgb.df.t <-data.table::transpose(hgb.df) names(hgb.df.t) <- change_col_names('HGB') ``` *EGFR* ```{r} # wbc_ob <- complete.labs.3to15 %>% select(rID, WBC) egfr.df <- data.frame(matrix(ncol = length(unique(admission_lab.NArandom$rID)), nrow = 15)) egfr.df <- measurement_df(orginial_df = admission_lab.NArandom, new_df = egfr.df, measure_name = 'EGFR') egfr.df.t <-data.table::transpose(egfr.df) names(egfr.df.t) <- change_col_names('EGFR') ``` *K* ```{r} # wbc_ob <- complete.labs.3to15 %>% select(rID, WBC) k.df <- data.frame(matrix(ncol = length(unique(admission_lab.NArandom$rID)), nrow = 15)) k.df <- measurement_df(orginial_df = admission_lab.NArandom, new_df = k.df, measure_name = 'K') k.df.t <-data.table::transpose(k.df) names(k.df.t) <- change_col_names('K') ``` *N_A* ```{r} # wbc_ob <- complete.labs.3to15 %>% select(rID, WBC) n_a.df <- data.frame(matrix(ncol = length(unique(admission_lab.NArandom$rID)), nrow = 15)) n_a.df <- measurement_df(orginial_df = admission_lab.NArandom, new_df = n_a.df, measure_name = 'N_A') n_a.df.t <-data.table::transpose(n_a.df) names(n_a.df.t) <- change_col_names('N_A') ``` *GLUCOSE* ```{r} # wbc_ob <- complete.labs.3to15 %>% select(rID, WBC) glucose.df <- data.frame(matrix(ncol = length(unique(admission_lab.NArandom$rID)), nrow = 15)) glucose.df <- measurement_df(orginial_df = admission_lab.NArandom, new_df = glucose.df, measure_name = 'GLUCOSE') glucose.df.t <-data.table::transpose(glucose.df) names(glucose.df.t) <- change_col_names('GLUCOSE') ``` *PLATELETS* ```{r} # wbc_ob <- complete.labs.3to15 %>% select(rID, WBC) platelets.df <- data.frame(matrix(ncol = length(unique(admission_lab.NArandom$rID)), nrow = 15)) platelets.df <- measurement_df(orginial_df = admission_lab.NArandom, new_df = platelets.df, measure_name = 'PLATELETS') platelets.df.t <- data.table::transpose(platelets.df) names(platelets.df.t) <- change_col_names('PLATELETS') ``` *HCT* ```{r} # wbc_ob <- complete.labs.3to15 %>% select(rID, WBC) # hct.df <- data.frame(matrix(ncol = length(unique(admission_lab.NArandom$rID)), nrow = 15)) # # hct.df <- measurement_df(orginial_df = admission_lab.NArandom, new_df = hct.df, measure_name = 'HCT') # # hct.df.t <- data.table::transpose(hct.df) # # names(hct.df.t) <- change_col_names('HCT') ``` *Procedures* ```{r} procedure.list <- names(admission_procedure.updated)[-c(1,2)] procedure.df <- data.frame(matrix(ncol = length(unique(admission_procedure.updated$rID)), nrow = 15)) procedure.df <- measurement_df(orginial_df = admission_procedure.updated, new_df = procedure.df, measure_name = procedure.list[1]) procedure.df.t <- data.table::transpose(procedure.df) names(procedure.df.t) <- change_col_names(procedure.list[1]) for (val in procedure.list[-1]){ procedure.df.temp <- data.frame(matrix(ncol = length(unique(admission_procedure.updated$rID)), nrow = 15)) procedure.df.temp <- measurement_df(orginial_df = admission_procedure.updated, new_df = procedure.df.temp, measure_name = val) procedure.df.temp.t <- data.table::transpose(procedure.df.temp) names(procedure.df.temp.t) <- change_col_names(val) procedure.df.t <- cbind(procedure.df.t, procedure.df.temp.t) } ``` ## number of readmissions ```{r} time.df <- data.frame(matrix(ncol = length(unique(admission_lab.NArandom$rID)), nrow = 15)) names(time.df) <- generate_col_names('T', patients_id) for (val in seq(1, length(unique(admission_lab.NArandom$rID)))){ time.df[[names(time.df)[val]]] <- seq(1,15) } time.df.t <- data.table::transpose(time.df) names(time.df.t) <- change_col_names('T') ``` # save dataset ```{r} combined.labs.time <- cbind(patients_id, wbc.df.t, hgb.df.t, egfr.df.t, k.df.t, n_a.df.t, glucose.df.t, platelets.df.t, time.df.t, procedure.df.t) write.xlsx(combined.labs.time, '~/Desktop/datasets/processed/GBTM_data/combined gbtm stata data v4.xlsx', col.names = TRUE, row.names = FALSE) ``` ```{r} rm(egfr.df, wbc.df, hgb.df, k.df, k.df.t, n_a.df, glucose.df.t, glucose.df, platelets.df, time.df, time.df.t) rm(val, generate_col_names, measurement_df, change_col_names) ``` # dataset characteristics ```{r} # summary(admission_lab.NArandom$WBC) # ggplot(data = admission_lab.NArandom, aes(WBC)) + geom_histogram() # # summary(admission_lab.NArandom$HGB) # ggplot(data = admission_lab.NArandom, aes(HGB)) + geom_histogram() # # summary(admission_lab.NArandom$EGFR) # ggplot(data = admission_lab.NArandom, aes(EGFR)) + geom_histogram() # # summary(admission_lab.NArandom$K) # ggplot(data = admission_lab.NArandom, aes(K)) + geom_histogram() # # summary(admission_lab.NArandom$GLUCOSE) # ggplot(data = admission_lab.NArandom, aes(GLUCOSE)) + geom_histogram() # # summary(admission_lab.NArandom$N_A) # ggplot(data = admission_lab.NArandom, aes(N_A)) + geom_histogram() # # summary(admission_lab.NArandom$PLATELETS) # ggplot(data = admission_lab.NArandom, aes(PLATELETS)) + geom_histogram() ``` **How many readings available at each readmission times?** # missing CHECK ```{r} combined.labs.time %>% select(starts_with("N_A_")) %>% summarise_all(funs(na = sum(is.na(.))/(dim(combined.labs.time)[1]), left = sum(!is.na(.)))) ``` ```{r} df <- read_excel("~/Desktop/trial save.xlsx", sheet="Sheet1") ``` # identify patients in each traj group ```{r} groups <- sort(unique(df$`_traj_Group`)) pat.membership <- vector(mode="list", length = length(groups)) for (group in groups){ pat.membership[[group]] <- df$patients_id[which(df$`_traj_Group`==group)] } ``` ### WBC ```{r} wbc.t <- cbind(patients_id, wbc.df.t) na.percol <- vector(mode="list", length=length(pat.membership)) for (i in 1:length(pat.membership)){ wbc.groups <- wbc.t[which(wbc.t$patients_id %in% pat.membership[[i]]),] na.percol[[i]] <- wbc.groups %>% select(starts_with("WBC_")) %>% summarise_all(funs(sum(is.na(.))/(dim(wbc.groups)[1]))) } for (i in 1:length(pat.membership)){ sub.percol <- data.frame(t(na.percol[[i]])) names(sub.percol) <- c("num_na") print(ggplot(data = sub.percol, aes(x=1:15, y=num_na)) + geom_line(linetype = "dashed") + geom_point() + xlab("times of admission") + ylab("% NA value")+ scale_y_continuous(breaks = seq(0, 1, 0.1))) } ``` ### NA ```{r} n_a.t <- cbind(patients_id, n_a.df.t) na.percol <- vector(mode="list", length=length(pat.membership)) for (i in 1:length(pat.membership)){ n_a.groups <- n_a.t[which(n_a.t$patients_id %in% pat.membership[[i]]),] na.percol[[i]] <- n_a.groups %>% select(starts_with("N_A_")) %>% summarise_all(funs(sum(is.na(.))/(dim(n_a.groups)[1]))) } for (i in 1:length(pat.membership)){ sub.percol <- data.frame(data.table::transpose(na.percol[[i]])) names(sub.percol) <- c("num_na") print(ggplot(data = sub.percol, aes(x=1:15, y=num_na)) + geom_line(linetype = "dashed") + geom_point() + xlab("times of admission") + ylab("% NA value")+ scale_y_continuous(breaks = seq(0, 1, 0.1))) } ``` <file_sep>--- title: "GBTM baseline covariates" date: "6/15/2020" output: html_document --- ```{r global_options, include=FALSE} knitr::opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE) library(tidyverse) library(knitr) library(readxl) library(openxlsx) library(data.table) library(Hmisc) ``` **Baseline covariates to use: AGE_ADMISSION, FEMALE, RACE, TOBACCO_STATUS_LABEL, HOSP_ROLLUP_GROUPING** ```{r} series.df <- read_excel('~/Desktop/datasets/processed/GBTM_data/combined gbtm stata data v2.xlsx', sheet = 'Sheet 1') baseline.df <- read_excel("/Users/jinchenxie/Desktop/datasets/processed/GBTM_data/gbtm Cohort data combined.xlsx", sheet = 'baseline') series.df.2 <- read_excel('~/Desktop/datasets/processed/GBTM_data/combined gbtm stata data v4.xlsx', sheet = 'Sheet 1') # admission.df <- read_excel("/Users/jinchenxie/Desktop/datasets/processed/GBTM_data/gbtm Cohort data combined.xlsx", sheet = "admission") admission.relevant <- read_excel('~/Desktop/datasets/processed/admission_procedure_everflags.xlsx', sheet = 'Sheet 1') ``` # save dataset ```{r} full.df <- cbind(baseline.df, admission.relevant[,-1]) covariates.df <- full.df %>% select(all_of(list.attris)) ``` ```{r} # write.xlsx(admission.relevant, "~/Desktop/datasets/processed/baseline_procedure_everflags.xlsx", col.names = TRUE, row.names = FALSE) ``` ```{r} combined.baseline <- cbind(series.df.2, covariates.df) write.xlsx(combined.baseline, '~/Desktop/datasets/processed/GBTM_data/combined gbtm stata data v5.xlsx', col.names = TRUE, row.names = FALSE) ``` <file_sep>--- title: "R Notebook" output: html_notebook editor_options: chunk_output_type: console --- ```{r} library(readxl) library(tidyverse) library(kml) library(kml3d) library(knitr) ``` ```{r} full.baseline <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/datasets/processed/All Baseline Attributes combined.xlsx", sheet = 'Sheet 1') labs <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/datasets/processed/GBTM_data/labs_labels_tvarycov.xlsx") gbtm.results.6.df <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/traj_results/multi_nofac_notcov.xlsx") ``` ```{r} egfr.labs <- labs %>% select(patients_id, starts_with('EGFR_')) egfr.labs.df <- data.frame(egfr.labs) egfr.cld <- clusterLongData(egfr.labs.df, varNames='EGFR', maxNA=9) exp1 <- kml(egfr.cld, nbClusters = 5, 10, toPlot='criterion') ``` ```{r} egfr.cld.2 <- clusterLongData(egfr.labs.df, varNames='EGFR', maxNA=9) option1 <- parALGO(saveFreq=10, imputationMethod = "copyMean") kml(egfr.cld.2, nbClusters = 5, 10, toPlot='both', parAlgo = option1) ``` # KmL3d ```{r} six.labs <- labs %>% select(patients_id, starts_with('EGFR_'), starts_with('HGB_'), starts_with('N_A_'), starts_with('K_'), starts_with('PLATELETS_'), starts_with('WBC_')) # six.labs[,12:21] six.labs.df <- data.frame(six.labs) labs.cld <- clusterLongData3d(traj=six.labs.df, timeInData=list(WBC=52:61, EGFR=2:11, HGB=12:21, N_A=22:31, K=32:41, Platelets=42:51), maxNA = 20, time=1:10, varNames = c("WBC", "EGFR", "HGB", "NA", "K", "Platelets")) option1 <- parKml3d(saveFreq=10, imputationMethod = "copyMean") kml3d(labs.cld, nbClusters = 5, 60, toPlot='none', parAlgo = option1) cluster.5 <- labs.cld['c5'][[2]]['clusters'] ``` Change CluterLongData to LongData class ```{r} labs.ld <- longData3d(traj=six.labs.df, timeInData=list(WBC=52:61, EGFR=2:11, HGB=12:21, N_A=22:31, K=32:41, Platelets=42:51), maxNA = 20, time=1:10, varNames = c("WBC", "EGFR", "HGB", "NA", "K", "Platelets")) part <- partition(cluster.5) lab <- 'Platelets' plotTrajMeans(longDataFrom3d(labs.ld, variable=lab), part, xlab='Time', ylab=lab, parTraj=parTRAJ(type="n"), ylim=c(150, 300)) # plotTrajMeans(longDataFrom3d(labs.ld,variable="Platelets"), part, xlab='Time', ylab='Platelets', parMean=parMEAN(type='l'), parTraj=parTRAJ(col ="clusters"), ylim=c(120, 300)) ``` ```{r} kmeans.df <- data.frame(id=labs.cld@idFewNA, group=cluster.5) write_xlsx(kmeans.df,"/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 25/multi_kml3d_groups.xlsx") ``` # Cluter membership overlaps ## 6 labs - kMmeans There 6 ids have more than 30 missing values: ```{r} id.diff <- setdiff(labs.cld@idAll, labs.cld@idFewNA) gbtm.results.6.df <- gbtm.results.6.df[!(gbtm.results.6.df$patients_id %in% id.diff),] ``` ```{r} gbtm.results.6 <- gbtm.results.6.df$`_traj_Group` gbtm.results.6[gbtm.results.6==1] <- 'D' gbtm.results.6[gbtm.results.6==2] <- 'E' gbtm.results.6[gbtm.results.6==3] <- 'C' gbtm.results.6[gbtm.results.6==4] <- 'A' gbtm.results.6[gbtm.results.6==5] <- 'B' ``` ```{r} gbtm.results.6 <- gbtm.results.6.df$`_traj_Group` gbtm.results.6[gbtm.results.6==1] <- 'D' gbtm.results.6[gbtm.results.6==2] <- 'E' gbtm.results.6[gbtm.results.6==3] <- 'B' gbtm.results.6[gbtm.results.6==4] <- 'A' gbtm.results.6[gbtm.results.6==5] <- 'C' ``` ```{r} traj.compare.df <- data.frame(id=gbtm.results.6.df$patients_id, kmeans=cluster.5, gbtm=gbtm.results.6) dim(traj.compare.df[which((traj.compare.df$kmeans=='C') &(traj.compare.df$gbtm=='C')),]) ``` <file_sep>--- title: "R Notebook" output: html_notebook --- # library ```{r global_options, include=FALSE} knitr::opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE) library(tidyverse) library(knitr) library(data.table) #for transpose() function library(reshape2) library(openxlsx) # library(Hmisc) ``` ```{r} multitraj.track <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/traj_results/multi_no_tcov.xlsx") egfr.track <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/traj_results/egfr_single.xlsx") ``` ```{r} traj.gr.track <- egfr.track %>% select(`patients_id`, starts_with("_traj_Group")) traj.gr.track ``` # Group 1 patients ```{r} gr1.conv <- c() gr2.conv <- c() gr3.conv <- c() gr4.conv <- c() gr5.conv <- c() ``` ```{r} gr = 5 traj.track.gr <- traj.gr.track[which(traj.gr.track$`_traj_Group`==gr),] gr.conv <- c() ``` ```{r} temp <- traj.track.gr temp <- temp[which((temp$`_traj_Group_T1`==gr)&(temp$`_traj_Group_T2`==gr)&(temp$`_traj_Group_T3`==gr)& (temp$`_traj_Group_T4`==gr)&(temp$`_traj_Group_T5`==gr)&(temp$`_traj_Group_T6`==gr)& (temp$`_traj_Group_T7`==gr)&(temp$`_traj_Group_T8`==gr)&(temp$`_traj_Group_T9`==gr)),] gr.conv <- c(gr.conv, dim(temp)[1]/dim(traj.track.gr)[1]) temp <- traj.track.gr temp <- temp[which((temp$`_traj_Group_T2`==gr)&(temp$`_traj_Group_T3`==gr)& (temp$`_traj_Group_T4`==gr)&(temp$`_traj_Group_T5`==gr)&(temp$`_traj_Group_T6`==gr)& (temp$`_traj_Group_T7`==gr)&(temp$`_traj_Group_T8`==gr)&(temp$`_traj_Group_T9`==gr)),] gr.conv <- c(gr.conv, dim(temp)[1]/dim(traj.track.gr)[1]) temp <- traj.track.gr temp <- temp[which((temp$`_traj_Group_T3`==gr)& (temp$`_traj_Group_T4`==gr)&(temp$`_traj_Group_T5`==gr)&(temp$`_traj_Group_T6`==gr)& (temp$`_traj_Group_T7`==gr)&(temp$`_traj_Group_T8`==gr)&(temp$`_traj_Group_T9`==gr)),] gr.conv <- c(gr.conv, dim(temp)[1]/dim(traj.track.gr)[1]) temp <- traj.track.gr temp <- temp[which((temp$`_traj_Group_T4`==gr)&(temp$`_traj_Group_T5`==gr)&(temp$`_traj_Group_T6`==gr)& (temp$`_traj_Group_T7`==gr)&(temp$`_traj_Group_T8`==gr)&(temp$`_traj_Group_T9`==gr)),] gr.conv <- c(gr.conv, dim(temp)[1]/dim(traj.track.gr)[1]) temp <- traj.track.gr temp <- temp[which((temp$`_traj_Group_T5`==gr)&(temp$`_traj_Group_T6`==gr)& (temp$`_traj_Group_T7`==gr)&(temp$`_traj_Group_T8`==gr)&(temp$`_traj_Group_T9`==gr)),] gr.conv <- c(gr.conv, dim(temp)[1]/dim(traj.track.gr)[1]) temp <- traj.track.gr temp <- temp[which((temp$`_traj_Group_T6`==gr)& (temp$`_traj_Group_T7`==gr)&(temp$`_traj_Group_T8`==gr)&(temp$`_traj_Group_T9`==gr)),] gr.conv <- c(gr.conv, dim(temp)[1]/dim(traj.track.gr)[1]) temp <- traj.track.gr temp <- temp[which((temp$`_traj_Group_T7`==gr)&(temp$`_traj_Group_T8`==gr)&(temp$`_traj_Group_T9`==gr)),] gr.conv <- c(gr.conv, dim(temp)[1]/dim(traj.track.gr)[1]) temp <- traj.track.gr temp <- temp[which((temp$`_traj_Group_T8`==gr)&(temp$`_traj_Group_T9`==gr)),] gr.conv <- c(gr.conv, dim(temp)[1]/dim(traj.track.gr)[1]) temp <- traj.track.gr temp <- temp[which((temp$`_traj_Group_T9`==gr)),] gr.conv <- c(gr.conv, dim(temp)[1]/dim(traj.track.gr)[1]) gr.conv <- c(gr.conv, dim(traj.track.gr)[1]/dim(traj.track.gr)[1]) gr.conv ``` ```{r} gr5.conv <- gr.conv ``` ```{r} df.gr.conv <- as.data.frame(cbind(n = 1:10, gr1.conv, gr2.conv, gr3.conv, gr4.conv, gr5.conv)) df.gr.conv ``` ```{r} ggplot(df.gr.conv, aes(x=n)) + geom_line(aes(y = gr1.conv, color = "G1")) + geom_line(aes(y = gr2.conv, color="G2")) + geom_line(aes(y = gr3.conv, color="G3")) + geom_line(aes(y = gr4.conv, color="G4")) + geom_line(aes(y = gr5.conv, color="G5")) + scale_color_discrete(name = "Groups", labels = c("G1", "G2", "G3", "G4", "G5")) + scale_x_continuous(10) + ylab("% of patients converged to the final group assignment") ggsave("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 20/egfr traj convergence plot.png", width = 7, height = 4) ``` <file_sep>--- title: "R Notebook" output: html_notebook --- ```{r global_options, include=FALSE} knitr::opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE) library(tidyverse) ``` # Import data ```{r} # static.features <- read_excel("~/Desktop/datasets/processed/Static Characteristics.xlsx", sheet = 'static') # baseline.df <- read_excel('~/Desktop/datasets/processed/Filtered Baseline imputed.xlsx', sheet = 'Sheet 1') # admission.df <- read_excel("/Users/jinchenxie/Desktop/datasets/processed/Filtered Attributes Admission v2.xlsx", sheet = 'Sheet 1') full.baseline <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/datasets/processed/All Baseline Attributes combined.xlsx", sheet = 'Sheet 1') ``` **patient 9597 has POST_VAD ==1 in baseline. We modified admission to match baseline record.** ```{r} # admission.df[which((admission.df$rID == 9597)&(admission.df$last_adm==1)),]$POST_VAD <- 1 # write.xlsx(admission.df, "/Users/jinchenxie/Desktop/datasets/processed/Filtered Attributes Admission v2.xlsx", col.names = TRUE, row.names = FALSE) ``` # Generate attributes based on procedures ever ```{r} # procedure.ever <- admission.df %>% select(-ends_with("_DAYS")) %>% select(rID, CABG:STVR, ends_with("FLAG"), PCI:CRT_IMPLANT) # procedure.ever <- procedure.ever %>% group_by(rID) %>% summarise_each(list(ever = max)) ``` # Save the FULL cohort ALL attributes baseline ```{r} # static.features <- static.features %>% select(-FEMALE, -starts_with("HX_"), -ends_with("_HST"), -starts_with("CCI_"), -ends_with("_CARDIOMYOPATHY")) # names(static.features)[names(static.features) == "AGE_ADMISSION"] <- "Normalized_Age" # full.baseline <- cbind(baseline.df, static.features[,-c(1)], procedure.ever[,-c(1)]) # write.xlsx(full.baseline, '~/Desktop/datasets/processed/All Baseline Attributes combined.xlsx', col.names = TRUE, row.names = FALSE) ``` # Profiling traj groups ## identify patients in each traj group ```{r} # df <- readxl::read_excel("~/Desktop/trial save.xlsx", sheet="Sheet1") df <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/egfr_single.xlsx") rid <- df$patients_id baseline.sub <- full.baseline[which(full.baseline$rID %in% rid),] groups <- sort(unique(df$`_traj_Group`)) pat.membership <- vector(mode="list", length = length(groups)) for (group in groups){ pat.membership[[group]] <- df$patients_id[which(df$`_traj_Group`==group)] } ``` ## Prepare the attributes dataframe ```{r} # select features attris.df <- baseline.sub %>% select("rID", "AGE_ADMISSION", "FEMALE", "RACE_White", starts_with("TOBACCO_"), starts_with("INSUR_"), starts_with("BP_"), "PULSE", "BMI", "RV_FUNC", "AR", "MR","PR", "TR", ends_with("_HST"), starts_with("HX_"), starts_with("PRIOR_"), "CCI_TOTAL_SCORE", starts_with("CCI_"), starts_with("POST_"), ends_with("_CARDIOMYOPATHY"), ends_with("_00"), "CTB", ends_with("_CTB"), total_adms, Corrected_Followup_Days) attris.df$TOBACCO_STATUS_LABEL <- NULL # we don't want the altered CCI_TOTAL_SCORE from static dataframe numeric.list <- c("n","%n","AGE_ADMISSION", "std(AGE)", "CCI_TOTAL_SCORE", "std(CCI_SCORE)", "BP_SYSTOLIC", "std(BP_SYSTOLIC)", "BP_DIASTOLIC", "std(BP_DIASTOLIC)", "PULSE", "std(PULSE)","BMI", "std(BMI)", "RV_FUNC", "std(RV_FUNC)", "AR", "std(AR)", "MR", "std(MR)", "PR", "std(PR)", "TR", "std(TR)","total_adms", "std(total_adms)", "Corrected_Followup_Days", "std(Corrected_Followup_Days)") nu.list <- c("AGE_ADMISSION", "CCI_TOTAL_SCORE", "BP_SYSTOLIC", "BP_DIASTOLIC", "PULSE", "BMI", "RV_FUNC", "AR", "MR","PR", "TR", "total_adms", "Corrected_Followup_Days") binary.list <- colnames(attris.df)[-1] binary.list <- binary.list[!binary.list %in% nu.list] attributes.list <- c(numeric.list, binary.list) list.attris <- c(nu.list, binary.list) ``` ```{r} profile.df <- data.frame(row.names = groups) for (group in groups){ k <- 1 profile.df[group, 1] <- length(pat.membership[[group]]) profile.df[group, 2] <- length(pat.membership[[group]])/dim(df)[1] k <- k+2 for (val in nu.list){ profile.df[group, k] <- mean(attris.df[[val]][which(attris.df$rID %in% pat.membership[[group]])], na.rm = TRUE) profile.df[group, k+1] <- sd(attris.df[[val]][which(attris.df$rID %in% pat.membership[[group]])], na.rm = TRUE) k <- k+2 } k <- 29 for (attri in binary.list){ # print(attri) profile.df[group, k] <- sum(attris.df[[attri]][which(attris.df$rID %in% pat.membership[[group]])], na.rm = TRUE)/length(pat.membership[[group]]) k <- k+1 } } names(profile.df) <- attributes.list profile.df <- cbind(groups, profile.df) rm(k, val) ``` # select significant attris only ```{r} sub.profile.df <- profile.df %>% select(groups, n, `%n`, all_of(sig.list)) ``` # save dataset ```{r} write.xlsx(sub.profile.df, '~/Desktop/traj profile.xlsx', col.names = TRUE, row.names = FALSE) # write.xlsx(update.baseline.df, '~/Desktop/datasets/processed/Filtered Attributes Baseline.xlsx', col.names = TRUE, row.names = FALSE) ``` <file_sep>import torch from torch.utils.data import Dataset, DataLoader, TensorDataset import torch.nn as nn import torch.nn.functional as F X_train = pd.DataFrame(X_train) X_test = pd.DataFrame(X_test) y_train = pd.DataFrame(y_train) y_test = pd.DataFrame(y_test) # Prepare the data for torch nn train_x = torch.tensor(X_train.values.astype(np.float32)) train_y = torch.tensor(y_train.values.astype(np.int_)) test_x = torch.tensor(X_test.values.astype(np.float32)) test_y = torch.tensor(y_test.values.astype(np.int_)) train_data = TensorDataset(train_x, train_y) train_loader = DataLoader(dataset=train_data, batch_size=36, shuffle=True) validation_data = TensorDataset(test_x, test_y) validation_loader = DataLoader(dataset=validation_data, batch_size=15, shuffle=True) class SimpleNN(nn.Module): def __init__(self): super(SimpleNN, self).__init__() # declaring some parameters self.inputSize = 156 self.outputSize = 2 self.hidden1Size = 500 # self.hidden2Size = 200 # self.hidden3Size = 20 # layers of linear transformation self.hidden1 = nn.Linear(self.inputSize, self.hidden1Size) # self.hidden2 = nn.Linear(self.hidden1Size, self.hidden2Size) # self.hidden3 = nn.Linear(self.hidden2Size, self.hidden3Size) self.output = nn.Linear(self.hidden1Size, self.outputSize) # # sigmoid activation and softmax output # self.sigmoid = nn.Sigmoid() # self.softmax = nn.Softmax(dim=1) def forward(self, x): x = torch.sigmoid(self.hidden1(x)) # x = torch.sigmoid(self.hidden2(x)) # x = torch.sigmoid(self.hidden3(x)) y = F.softmax(self.output(x), dim=1) return y model = SimpleNN() optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.5) criterion = nn.CrossEntropyLoss() def train(epoch, log_interval=20): # set model to training mode model.train() # loop over batch from the training set for batch_idx, (data, target) in enumerate(train_loader): # Zero gradient buffers optimizer.zero_grad() # pass data through the network output = model(data) # calculate loss loss = criterion(output, target) # Backpropagate loss.backward() # Update Weights optimizer.step() print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.data.item())) return def validate(loss_vector, accuracy_vector): model.eval() val_loss, correct = 0, 0 for data, target in validation_loader: output = model(data) val_loss += criterion(output, target).data.item() pred = output.data.max(1)[1] correct += pred.eq(target.data).sum() val_loss /= len(validation_loader) loss_vector.append(val_loss) accuracy = 100. * correct.to(torch.float32) / len(validation_loader.dataset) accuracy_vector.append(accuracy) print('\nValidation set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format( val_loss, correct, len(validation_loader.dataset), accuracy)) num_epochs = 50 lossv, accv = [], [] for epoch in range(1, num_epochs + 1): train(epoch) validate(lossv, accv) <file_sep>--- title: "R Notebook" output: html_notebook --- ```{r global_options, include=FALSE} knitr::opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE) library(tidyverse) library(knitr) library(data.table) #for transpose() function library(reshape2) library(openxlsx) # library(Hmisc) cbPalette <- c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") ``` # Import Data ```{r} # multitraj.results <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/traj_results/multi_no_tcov.xlsx") egfr.results <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/traj_results/egfr_single.xlsx") group.results <- egfr.results %>% select(patients_id, starts_with("_traj_Group")) names(group.results)[names(group.results) == "_traj_Group"] <- "_traj_Group_T10" group.results <- group.results %>% select(-"_traj_Group_T10", "_traj_Group_T10") ``` ```{r} traj.members <- group.results %>% group_by(`_traj_Group_T1`) %>% tally() i <- 2 for (val in names(group.results)[c(3:length(names(group.results)))]){ temp <- group.results %>% group_by(.dots=as.name(val)) %>% tally() names(temp) <- c(paste('_traj_Group',i, sep='_'), paste('n',i,sep='')) traj.members <- cbind(traj.members, temp) i <- i+1 } traj.members <- traj.members %>% select(starts_with("n")) traj.members.t <- as.data.frame(t(traj.members)) ggplot(data = traj.members.t, aes(x=seq(1,10,1))) + geom_line(aes(y=V1, colour='Group1')) + geom_line(aes(y=V2, colour='Group2')) + geom_line(aes(y=V3, colour="Group3")) + geom_line(aes(y=V4, colour="Group4")) + geom_line(aes(y=V5, colour="Group5")) + scale_y_continuous(name ="Number of patients in each traj group") + scale_x_continuous(name = "Admission Number", breaks=seq(1, 10, 1)) ggsave("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 20/egfr traj membership plot.png", width = 7, height = 4) ``` How many <file_sep>--- title: "R Notebook" output: html_notebook --- ```{r global_options, include=FALSE} knitr::opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE) library(tidyverse) library(knitr) library(data.table) library(Hmisc) library(arsenal) library(survival) library(survminer) library(writexl) ``` # import data ```{r} baseline.profile.df <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/datasets/processed/All Baseline Attributes combined.xlsx", sheet = 'Sheet 1') # baseline.df <- read_excel('~/Desktop/datasets/processed/GBTM_data/Filtered Baseline imputed.xlsx', sheet = 'Sheet 1') admission_30NA <- readxl::read_excel("~/Desktop/HF_Research/datasets/processed/Filtered Attributes Admission v2.xlsx", sheet = 'Sheet 1') # static.features <- read_excel("~/Desktop/datasets/processed/Static Characteristics.xlsx", sheet = 'static') ``` # Profiling ```{r} attris.df <- baseline.profile.df %>% select("rID", "AGE_ADMISSION", "FEMALE", "RACE_White", starts_with("TOBACCO_"), starts_with("INSUR_"), starts_with("BP_"), "PULSE", "BMI", ends_with("_HST"), starts_with("HX_"), starts_with("PRIOR_"), "CCI_TOTAL_SCORE", starts_with("CCI_"), starts_with("POST_"), ends_with("_CARDIOMYOPATHY"), ends_with("_00"), "CTB", ends_with("_CTB"), total_adms, Corrected_Followup_Days) attris.df$TOBACCO_STATUS_LABEL <- NULL nu.list <- c("AGE_ADMISSION", "CCI_TOTAL_SCORE", "BP_SYSTOLIC", "BP_DIASTOLIC", "PULSE", "BMI", "total_adms", "Corrected_Followup_Days") binary.list <- colnames(attris.df)[-1] binary.list <- binary.list[!binary.list %in% nu.list] list.attris <- c(nu.list, binary.list) ``` ## groups profiling ```{r} df <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/traj_results/multi_nofac_notcov.xlsx") baseline.sub <- baseline.profile.df[which(baseline.profile.df$rID %in% df$patients_id),] temp.1 <- baseline.sub %>% select(nu.list) temp.2 <- baseline.sub %>% select(binary.list) # converting all columns into categorical variables temp.2[,names(temp.2)] <- lapply(temp.2[,names(temp.2)], factor) temp <- cbind(temp.1, temp.2) temp <- cbind(temp, df$`_traj_Group`) names(temp)[names(temp) == "df$`_traj_Group`"] <- "Group" mycontrols <- tableby.control(test=TRUE, cat.test="chisq") table.1 <- tableby(Group ~ ., data = temp, control = mycontrols) summary(table.1) temp.tab <- as.data.frame(summary(table.1)) temp.tab <- temp.tab[-which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;Range"),] temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;Mean (SD)"), 1] <- "Mean (SD)" temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;0"), 1] <- "0" temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;1"), 1] <- "1" View(temp.tab) # tests(table.1) rm(temp.1, temp.2) temp.tab.filtered <- temp.tab[which((temp.tab$`p value` <= 0.05)|(temp.tab$`p value`=="< 0.001")),] View(temp.tab.filtered) ``` ```{r} write_xlsx(temp.tab.filtered,"/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/multi_nofac_alltcov_chara.xlsx") ``` ```{r eval=FALSE} df <- readxl::read_excel("~/Desktop/trial save.xlsx", sheet="Sheet1") baseline.sub <- baseline.profile.df[which(baseline.profile.df$rID %in% df$patients_id),] baseline.data <- cbind(baseline.sub, df$`_traj_Group`) names(baseline.data)[names(baseline.data) == "df$`_traj_Group`"] <- "Group" # baseline.data[binary.list] <- lapply(baseline.data[binary.list], as.factor) # baseline.data[nu.list] <- sapply(baseline.data[nu.list], as.numeric) temp <- baseline.data %>% select(Group, list.attris) # temp <- temp[which(temp$Group %in% c(1, 3)),] mycontrols <- tableby.control(test=TRUE, cat.test="chisq") table.1 <- tableby(Group ~ ., data = temp) summary(table.1) temp.tab <- as.data.frame(summary(table.1)) # rename first column temp.tab <- temp.tab[-which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;Range"),] # temp.tab <- temp.tab[-which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;N-Miss"),] temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;Mean (SD)"), 1] <- "Mean (SD)" # temp.tab <- temp.tab[-which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;Mean (SD)"),] # write_xlsx(temp.tab,"~/Desktop/temp.xlsx") temp.tab.filtered <- temp.tab[which((temp.tab$`p value` <= 0.05)|(temp.tab$`p value`=="< 0.001")),] # temp.tab.filtered <- temp.tab.filtered[-which(as.character(temp.tab.filtered$`p value`)==" NaN"),] View(temp.tab.filtered) # temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;Mean (SD)"), 1] <- "Mean (SD)" # write_xlsx(temp.tab.filtered,"~/Desktop/temp.xlsx") # tests(table.1) ``` ```{r extract_sig_attris function} extract_sig_attris <- function(p.value.tbl){ attris.list <- c() list <- p.value.tbl[,1][-which(p.value.tbl[,1]=="Mean (SD)")] for (attri in list){ attris.list <- c(attris.list, substr(attri, 3, nchar(attri)-2)) } return(attris.list) } ``` ```{r} sig.list <- extract_sig_attris(temp.tab.filtered) ``` # Kaplan Meier Curve ```{r} admission.sub <- admission_30NA[which(admission_30NA$rID %in% baseline.sub$rID),] %>% select(rID, AGE_ADMISSION) kapm.df <- baseline.sub %>% select(rID, Corrected_Followup_Days, CTB, POST_VAD, POST_TRANSPLANT) # add the univariate EGFR group info # kapm.df <- cbind(kapm.df, ctb.gr.df$group_egfr) # names(kapm.df)[names(kapm.df) == "ctb.gr.df$group_egfr"] <- "group_egfr" # add the univariate Sodium group info kapm.df <- cbind(kapm.df, df$`_traj_Group`) names(kapm.df)[names(kapm.df) == "df$`_traj_Group`"] <- "group_multivar" ``` ```{r} surv_object <- Surv(time = kapm.df$Corrected_Followup_Days, event = kapm.df$CTB) # fit1 <- survfit(surv_object ~ POST_VAD, data = kapm.df) # fit2 <- survfit(surv_object ~ group_egfr, data = kapm.df) fit3 <- survfit(surv_object ~ group_multivar, data = kapm.df) ``` ```{r} # survminer::ggsurvplot(fit1, data = kapm.df, pva1 = TRUE, xlab = "Follow up days") # survminer::ggsurvplot(fit2, data = kapm.df, pva1 = TRUE, xlab = "Follow up days") survminer::ggsurvplot(fit3, data = kapm.df, pva1 = TRUE, xlab = "Follow up days") ggsave("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/multi_traj KM plot2.png", width = 7, height = 5) ``` ```{r} temp.baseline <- cbind(baseline.sub[which(baseline.sub$rID %in% ids),], INTER = group.1.inter$POST_INTER) kapm.df <- temp.baseline %>% select(rID, Corrected_Followup_Days, CTB, INTER) surv_object <- Surv(time = kapm.df$Corrected_Followup_Days, event = kapm.df$CTB) fit <- survfit(surv_object ~ INTER, data = kapm.df) survminer::ggsurvplot(fit, data = kapm.df, pva1 = TRUE, xlab = "Follow up days") ggsave("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 20/inter KM plot5.png", width = 7, height = 5) ``` # CTB Profiling** ```{r} df <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/egfr_single.xlsx") baseline.sub <- baseline.profile.df[which(baseline.profile.df$rID %in% df$patients_id),] baseline.data <- cbind(baseline.sub, df$`_traj_Group`) temp.1 <- baseline.data %>% select(nu.list) temp.2 <- baseline.data %>% select(binary.list) # converting all columns into categorical variables temp.2[,names(temp.2)] <- lapply(temp.2[,names(temp.2)], factor) temp <- cbind(temp.1, temp.2) mycontrols <- tableby.control(test=TRUE, cat.test="chisq") table.1 <- tableby(CTB ~ ., data = temp, control = mycontrols) summary(table.1) temp.tab <- as.data.frame(summary(table.1)) temp.tab <- temp.tab[-which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;Range"),] temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;Mean (SD)"), 1] <- "Mean (SD)" temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;0"), 1] <- "0" temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;1"), 1] <- "1" tests(table.1) rm(temp.1, temp.2) ``` ```{r} write_xlsx(temp.tab,"/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/egfr_single_chara.xlsx") ``` ## 30-day CTB profilng ```{r} temp.1 <- baseline.data %>% select(nu.list) temp.2 <- baseline.data %>% select(binary.list) # converting all columns into categorical variables temp.2[,names(temp.2)] <- lapply(temp.2[,names(temp.2)] , factor) temp <- cbind(temp.1, temp.2) mycontrols <- tableby.control(test=TRUE, cat.test="chisq") table.1 <- tableby(`30_day_CTB`~., data = temp, control = mycontrols) # summary(table.1) tests(table.1) temp.tab <- as.data.frame(summary(table.1)) temp.tab <- temp.tab[-which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;Range"),] temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;Mean (SD)"), 1] <- "Mean (SD)" temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;0"), 1] <- "0" temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;1"), 1] <- "1" rm(temp.1, temp.2) ``` ```{r} write_xlsx(temp.tab,"~/Desktop/temp.xlsx") ``` ```{r} dim(admission.df) dim(admission.sub) admission.df %>% group_by(admission_count) %>% count() temp1 <- admission.sub %>% group_by(admission_count) %>% count() write_xlsx(temp1,"~/Desktop/temp.xlsx") ``` # Post Procedure Timing ```{r} df <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/Weekly Progress/week 18/traj_results/multi_no_tcov.xlsx") %>% select(patients_id, `_traj_Group`) admission_30NA <- readxl::read_excel("~/Desktop/HF_research/datasets/processed/Filtered Attributes Admission v2.xlsx", sheet = 'Sheet 1') admission.relevant <- admission_30NA %>% select(rID, POST_TRANSPLANT, POST_VAD, admission_count, READMISSION_DAYS) groups <- sort(unique(df$`_traj_Group`)) pat.membership <- vector(mode="list", length = length(groups)) for (group in groups){ pat.membership[[group]] <- df$patients_id[which(df$`_traj_Group`==group)] } admission.relevant[is.na(admission.relevant$READMISSION_DAYS),]$READMISSION_DAYS <- 0 ``` **We only count the admission of each patient's first VAD and heart transplant. ** ```{r proc_adm_ave functions} proc_adm_ave <- function(procedure, group.membership, admission.relevant){ group.adm.mean <- c() group.adm.std <- c() for (group in groups){ adm.count.list <- c() temp_pats <- admission.relevant[which((admission.relevant$rID %in% group.membership[[group]]) & (admission.relevant[procedure] == 1)),] for (id in unique(temp_pats$rID)){ temp.pat <- temp_pats[which(temp_pats$rID == id),] adm.count.list <- c(adm.count.list, as.numeric(temp.pat[1, "admission_count"])) } cat("n: ", length(adm.count.list), "\n") group.adm.mean <- c(group.adm.mean, mean(adm.count.list)) group.adm.std <- c(group.adm.std, sd(adm.count.list)) } print("means:") print(group.adm.mean) print("sd:") print(group.adm.std) return } proc_days_ave <- function(procedure, group.membership, admission.relevant){ group.adm.mean <- c() group.adm.std <- c() for (group in groups){ adm.count.list <- c() temp_pats <- admission.relevant[which((admission.relevant$rID %in% group.membership[[group]]) & (admission.relevant[procedure] == 1)),] for (id in unique(temp_pats$rID)){ temp.pat <- temp_pats[which(temp_pats$rID == id),] adm.count.list <- c(adm.count.list, as.numeric(temp.pat[1, "READMISSION_DAYS"])) } cat("n: ", length(adm.count.list), "\n") group.adm.mean <- c(group.adm.mean, mean(adm.count.list)) group.adm.std <- c(group.adm.std, sd(adm.count.list)) } print("means:") print(group.adm.mean) print("sd:") print(group.adm.std) return } proc_ctb_adm_ave <- function(procedure, group.membership, admission.relevant, baseline.profile.df, CTB_state){ group.adm.mean <- c() group.adm.std <- c() for (group in groups){ adm.count.list <- c() ctb.satisfied <- baseline.profile.df[which(baseline.profile.df$CTB == CTB_state),]$rID temp_pats <- admission.relevant[which((admission.relevant$rID %in% group.membership[[group]]) & (admission.relevant[procedure] == 1) & (admission.relevant$rID %in% ctb.satisfied)),] for (id in unique(temp_pats$rID)){ temp.pat <- temp_pats[which(temp_pats$rID == id),] adm.count.list <- c(adm.count.list, as.numeric(temp.pat[1, "admission_count"])) } cat("n: ", length(adm.count.list), "\n") group.adm.mean <- c(group.adm.mean, mean(adm.count.list)) group.adm.std <- c(group.adm.std, sd(adm.count.list)) } return(group.adm.mean) } ``` ```{r} # proc_adm_ave("POST_VAD", pat.membership, admission.relevant) # proc_adm_ave("POST_TRANSPLANT", pat.membership, admission.relevant) # proc_ctb_adm_ave("POST_VAD", pat.membership, admission.relevant, baseline.profile.df, 1) # proc_ctb_adm_ave("POST_VAD", pat.membership, admission.relevant, baseline.profile.df, 0) proc_days_ave("POST_VAD", pat.membership, admission.relevant) proc_days_ave("POST_TRANSPLANT", pat.membership, admission.relevant) ``` # Time span of the admissions we modeled ```{r} admission_trunc <- admission_30NA[which((admission_30NA$admission_count <= 10)&(admission_30NA$rID %in% df$patients_id)),] summary(admission_trunc$READMISSION_DAYS) ``` # Data Availability ```{r} input <- readxl::read_excel("/Users/jinchenxie/Desktop/HF_Research/datasets/processed/GBTM_data/labs_labels_tvarycov.xlsx") sapply(input, function(x) (1-sum(is.na(x))/1653)*100) ``` # K-Means group profiling ```{r} df <- traj.compare.df baseline.sub <- baseline.profile.df[which(baseline.profile.df$rID %in% df$id),] temp.1 <- baseline.sub %>% select(nu.list) temp.2 <- baseline.sub %>% select(binary.list) # converting all columns into categorical variables temp.2[,names(temp.2)] <- lapply(temp.2[,names(temp.2)], factor) temp <- cbind(temp.1, temp.2) temp <- cbind(temp, df$`kmeans`) names(temp)[names(temp) == "df$kmeans"] <- "Group" mycontrols <- tableby.control(test=TRUE, cat.test="chisq") table.1 <- tableby(Group ~ ., data = temp, control = mycontrols) summary(table.1) temp.tab <- as.data.frame(summary(table.1)) temp.tab <- temp.tab[-which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;Range"),] temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;Mean (SD)"), 1] <- "Mean (SD)" temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;0"), 1] <- "0" temp.tab[which(temp.tab[,1]=="&nbsp;&nbsp;&nbsp;1"), 1] <- "1" View(temp.tab) # tests(table.1) rm(temp.1, temp.2) temp.tab.filtered <- temp.tab[which((temp.tab$`p value` <= 0.05)|(temp.tab$`p value`=="< 0.001")),] View(temp.tab.filtered) ``` <file_sep>--- title: "R Notebook" output: html_notebook --- ```{r global_options, include=FALSE} knitr::opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE) library(readxl) library(openxlsx) library(mice) ``` ```{r} df <- read_excel('~/Desktop/datasets/processed/Filtered Attributes Baseline.xlsx', sheet="NA30_filtered_baseline") ``` ```{r} df.sub <- df %>% select(c("AGE_ADMISSION", "FEMALE","BMI", "PULSE", "BP_DIASTOLIC", "BP_SYSTOLIC"), ends_with("_HST"), starts_with("CCI_"), ends_with("_00")) md.pattern(df.sub) df.update <- df %>% select(-c("BMI", "PULSE", "BP_DIASTOLIC", "BP_SYSTOLIC")) # summary(df.sub) ``` ```{r} tempData <- mice(df.sub, m=5, method = "pmm") tempData$imp$BMI completedData <- complete(tempData, 1) imp.list <- c("BMI", "PULSE", "BP_DIASTOLIC", "BP_SYSTOLIC") for (val in imp.list){ completedData.sub <- cbind(complete(tempData, 1)[val], complete(tempData, 2)[val], complete(tempData, 3)[val], complete(tempData, 4)[val], complete(tempData,5)[val]) completedData.sub$mean <- rowMeans(completedData.sub) completedData[val] <- completedData.sub$mean } completedData <- select(completedData, imp.list) df.update <- cbind(df.update, completedData) ``` ```{r} # xyplot(data=tempData, BMI~PULSE+BP_DIASTOLIC+BP_SYSTOLIC, pch=18, cex=1) densityplot(tempData) ``` ```{r} write.xlsx(df.update, '~/Desktop/datasets/processed/GBTM_data/Filtered Baseline imputed.xlsx', col.names = TRUE, row.names = FALSE) ```
0fd46a453399a353c4012c31f9adfcabf9711e6a
[ "Markdown", "Python", "R", "RMarkdown" ]
17
RMarkdown
xjcjessie/HF_project_code
34676419090ad42c3486eccc08075e8337815a3a
300cc446452ec96c01327281c9b422b20afea37b
refs/heads/main
<repo_name>TanGuangZhi/jqueryDemo-2048<file_sep>/js/animation.js function showNumWithAnimation(randomPosition, randomNum) { let numCell = $('#num-cell-' + randomPosition["x"] + '-' + randomPosition["y"]) numCell.text(randomNum) numCell.css('background-color', getBgColor(randomNum)) numCell.css("color", getNumberColor(randomNum)) numCell.animate({ winth: '100px', height: '100px', top: getPosition(randomPosition["x"], randomPosition["y"].top), left: getPosition(randomPosition["x"], randomPosition["y"].left) }, 500) }<file_sep>/js/test.js /* 在随机单元格生成一个随机数 1. 随机产生一个2或4 2. 在空余的空间随机找一个 */ function generateOneRandomNum(nums) { // 随机找一个位置 let temp = [] let count = 0 for (let i = 0; i < 4; i++) { for (let j = 0; j < 4; j++) { if (nums[i][j] == 0) { temp[count] = i * 4 + j count++ } } } let randomPosition = {} let pos = Math.floor(Math.random(0, count)) randomPosition["x"] = Math.floor(temp[pos] / 4) randomPosition["y"] = temp[pos] % 4 // 随机生成一个数字 let randomNum = Math.random()<0.5?2:4 } let nums = [] generateOneRandomNum()
1dd549d53ba1adfb600c72eaa3d5349b905d5119
[ "JavaScript" ]
2
JavaScript
TanGuangZhi/jqueryDemo-2048
2b0825f44b18307da4edaa6eeb3a0c3b3c906a06
5e919058abcbf9b924740210b4ddc292963df76b
refs/heads/master
<file_sep>#!/bin/bash # # twist rake 1.0 # <EMAIL> # <EMAIL> #hilfe if [ -z $1 ]; then SHOWHELP="1"; fi if [ "$1" == "--help" ]; then SHOWHELP="1"; fi if [ "$1" == "-h" ]; then SHOWHELP="1"; fi if [ "$SHOWHELP" == "1" ] then echo "take 1.0 usage:" echo "$0 { [ f | i | l | u | p] | [ pfad/zum/test ] | [ pfad/zum/test test_x ] }" exit fi #testlisting if [ "$1" == "--list" ] then if [ -f "$2" ] then grep "def test_" $2 grep "test .* do" $2 exit 0 fi elif [ "$2" == "--list" ] then if [ -f "$1" ] then grep "def test_" $1 grep "test .* do" $1 exit 0 fi fi #rekursives testen if [ "$1" == "-r" ] then echo "testing recursivly..." for T in `find $2 -name "*test.rb"` do echo "testing $T" take $T done exit fi # Was fuer ne Testart? TESTKIND=$1 LINE="rake" #if the first argument is a path, we scan it for "functionals", "units" etc if [ -f "$1" ] #this means $1 is an existing path then if [ -n "`echo $1 | grep integration`" ] then TESTKIND="integration" elif [ -n "`echo $1 | grep functional`" ] then TESTKIND="functionals" elif [ -n "`echo $1 | grep unit`" ] then TESTKIND="units" elif [ -n "`echo $1 | grep lib`" ] then TESTKIND="libs" elif [ -n "`echo $1 | grep plugins`" ] then TESTKIND="plugins" fi LINE="rake test:$TESTKIND TEST=$1" if [ "$2" != "" ] then if [ "$2" == "-f" ] then echo "fuzzy" TESTS="`grep "test_.*$3.*" $1 | awk '{print $2}'`" for T in $TESTS do echo "testing $T" take $1 $T done exit else LINE=$LINE" TESTOPTS=-n$2" fi fi else #the first argument is the testkind if [ "${TESTKIND:0:1}" = "f" ];then TESTKIND=":functionals"; fi if [ "${TESTKIND:0:1}" = "i" ];then TESTKIND=":integration"; fi if [ "${TESTKIND:0:1}" = "u" ];then TESTKIND=":units"; fi if [ "${TESTKIND:0:1}" = "l" ];then TESTKIND=":libs"; fi if [ "${TESTKIND:0:1}" = "p" ];then TESTKIND=":plugins"; fi if [ "${TESTKIND:0:1}" = "a" ];then TESTKIND=""; fi LINE="rake test$TESTKIND" if [ "$2" != "" ] then FILE=$(echo "$2"|sed -e "s/^\///") LINE=$LINE" TEST=$FILE" fi if [ "$3" != "" ] then LINE=$LINE" TESTOPTS=-n$3" fi fi $LINE
5827f8aff340ba61fdf272008015013bdb5b6c43
[ "Shell" ]
1
Shell
twist/take
7e6e6b7234ad32a8b4f16b463c19c81f7d2741b0
c22b92bbc834064362b88a8356511f483a045669
refs/heads/master
<repo_name>DC-SWAT/DreamShell<file_sep>/applications/bios_flasher/modules/module.c /* DreamShell ##version## module.c - Bios flasher app module Copyright (C)2013 Yev Copyright (C)2013-2014 SWAT */ #include "ds.h" #include "drivers/bflash.h" #include <time.h> #include <stdbool.h> DEFAULT_MODULE_EXPORTS(app_bios_flasher); typedef enum OperationState { eNone = -1, eErasing = 0, eWriting, eReading, eCompare }OperationState_t; typedef enum OperationError { eSuccess = 0, eUnknownFail = -1, eDetectionFail = -2, eFileFail = -3, eErasingFail = -4, eWritingFail = -5, eReadingFail = -6, eDataMissmatch = 1 }OperationError_t; static const uint16 CHUNK_SIZE = 32 * 1024; #define UPDATE_GUI(state, progress, gui) do { if(gui) gui(state, progress); } while(0) typedef void BiosFlasher_OperationCallback(OperationState_t state, float progress); int BiosFlasher_WriteBiosFileToFlash(const char* filename, BiosFlasher_OperationCallback guiClbk); int BiosFlasher_CompareBiosWithFile(const char* filename, BiosFlasher_OperationCallback guiClbk); int BiosFlasher_ReadBiosToFile(const char* filename, BiosFlasher_OperationCallback guiClbk); void BiosFlasher_EnableMainPage(); void BiosFlasher_EnableChoseFilePage(); void BiosFlasher_EnableProgressPage(); void BiosFlasher_EnableResultPage(int result, const char* fileName); void BiosFlasher_EnableSettingsPage(); void BiosFlasher_OnOperationProgress(OperationState_t state, float progress); struct { App_t* m_App; GUI_Widget *m_LabelProgress; GUI_Widget *m_LabelProgressDesc; GUI_Widget *m_ProgressBar; GUI_Widget *filebrowser; GUI_Widget *pages; GUI_Surface *m_ItemNormal; GUI_Surface *m_ItemSelected; char* m_SelectedBiosFile; OperationState_t m_CurrentOperation; unsigned int m_ScrollPos; unsigned int m_MaxScroll; bool have_args; }self; struct { size_t m_DataStart; size_t m_DataLength; }settings; void BiosFlasher_ResetSelf() { memset(&self, 0, sizeof(self)); self.m_CurrentOperation = eNone; memset(&settings, 0, sizeof(settings)); } // BIOS bflash_dev_t* BiosFlasher_DetectFlashChip() { bflash_manufacturer_t* mfr = 0; bflash_dev_t* dev = 0; if (bflash_detect(&mfr, &dev) < 0) { dev = (bflash_dev_t*)malloc(sizeof(*dev)); memset(dev, 0, sizeof(*dev)); dev->name = strdup("Unknown"); } return dev; } int BiosFlasher_WriteBiosFileToFlash(const char* filename, BiosFlasher_OperationCallback guiClbk) { size_t i = 0; uint8* data = 0; file_t pFile = 0; UPDATE_GUI(eReading, 0.0f, guiClbk); // Detect writible flash bflash_dev_t *dev = NULL; bflash_manufacturer_t *mrf = NULL; if( bflash_detect(&mrf, &dev) < 0 || !(dev->flags & F_FLASH_PROGRAM) ) { ds_printf("DS_ERROR: flash chip detection error.\n"); return eDetectionFail; } // Read bios file from file to memory pFile = fs_open(filename, O_RDONLY); if (pFile == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open bios file: %s.\n", filename); return eFileFail; } size_t fileSize = fs_total(pFile); if(fileSize > dev->size * 1024) { ds_printf("DS_ERROR: The firmware larger than a flash chip (%d KB vs %d KB).\n", (fileSize / 1024), dev->size); fs_close(pFile); return eFileFail; } data = (uint8 *) memalign(32, fileSize); if(data == NULL) { ds_printf("DS_ERROR: Not enough memory\n"); fs_close(pFile); return eUnknownFail; } size_t readLen = fs_read(pFile, data, fileSize); if (fileSize != readLen) { ds_printf("DS_ERROR: File wasn't loaded fully to memory\n"); fs_close(pFile); return eFileFail; } fs_close(pFile); EXPT_GUARD_BEGIN; // Erasing if (dev->flags & F_FLASH_ERASE_SECTOR || dev->flags & F_FLASH_ERASE_ALL) { for (i = 0; i < dev->sec_count; ++i) { UPDATE_GUI(eErasing, (float)i / dev->sec_count, guiClbk); if (bflash_erase_sector(dev, dev->sectors[i]) < 0) { ds_printf("DS_ERROR: Can't erase flash\n"); free(data); EXPT_GUARD_RETURN eErasingFail; } } } // Writing size_t offset = 0; if (fileSize >= settings.m_DataStart + settings.m_DataLength) { offset = settings.m_DataStart; fileSize = (settings.m_DataLength > 0) ? offset + settings.m_DataLength : fileSize - offset; } size_t chunkCount = fileSize / CHUNK_SIZE; for (i = 0; i <= chunkCount; ++i) { UPDATE_GUI(eWriting, (float)i / chunkCount, guiClbk); size_t dataPos = i * CHUNK_SIZE + offset; size_t dataLen = (dataPos + CHUNK_SIZE > fileSize) ? fileSize - dataPos : CHUNK_SIZE; // ScreenWaitUpdate(); LockVideo(); int result = bflash_write_data(dev, dataPos, data + dataPos, dataLen); UnlockVideo(); if (result < 0) { ds_printf("DS_ERROR: Can't write flash\n"); free(data); EXPT_GUARD_RETURN eWritingFail; } } EXPT_GUARD_CATCH; ds_printf("DS_ERROR: Fatal error\n"); free(data); fs_close(pFile); EXPT_GUARD_RETURN eFileFail; EXPT_GUARD_END; free(data); fs_close(pFile); return 0; } int BiosFlasher_CompareBiosWithFile(const char* filename, BiosFlasher_OperationCallback guiClbk) { uint8* data = 0; file_t pFile = 0; UPDATE_GUI(eReading, 0.0f, guiClbk); // Detect writible flash bflash_dev_t *dev = NULL; bflash_manufacturer_t *mrf = NULL; if (bflash_detect(&mrf, &dev) < 0) { ds_printf("DS_ERROR: flash chip detection error.\n"); return eDetectionFail; } // Read bios file from file to memory pFile = fs_open(filename, O_RDONLY); if (pFile == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open bios file: %s.\n", filename); return eFileFail; } size_t fileSize = fs_total(pFile); if (fileSize > dev->size * 1024) { ds_printf("DS_ERROR: The firmware larger than a flash chip (%d KB vs %d KB).\n", (fileSize / 1024), dev->size); fs_close(pFile); return eDataMissmatch; } data = (uint8 *) memalign(32, CHUNK_SIZE); if(data == NULL) { ds_printf("DS_ERROR: Not enough memory\n"); fs_close(pFile); return eUnknownFail; } int ret = eSuccess; int i = 0; size_t chunkCount = fileSize / CHUNK_SIZE; size_t dataPos, dataLen, readLen; for (i = 0; i <= chunkCount; ++i) { dataPos = i * CHUNK_SIZE; dataLen = (dataPos + CHUNK_SIZE > fileSize) ? fileSize - dataPos : CHUNK_SIZE; UPDATE_GUI(eReading, (float)i / chunkCount, guiClbk); readLen = fs_read(pFile, data, dataLen); if (readLen != dataLen) { ds_printf("DS_ERROR: Part of file wasn't loaded to memory\n"); free(data); fs_close(pFile); return eFileFail; } if (memcmp(data, (uint8*)BIOS_FLASH_ADDR + dataPos, dataLen) != 0) { ret = eDataMissmatch; break; } } free(data); fs_close(pFile); return ret; } int BiosFlasher_ReadBiosToFile(const char* filename, BiosFlasher_OperationCallback guiClbk) { uint8* data = 0; file_t pFile = 0; UPDATE_GUI(eReading, 0.0f, guiClbk); // Detect writible flash bflash_dev_t *dev = NULL; bflash_manufacturer_t *mrf = NULL; if (bflash_detect(&mrf, &dev) < 0) { ds_printf("DS_ERROR: flash chip detection error.\n"); return eDetectionFail; } // Read bios from file to memory pFile = fs_open(filename, O_WRONLY | O_TRUNC | O_CREAT); if (pFile == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open bios file: %s.\n", filename); return eFileFail; } size_t fileSize = dev->size * 1024; size_t offset = 0; if (fileSize >= settings.m_DataStart + settings.m_DataLength) { offset = settings.m_DataStart; fileSize = (settings.m_DataLength > 0) ? offset + settings.m_DataLength : fileSize - offset; } data = memalign(32, fileSize); if(!data) { ds_printf("DS_ERROR: Not enough memory\n"); fs_close(pFile); return eUnknownFail; } /* * We can't use G1 bus simultaneously for IDE and BIOS, * so need copy BIOS data to RAM */ memcpy(data, (uint8*)BIOS_FLASH_ADDR, fileSize); int i = 0; size_t chunkCount = fileSize / CHUNK_SIZE; for (i = 0; i <= chunkCount; ++i) { UPDATE_GUI(eReading, (float)i / chunkCount, guiClbk); size_t dataPos = i * CHUNK_SIZE + offset; size_t dataLen = (dataPos + CHUNK_SIZE > fileSize) ? fileSize - dataPos : CHUNK_SIZE; size_t writeLen = fs_write(pFile, data + dataPos, dataLen); if (writeLen != dataLen) { ds_printf("DS_ERROR: Can't write data to file\n"); fs_close(pFile); free(data); return eFileFail; } } free(data); fs_close(pFile); return 0; } char* BiosFlasher_GenerateBackupName() { char tmp[128]; time_t t; struct tm* ti; time(&t); ti = localtime(&t); sprintf(tmp, "backup_%04d-%02d-%02d_%02d-%02d-%02d.bios", 1900 + ti->tm_year, 1 + ti->tm_mon, ti->tm_mday, ti->tm_hour, ti->tm_min, ti->tm_sec); ds_printf("Backup filename: %s\n", tmp); char* filename = strdup(tmp); return filename; } // HELPERS void* BiosFlasher_GetElement(const char *name, ListItemType type, int from) { Item_t *item; item = listGetItemByName(from ? self.m_App->elements : self.m_App->resources, name); if(item != NULL && item->type == type) { return item->data; } ds_printf("Resource not found: %s\n", name); return NULL; } GUI_Widget* BiosFlasher_GetWidget(const char* name) { return (GUI_Widget *) BiosFlasher_GetElement(name, LIST_ITEM_GUI_WIDGET, 1); } int BiosFlasher_GetNumFilesCurrentDir() { GUI_Widget *w = GUI_FileManagerGetItemPanel(self.filebrowser); return GUI_ContainerGetCount(w); } // HANDLERS void BiosFlasher_ActivateScrollButtons(int currScrollPos, int maxScroll) { GUI_WidgetSetEnabled(BiosFlasher_GetWidget("btn_scroll_left"), 0); GUI_WidgetSetEnabled(BiosFlasher_GetWidget("btn_scroll_right"), 0); if (currScrollPos > 0) { GUI_WidgetSetEnabled(BiosFlasher_GetWidget("btn_scroll_left"), 1); } if (currScrollPos < maxScroll) { GUI_WidgetSetEnabled(BiosFlasher_GetWidget("btn_scroll_right"), 1); } } void BiosFlasher_OnLeftScrollPressed(GUI_Widget *widget) { if (--self.m_ScrollPos < 0) self.m_ScrollPos = 0; GUI_PanelSetYOffset(GUI_FileManagerGetItemPanel(self.filebrowser), self.m_ScrollPos * 300); BiosFlasher_ActivateScrollButtons(self.m_ScrollPos, self.m_MaxScroll); } void BiosFlasher_OnRightScrollPressed(GUI_Widget *widget) { if (++self.m_ScrollPos > self.m_MaxScroll) self.m_ScrollPos = self.m_MaxScroll; GUI_PanelSetYOffset(GUI_FileManagerGetItemPanel(self.filebrowser), self.m_ScrollPos * 300); BiosFlasher_ActivateScrollButtons(self.m_ScrollPos, self.m_MaxScroll); } void BiosFlasher_ItemClick(dirent_fm_t *fm_ent) { dirent_t *ent = &fm_ent->ent; GUI_Widget *fmw = (GUI_Widget*)fm_ent->obj; if(ent->attr == O_DIR) { GUI_FileManagerChangeDir(fmw, ent->name, ent->size); self.m_ScrollPos = 0; self.m_MaxScroll = BiosFlasher_GetNumFilesCurrentDir() / 10; GUI_PanelSetYOffset(GUI_FileManagerGetItemPanel(fmw), self.m_ScrollPos * 300); BiosFlasher_ActivateScrollButtons(self.m_ScrollPos, self.m_MaxScroll); return; } if (IsFileSupportedByApp(self.m_App, ent->name)) { if(self.m_SelectedBiosFile) { free(self.m_SelectedBiosFile); } self.m_SelectedBiosFile = strdup(ent->name); int i; GUI_Widget *panel, *w; panel = GUI_FileManagerGetItemPanel(fmw); for(i = 0; i < GUI_ContainerGetCount(panel); i++) { w = GUI_FileManagerGetItem(fmw, i); if(i != fm_ent->index) { GUI_ButtonSetNormalImage(w, self.m_ItemNormal); GUI_ButtonSetHighlightImage(w, self.m_ItemNormal); } else { GUI_ButtonSetNormalImage(w, self.m_ItemSelected); GUI_ButtonSetHighlightImage(w, self.m_ItemSelected); } } } } void BiosFlasher_OnWritePressed(GUI_Widget *widget) { self.m_CurrentOperation = eWriting; BiosFlasher_EnableChoseFilePage(); } void BiosFlasher_OnReadPressed(GUI_Widget *widget) { self.m_CurrentOperation = eReading; BiosFlasher_EnableChoseFilePage(); } void BiosFlasher_OnComparePressed(GUI_Widget *widget) { self.m_CurrentOperation = eCompare; BiosFlasher_EnableChoseFilePage(); } void BiosFlasher_OnDetectPressed(GUI_Widget *widget) { ScreenFadeOut(); thd_sleep(200); BiosFlasher_EnableMainPage(); // Redetect bios again ScreenFadeIn(); } void BiosFlasher_OnBackPressed(GUI_Widget *widget) { BiosFlasher_EnableMainPage(); } void BiosFlasher_OnSettingsPressed(GUI_Widget *widget) { BiosFlasher_EnableSettingsPage(); } void BiosFlasher_OnConfirmPressed(GUI_Widget *widget) { if (self.m_SelectedBiosFile == 0 && self.m_CurrentOperation != eReading) { ds_printf("Select bios file!\n"); return; } BiosFlasher_EnableProgressPage(); int result = eSuccess; char* fileName = 0; char filePath[NAME_MAX]; memset(filePath, 0, NAME_MAX); switch(self.m_CurrentOperation) { case eWriting: snprintf(filePath, NAME_MAX, "%s/%s", GUI_FileManagerGetPath(self.filebrowser), self.m_SelectedBiosFile); // TODO result = BiosFlasher_WriteBiosFileToFlash(filePath, &BiosFlasher_OnOperationProgress); break; case eReading: fileName = BiosFlasher_GenerateBackupName(); snprintf(filePath, NAME_MAX, "%s/%s", GUI_FileManagerGetPath(self.filebrowser), fileName); // TODO result = BiosFlasher_ReadBiosToFile(filePath, &BiosFlasher_OnOperationProgress); break; case eCompare: snprintf(filePath, NAME_MAX, "%s/%s", GUI_FileManagerGetPath(self.filebrowser), self.m_SelectedBiosFile); // TODO result = BiosFlasher_CompareBiosWithFile(filePath, &BiosFlasher_OnOperationProgress); break; case eNone: case eErasing: break; }; BiosFlasher_EnableResultPage(result, fileName); free(fileName); } void BiosFlasher_OnSaveSettingsPressed(GUI_Widget *widget) { const char* dataStart = GUI_TextEntryGetText(BiosFlasher_GetWidget("start_addresss")); settings.m_DataStart = atol(dataStart); const char* dataLength = GUI_TextEntryGetText(BiosFlasher_GetWidget("data_length")); settings.m_DataLength = atol(dataLength); // TODO: Validate start address and length here BiosFlasher_EnableMainPage(); } void BiosFlasher_OnSupportedPressed(GUI_Widget *widget) { dsystem("bflash -l"); ShowConsole(); } void BiosFlasher_OnExitPressed(GUI_Widget *widget) { (void)widget; App_t *app = NULL; if(self.have_args == true) { app = GetAppByName("File Manager"); if(!app || !(app->state & APP_STATE_LOADED)) { app = NULL; } } if(!app) { app = GetAppByName("Main"); } OpenApp(app, NULL); } void BiosFlasher_OnOperationProgress(OperationState_t state, float progress) { char msg[64]; // TODO: Check overflow memset(msg, 0, sizeof(msg)); switch(state) { case eErasing: sprintf(msg, "Erasing: %d%%", (int)(progress * 100)); break; case eWriting: sprintf(msg, "Writing: %d%%", (int)(progress * 100)); break; case eReading: sprintf(msg, "Reading: %d%%", (int)(progress * 100)); break; case eNone: case eCompare: break; }; GUI_LabelSetText(self.m_LabelProgress, msg); GUI_ProgressBarSetPosition(self.m_ProgressBar, progress); } void BiosFlasher_EnableMainPage() { if (GUI_CardStackGetIndex(self.pages) != 0) { ScreenFadeOut(); thd_sleep(200); GUI_CardStackShowIndex(self.pages, 0); ScreenFadeIn(); } bflash_dev_t* dev = BiosFlasher_DetectFlashChip(); char info[64]; sprintf(info, "Model: %s", dev->name); GUI_LabelSetText(BiosFlasher_GetWidget("label_flash_name"), info); sprintf(info, "Size: %dKb", dev->size); GUI_LabelSetText(BiosFlasher_GetWidget("label_flash_size"), info); sprintf(info, "Voltage: %dV", (dev->flags & F_FLASH_LOGIC_3V) ? 3 : 5); GUI_LabelSetText(BiosFlasher_GetWidget("label_flash_voltage"), info); sprintf(info, "Access: %s", (dev->flags & F_FLASH_PROGRAM) ? "Read/Write" : "Read only"); GUI_LabelSetText(BiosFlasher_GetWidget("label_flash_access"), info); } void BiosFlasher_EnableChoseFilePage() { ScreenFadeOut(); thd_sleep(200); GUI_CardStackShowIndex(self.pages, 1); ScreenFadeIn(); self.m_ScrollPos = 0; self.m_MaxScroll = BiosFlasher_GetNumFilesCurrentDir() / 10; GUI_PanelSetYOffset(GUI_FileManagerGetItemPanel(self.filebrowser), self.m_ScrollPos * 300); BiosFlasher_ActivateScrollButtons(self.m_ScrollPos, self.m_MaxScroll); } void BiosFlasher_EnableProgressPage() { ScreenFadeOut(); thd_sleep(200); GUI_CardStackShowIndex(self.pages, 2); ScreenFadeIn(); } void BiosFlasher_EnableResultPage(int result, const char* fileName) { ScreenFadeOut(); thd_sleep(200); GUI_CardStackShowIndex(self.pages, 3); ScreenFadeIn(); char title[32]; char msg[64]; // TODO: Check overflow memset(title, 0, sizeof(title)); memset(msg, 0, sizeof(msg)); switch(self.m_CurrentOperation) { case eWriting: if (result == eSuccess) { sprintf(title, "Done"); sprintf(msg, "Writing successful"); } else { sprintf(title, "Error"); sprintf(msg, "Writing fail. Status code: %d", result); } break; case eReading: if (result == eSuccess) { sprintf(title, "Done"); sprintf(msg, "Reading successful. File stored at file %s", fileName); } else { sprintf(title, "Error"); sprintf(msg, "Reading fail. Status code: %d", result); } break; case eCompare: if (result == eSuccess) { sprintf(title, "Done"); sprintf(msg, "Comare successful. Flash data match"); } else if (result == eDataMissmatch) { sprintf(title, "Done"); sprintf(msg, "Comare successful. Flash data missmatch"); } else { sprintf(title, "Error"); sprintf(msg, "Comaring fail. Status code: %d", result); } break; case eNone: case eErasing: break; }; GUI_LabelSetText(BiosFlasher_GetWidget("result_title_text"), title); GUI_LabelSetText(BiosFlasher_GetWidget("result_desc_text"), msg); } void BiosFlasher_EnableSettingsPage() { ScreenFadeOut(); thd_sleep(200); GUI_CardStackShowIndex(self.pages, 4); ScreenFadeIn(); } void BiosFlasher_Init(App_t* app) { BiosFlasher_ResetSelf(); self.m_App = app; if (self.m_App != 0) { self.m_LabelProgress = (GUI_Widget *) BiosFlasher_GetElement("progress_text", LIST_ITEM_GUI_WIDGET, 1); self.m_LabelProgressDesc = (GUI_Widget *) BiosFlasher_GetElement("progress_desc", LIST_ITEM_GUI_WIDGET, 1); self.m_ProgressBar = (GUI_Widget *) BiosFlasher_GetElement("progressbar", LIST_ITEM_GUI_WIDGET, 1); self.filebrowser = (GUI_Widget *) BiosFlasher_GetElement("file_browser", LIST_ITEM_GUI_WIDGET, 1); self.pages = (GUI_Widget *) BiosFlasher_GetElement("pages", LIST_ITEM_GUI_WIDGET, 1); self.m_ItemNormal = (GUI_Surface *) BiosFlasher_GetElement("item-normal", LIST_ITEM_GUI_SURFACE, 0); self.m_ItemSelected = (GUI_Surface *) BiosFlasher_GetElement("item-selected", LIST_ITEM_GUI_SURFACE, 0); /* Disabling scrollbar on filemanager */ GUI_FileManagerRemoveScrollbar(self.filebrowser); if (app->args != 0) { char *name = getFilePath(app->args); self.have_args = true; if(name) { GUI_FileManagerSetPath(self.filebrowser, name); free(name); name = strrchr(app->args, '/'); if(name) { name++; self.m_SelectedBiosFile = strdup(name); } } BiosFlasher_OnWritePressed(NULL); } else { self.have_args = false; BiosFlasher_EnableMainPage(); } } else { ds_printf("DS_ERROR: Can't find app named: %s\n", "BiosFlasher"); } } <file_sep>/modules/httpd/module.c /* DreamShell ##version## module.c - httpd module Copyright (C)2012-2013 SWAT */ #include "ds.h" #include "network/http.h" DEFAULT_MODULE_EXPORTS_CMD(httpd, "DreamShell http server"); int builtin_httpd_cmd(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s options args\n" "Options: \n" " -s, --start -Start server\n" " -t, --stop -Stop server\n\n" "Arguments: \n" " -p, --port -Server listen port (default 80)\n\n" "Example: %s --start\n\n", argv[0], argv[0]); return CMD_NO_ARG; } int start_srv = 0, stop_srv = 0, port = 0; struct cfg_option options[] = { {"start", 's', NULL, CFG_BOOL, (void *) &start_srv, 0}, {"stop", 't', NULL, CFG_BOOL, (void *) &stop_srv, 0}, {"port", 'p', NULL, CFG_INT, (void *) &port, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(start_srv) { httpd_init(port); return CMD_OK; } if(stop_srv) { httpd_shutdown(); return CMD_OK; } return CMD_NO_ARG; } <file_sep>/modules/mp3/libmp3/libmp3/mpg123_snddrv.c /* ** ** LIBMPG123_SNDDRV (C) PH3NOM 2011 ** ** All of the input file acces is done through the library ** by using mpg123_open(), and this allows for the use of ** mpg123_read() to get a desired number of pcm samples ** without having to worry about feeding the input buffer ** ** The last function in this module snddrv_mp3() ** demonstrates decoding an MP2/MP3 in a seperate thread ** */ #include <kos.h> #include <assert.h> #include "config.h" #include "compat.h" #include "mpg123.h" #include "snddrv.h" static mpg123_handle *mh; //static struct mpg123_frameinfo decinfo; static long hz; static int chn, enc; static int err; static size_t done; static int id3;//, idx; static int pos_t; static int len_t; /* Copy the ID3v2 fields into our song info structure */ void print_v2(mpg123_id3v2 *v2) { printf("%s", (char*)v2->title ); printf("%s", (char*)v2->artist ); printf("Album: %s", (char*)v2->album ); printf("Genre: %s", (char*)v2->genre); } /* Copy the ID3v1 fields into our song info structure */ void print_v1(mpg123_id3v1 *v1) { printf("%s", (char*)v1->title ); printf("%s", (char*)v1->artist ); printf("Album: %s", (char*)v1->album ); //printf("Genre: %i", (char*)v1->genre); } static void *pause_thd(void *p) { while( snddrv.dec_status != SNDDEC_STATUS_RESUMING ) { if ( snddrv.buf_status == SNDDRV_STATUS_NEEDBUF ) { memset( snddrv.pcm_buffer, 0, snddrv.pcm_needed ); snddrv.buf_status = SNDDRV_STATUS_HAVEBUF; } thd_sleep(20); } snddrv.dec_status = SNDDEC_STATUS_STREAMING; return NULL; } /* Proprietary routines for file seeking */ int sndmp3_pause() { if( snddrv.dec_status == SNDDEC_STATUS_STREAMING ) { snddrv.dec_status = SNDDEC_STATUS_PAUSING; if( snddrv.dec_status != SNDDEC_STATUS_STREAMING ) return 0; printf("LibADX: Pausing\n"); snddrv.dec_status = SNDDEC_STATUS_PAUSING; while( snddrv.dec_status != SNDDEC_STATUS_PAUSED ) thd_pass(); thd_create(0, pause_thd, NULL ); } return snddrv.dec_status; } int sndmp3_restart() { if( snddrv.dec_status == SNDDEC_STATUS_STREAMING ) { snddrv.dec_status = SNDDEC_STATUS_PAUSING; while( snddrv.dec_status != SNDDEC_STATUS_PAUSED ) thd_pass(); mpg123_seek( mh, 0, SEEK_SET ); snddrv.dec_status = SNDDEC_STATUS_STREAMING; } return snddrv.dec_status; } int sndmp3_rewind() { if( snddrv.dec_status == SNDDEC_STATUS_STREAMING ) { snddrv.dec_status = SNDDEC_STATUS_PAUSING; while( snddrv.dec_status != SNDDEC_STATUS_PAUSED ) thd_pass(); pos_t = mpg123_tell( mh ); if( pos_t >= SEEK_LEN/4 ) { pos_t -= SEEK_LEN/4; mpg123_seek( mh, pos_t, SEEK_SET ); } snddrv.dec_status = SNDDEC_STATUS_STREAMING; } return snddrv.dec_status; } int sndmp3_fastforward() { if( snddrv.dec_status == SNDDEC_STATUS_STREAMING ) { snddrv.dec_status = SNDDEC_STATUS_PAUSING; while( snddrv.dec_status != SNDDEC_STATUS_PAUSED ) thd_pass(); pos_t = mpg123_tell( mh ); if( pos_t <= len_t - SEEK_LEN/4 ) { pos_t += SEEK_LEN/4; mpg123_seek( mh, pos_t, SEEK_SET ); } snddrv.dec_status = SNDDEC_STATUS_STREAMING; } return snddrv.dec_status; } int sndmp3_stop() { if(snddrv.dec_status != SNDDEC_STATUS_NULL) { snddrv.dec_status = SNDDEC_STATUS_DONE; while( snddrv.dec_status != SNDDEC_STATUS_NULL ) thd_pass(); } return 0; } int mpg123_callback( ) { /* Wait for the AICA Driver to signal for more data */ while( snddrv.buf_status != SNDDRV_STATUS_NEEDBUF ) thd_pass(); /* Decode the data, now that we know how many samples the driver needs */ err = mpg123_read(mh, (uint8*)snddrv.pcm_buffer, snddrv.pcm_needed, &done); snddrv.pcm_bytes = done; snddrv.pcm_ptr = snddrv.pcm_buffer; //printf("SNDDRV REQ: %i, SNDDRV RET: %i\n", snddrv.pcm_needed, snddrv.pcm_bytes ); /* Check for end of stream and make sure we have enough samples ready */ if ( (err == MPG123_DONE) || (done < snddrv.pcm_needed && snddrv.pcm_needed > 0) ){ snddrv.dec_status = SNDDEC_STATUS_DONE; printf("spu_mp3_stream: return done\n"); } /* Check for error */ if (err == MPG123_ERR ){ printf("err = %s\n", mpg123_strerror(mh)); snddrv.dec_status = SNDDEC_STATUS_ERROR; printf("spu_mp3_stream: return error\n"); } /* Alert the AICA driver that the requested bytes are ready */ snddrv.buf_status = SNDDRV_STATUS_HAVEBUF; return snddrv.pcm_bytes; } int sndmp3_start_block(const char * fname) { /* Initialize the Decoder */ err = mpg123_init(); if(!mh) { printf("Mh init\n"); mh = mpg123_new(NULL, &err); } if(mh == NULL) { printf("Can't init mpg123: %s\n", mpg123_strerror(mh)); return -1; } /* Open the MP3 context*/ err = mpg123_open(mh, fname); //assert(err == MPG123_OK); if(err != MPG123_OK) { mpg123_exit(); return -1; } mpg123_getformat(mh, &hz, &chn, &enc); printf("MP3 File Info: %ld Hz, %i channels...\n", hz, chn); if(!hz && !chn) { printf("Can't detect format\n"); mpg123_close(mh); mpg123_exit(); return -1; } mpg123_id3v1 *v1; mpg123_id3v2 *v2; /* Get the ID3 Tag data */ int meta = mpg123_meta_check(mh); if(meta & MPG123_ID3 && mpg123_id3(mh, &v1, &v2) == MPG123_OK) { printf("Tag data on %s:\n", fname); if(v1 != NULL) { printf("\n==== ID3v1 ====\n"); print_v1(v1); id3=1; } else if(v2 != NULL) { printf("\n==== ID3v2 ====\n"); print_v2(v2); id3=1; } } /* mpg123_info(mh, &decinfo); printf("Output Sampling rate = %ld\r\n", decinfo.rate); printf("Output Bitrate = %d\r\n", decinfo.bitrate); printf("Output Frame size = %d\r\n", decinfo.framesize); */ len_t = mpg123_length(mh); snd_sinfo.slen = len_t / hz; /* Start the AICA Driver */ snddrv_start( hz, chn ); snddrv.dec_status = SNDDEC_STATUS_STREAMING; printf("spu_wave_stream: beginning\n"); snddrv.dec_status = SNDDEC_STATUS_STREAMING; while( snddrv.dec_status != SNDDEC_STATUS_DONE && snddrv.dec_status != SNDDEC_STATUS_ERROR ) { /* A request has been made to access the decoder handle */ if( snddrv.dec_status == SNDDEC_STATUS_PAUSING ) snddrv.dec_status = SNDDEC_STATUS_PAUSED; /* Wait for request to complete */ while( snddrv.dec_status != SNDDEC_STATUS_STREAMING ) thd_pass(); mpg123_callback( ); //timer_spin_sleep(10); } printf("spu_wave_stream: finished\n"); /* Exit the AICA Driver */ snddrv_exit(); /* Release the audio decoder */ mpg123_close(mh); mpg123_exit(); err = 0; hz = 0; chn = 0; done = 0; enc = 0; snddrv.pcm_ptr = 0; id3 = 0; sq_clr( snddrv.pcm_buffer, 65536 ); SNDDRV_FREE_SINFO(); snddrv.dec_status = SNDDEC_STATUS_NULL; printf("spu_mp3_stream: exited\n"); return 0; } void *snddrv_mp3_thread() { while( snddrv.dec_status != SNDDEC_STATUS_DONE && snddrv.dec_status != SNDDEC_STATUS_ERROR ) { /* A request has been made to access the decoder handle */ if( snddrv.dec_status == SNDDEC_STATUS_PAUSING ) snddrv.dec_status = SNDDEC_STATUS_PAUSED; /* Wait for request to complete */ while( snddrv.dec_status != SNDDEC_STATUS_STREAMING ) thd_pass(); mpg123_callback( ); //timer_spin_sleep(30); } printf("spu_wave_stream: finished\n"); /* Exit the AICA Driver */ snddrv_exit(); /* Release the audio decoder */ mpg123_close(mh); mpg123_exit(); err = 0; hz = 0; chn = 0; done = 0; enc = 0; snddrv.pcm_ptr = 0; sq_clr( snddrv.pcm_buffer, 65536 ); SNDDRV_FREE_SINFO(); snddrv.dec_status = SNDDEC_STATUS_NULL; printf("spu_mp3_stream: exited\n"); return NULL; } int sndmp3_start(const char * fname, int loop) { /* Initialize the Decoder */ err = mpg123_init(); if(!mh) { printf("Mh init\n"); mh = mpg123_new(NULL, &err); } //assert(mh != NULL); if(mh == NULL) return -1; /* Open the MP3 context*/ err = mpg123_open(mh, fname); //assert(err == MPG123_OK); if(err != MPG123_OK) { mpg123_exit(); return -1; } mpg123_getformat(mh, &hz, &chn, &enc); printf("MP3 File Info: %ld Hz, %i channels...\n", hz, chn); if(!hz && !chn) { printf("Can't detect format\n"); mpg123_close(mh); mpg123_exit(); return -1; } /* mpg123_info(mh, &decinfo); printf("Output Sampling rate = %ld\n", decinfo.rate); printf("Output Bitrate = %d\n", decinfo.bitrate); printf("Output Frame size = %d\n", decinfo.framesize); */ len_t = mpg123_length(mh); snd_sinfo.slen = len_t / hz; /* Start the AICA Driver */ snddrv_start( hz, chn ); snddrv.dec_status = SNDDEC_STATUS_STREAMING; printf("spu_wave_stream: beginning\n"); snddrv.dec_status = SNDDEC_STATUS_STREAMING; /* Start the DECODER thread */ thd_create(0, snddrv_mp3_thread, NULL ); return 0; } <file_sep>/modules/luaDS/module.c /* DreamShell ##version## module.c - luaDS module Copyright (C)2007-2013 SWAT */ #include <kos.h> #include <kos/exports.h> #include "ds.h" DEFAULT_MODULE_HEADER(luaDS); int tolua_DS_open(lua_State* tolua_S); int lib_open(klibrary_t * lib) { lua_State *L = GetLuaState(); if(L != NULL) { tolua_DS_open(L); } RegisterLuaLib(lib_get_name(), (LuaRegLibOpen *)tolua_DS_open); return nmmgr_handler_add(&ds_luaDS_hnd.nmmgr); } typedef struct lua_hnd { const char *lua; const char *cmd; } lua_hnd_t; static lua_hnd_t hnds[32]; static int cur_hnds_size = 0; int lib_close(klibrary_t * lib) { UnregisterLuaLib(lib_get_name()); if(cur_hnds_size) { int i; for(i = 0; i < cur_hnds_size; i++) { RemoveCmd(GetCmdByName(hnds[i].cmd)); } //free(hnds); memset(&hnds, 0, sizeof(hnds)); cur_hnds_size = 0; } return nmmgr_handler_remove(&ds_luaDS_hnd.nmmgr); } static int LuaCmdHandler(int argc, char *argv[]) { int i, j; lua_State *L = GetLuaState(); //ds_printf("CALL: %s\n", argv[0]); for(i = 0; i < cur_hnds_size; i++) { //ds_printf("FIND: %s\n", hnds[i].cmd); if(!strcmp(hnds[i].cmd, argv[0])) { lua_getfield(L, LUA_GLOBALSINDEX, hnds[i].lua); if(lua_type(L, -1) != LUA_TFUNCTION) { ds_printf("DS_ERROR: Can't find function: \"%s\" Command handlers support only global functions.\n", hnds[i].lua); return CMD_NOT_EXISTS; } lua_pushnumber(L, argc); lua_newtable(L); for (j = 0; j < argc; j++) { lua_pushnumber(L, j); lua_pushstring(L, argv[j]); lua_settable(L, -3); } EXPT_GUARD_BEGIN; lua_report(L, lua_docall(L, 2, 1)); EXPT_GUARD_CATCH; ds_printf("DS_ERROR: lua command failed: %s\n", argv[0]); EXPT_GUARD_END; //return luaL_checkinteger(L, 1); return CMD_OK; } } return CMD_NOT_EXISTS; } Cmd_t *AddCmdLua(const char *cmd, const char *helpmsg, const char *handler) { cur_hnds_size++; /* if(cur_hnds_size == 1) { hnds = (lua_hnd_t**)malloc(sizeof(lua_hnd_t) * cur_hnds_size); } else { hnds = (lua_hnd_t**)realloc(hnds, sizeof(lua_hnd_t) * cur_hnds_size); }*/ hnds[cur_hnds_size-1].cmd = cmd; hnds[cur_hnds_size-1].lua = handler; //strcpy((char*)hnds[cur_hnds_size-1]->cmd, (char*)cmd); //strcpy((char*)hnds[cur_hnds_size-1]->lua, (char*)handler); //ds_printf("ADD: %s\n", hnds[cur_hnds_size-1].cmd); return AddCmd(cmd, helpmsg, LuaCmdHandler); } static void LuaEvent(void *ds_event, void *sdl_event, int action) { SDL_Event *event = NULL; Event_t *devent = (Event_t *) ds_event; const char *lua = (const char *) devent->param; lua_State *L = GetLuaState(); int narg = 0; lua_getfield(L, LUA_GLOBALSINDEX, lua); if(lua_type(L, -1) != LUA_TFUNCTION) { ds_printf("DS_ERROR: Can't find function: \"%s\" Event handlers support only global functions.\n", lua); return; } if(devent->type == EVENT_TYPE_INPUT) { narg = 1; event = (SDL_Event *) sdl_event; lua_createtable(L,1,8); lua_pushliteral(L,"type"); lua_pushnumber(L,event->type); lua_settable(L,-3); lua_pushliteral(L,"active"); lua_createtable(L,0,2); lua_pushliteral(L,"gain"); lua_pushnumber(L,event->active.gain); lua_settable(L,-3); lua_pushliteral(L,"state"); lua_pushnumber(L,event->active.state); lua_settable(L,-3); lua_settable(L,-3); lua_pushliteral(L,"key"); lua_createtable(L,0,3); lua_pushliteral(L,"type"); lua_pushnumber(L,event->key.type); lua_settable(L,-3); lua_pushliteral(L,"state"); lua_pushnumber(L,event->key.state); lua_settable(L,-3); lua_pushliteral(L,"keysym"); lua_createtable(L,0,3); lua_pushliteral(L,"sym"); lua_pushnumber(L,event->key.keysym.sym); lua_settable(L,-3); lua_pushliteral(L,"mod"); lua_pushnumber(L,event->key.keysym.mod); lua_settable(L,-3); lua_pushliteral(L,"unicode"); lua_pushnumber(L,event->key.keysym.unicode); lua_settable(L,-3); lua_settable(L,-3); lua_settable(L,-3); lua_pushliteral(L,"motion"); lua_createtable(L,0,3); lua_pushliteral(L,"state"); lua_pushnumber(L,event->motion.state); lua_settable(L,-3); lua_pushliteral(L,"x"); lua_pushnumber(L,event->motion.x); lua_settable(L,-3); lua_pushliteral(L,"y"); lua_pushnumber(L,event->motion.y); lua_settable(L,-3); lua_settable(L,-3); lua_pushliteral(L,"button"); lua_createtable(L,0,5); lua_pushliteral(L,"type"); lua_pushnumber(L,event->button.type); lua_settable(L,-3); lua_pushliteral(L,"button"); lua_pushnumber(L,event->button.button); lua_settable(L,-3); lua_pushliteral(L,"state"); lua_pushnumber(L,event->button.state); lua_settable(L,-3); lua_pushliteral(L,"x"); lua_pushnumber(L,event->button.x); lua_settable(L,-3); lua_pushliteral(L,"y"); lua_pushnumber(L,event->button.y); lua_settable(L,-3); lua_settable(L,-3); lua_pushliteral(L,"jaxis"); lua_createtable(L,0,2); lua_pushliteral(L,"axis"); lua_pushnumber(L,event->jaxis.axis); lua_settable(L,-3); lua_pushliteral(L,"value"); lua_pushnumber(L,event->jaxis.value); lua_settable(L,-3); lua_settable(L,-3); lua_pushliteral(L,"jhat"); lua_createtable(L,0,2); lua_pushliteral(L,"hat"); lua_pushnumber(L,event->jhat.hat); lua_settable(L,-3); lua_pushliteral(L,"value"); lua_pushnumber(L,event->jhat.value); lua_settable(L,-3); lua_settable(L,-3); lua_pushliteral(L,"jbutton"); lua_createtable(L,0,3); lua_pushliteral(L,"type"); lua_pushnumber(L,event->jbutton.type); lua_settable(L,-3); lua_pushliteral(L,"button"); lua_pushnumber(L,event->jbutton.button); lua_settable(L,-3); lua_pushliteral(L,"state"); lua_pushnumber(L,event->jbutton.state); lua_settable(L,-3); lua_settable(L,-3); lua_pushliteral(L,"user"); lua_createtable(L,0,2); lua_pushliteral(L,"type"); lua_pushnumber(L,event->user.type); lua_settable(L,-3); lua_pushliteral(L,"code"); lua_pushnumber(L,event->user.code); lua_settable(L,-3); lua_settable(L,-3); } EXPT_GUARD_BEGIN; lua_report(L, lua_docall(L, narg, 1)); EXPT_GUARD_CATCH; ds_printf("DS_ERROR: lua event failed: %s\n", lua); EXPT_GUARD_END; } Event_t *AddEventLua(const char *name, int type, const char *handler) { return AddEvent(name, type, LuaEvent, (void *)handler); } <file_sep>/src/chdir.c /* DreamShell ##version## * chdir.c * (c) 2004-2014 SWAT */ #include "ds.h" /* read a pathname based on the current directory and turn it into an abs one, we don't check for validity, or really do anything except handle ..'s and .'s */ int makeabspath_wd(char *buff, char *path, char *dir, size_t size) { int numtxts; int i; char *txts[32]; /* max of 32...should be nuff */ char *rslash; numtxts = 0; /* check if path is already absolute */ if (path[0] == '/') { strncpy(buff, path, size); return 0; } /* split the path into tokens */ for (numtxts = 0; numtxts < 32;) { if ((txts[numtxts] = strsep(&path, "/")) == NULL) break; if (*txts[numtxts] != '\0') numtxts++; } /* start from the current directory */ strncpy(buff, dir, size); for (i = 0; i < numtxts; i++) { if (strcmp(txts[i], "..") == 0) { if ((rslash = strrchr(buff, '/')) != NULL) *rslash = '\0'; } else if (strcmp(txts[i], ".") == 0) { /* do nothing */ } else { if (buff[strlen(buff) - 1] != '/') strncat(buff, "/", size - 1 - strlen(buff)); strncat(buff, txts[i], size - 1 - strlen(buff)); } } /* make sure it's not empty */ if (buff[0] == '\0') { buff[0] = '/'; buff[1] = '\0'; } return 0; } // Deprecated int makeabspath(char *buff, char *path, size_t size) { //return makeabspath_wd(buff, path, cwd, size); realpath(path, buff); return 1; } const char *relativeFilePath(const char *rel, const char *file) { if(file[0] == '/') return file; char *rslash, *dir, *ret; char fn[NAME_MAX]; char buff[NAME_MAX]; if((rslash = strrchr(rel, '/')) != NULL) { strncpy(buff, file, NAME_MAX); dir = substring(rel, 0, strlen(rel) - strlen(rslash)); makeabspath_wd(fn, buff, dir, NAME_MAX); fn[strlen(fn)] = '\0'; ret = strdup(fn); //ds_printf("Directory: '%s' File: '%s' Out: '%s'", dir, rslash, ret, fn); free(dir); } else { return file; } return ret; } int relativeFilePath_wb(char *buff, const char *rel, const char *file) { if(file[0] == '/') { strncpy(buff, file, NAME_MAX); return 1; } /* char *rslash, *dir; if((rslash = strrchr(rel, '/')) != NULL) { dir = substring(rel, 0, strlen(rel) - strlen(rslash)); makeabspath_wd(buff, file, dir, NAME_MAX); ds_printf("Directory: '%s' File: '%s' Out: '%s'", dir, rel, buff); */ makeabspath_wd(buff, (char*)file, getFilePath(rel), NAME_MAX); //ds_printf("Directory: '%s' File: '%s' Out: '%s'", path, rel, buff); return 1; } char *getFilePath(const char *file) { char *rslash; if((rslash = strrchr(file, '/')) != NULL) { return substring(file, 0, strlen(file) - strlen(rslash)); } return NULL; } /* change the current directory (dir is an absolute path for now) */ // Deprecated int ds_chdir(char *dir) { return fs_chdir(dir); } <file_sep>/include/audio/snddrv.h /* ** ** This File is a part of Dreamcast Media Center ** (C) Josh "PH3NOM" Pearson 2011 ** */ #ifndef SNDDRV_H #define SNDDRV_H /* Keep track of things from the Driver side */ #define SNDDRV_STATUS_NULL 0x00 #define SNDDRV_STATUS_INITIALIZING 0x01 #define SNDDRV_STATUS_READY 0x02 #define SNDDRV_STATUS_STREAMING 0x03 #define SNDDRV_STATUS_DONE 0x04 #define SNDDRV_STATUS_ERROR 0x05 /* Keep track of things from the Decoder side */ #define SNDDEC_STATUS_NULL 0x00 #define SNDDEC_STATUS_INITIALIZING 0x01 #define SNDDEC_STATUS_READY 0x02 #define SNDDEC_STATUS_STREAMING 0x03 #define SNDDEC_STATUS_PAUSING 0x04 #define SNDDEC_STATUS_PAUSED 0x05 #define SNDDEC_STATUS_RESUMING 0x06 #define SNDDEC_STATUS_DONE 0x07 #define SNDDEC_STATUS_ERROR 0x08 /* Keep track of the buffer status from both sides*/ #define SNDDRV_STATUS_NEEDBUF 0x00 #define SNDDRV_STATUS_HAVEBUF 0x01 #define SNDDRV_STATUS_BUFEND 0x02 /* This seems to be a good number for file seeking on compressed audio */ #define SEEK_LEN 16384*48 /* SNDDRV (C) AICA Audio Driver */ static struct snddrv { int rate; int channels; int pcm_bytes; int pcm_needed; volatile int drv_status; volatile int dec_status; volatile int buf_status; unsigned int pcm_buffer[65536+16384]; unsigned int *pcm_ptr; }snddrv; #define SNDDRV_FREE_STRUCT() { \ snddrv.rate = snddrv.channels = snddrv.drv_status = \ snddrv.dec_status = snddrv.buf_status = 0; } static struct snddrv_song_info { char *artist[128]; char * title[128]; char * track[128]; char * album[128]; char * genre[128]; char *fname; volatile int fpos; volatile float spos; int fsize; float slen; }snd_sinfo; #define SNDDRV_FREE_SINFO() { \ sq_clr( snd_sinfo.artist, 128 ); \ sq_clr( snd_sinfo.title, 128 ); \ sq_clr( snd_sinfo.track, 128 ); \ sq_clr( snd_sinfo.album, 128 ); \ sq_clr( snd_sinfo.genre, 128 ); \ snd_sinfo.fpos = snd_sinfo.spos = snd_sinfo.fsize = snd_sinfo.slen = 0; } #define min(a,b) ( (a) < (b) ? (a) : (b) ) #define MAX_CHANNELS 6 /* make this higher to support files with more channels for LibFAAD */ /* MicroSoft channel definitions */ #define SPEAKER_FRONT_LEFT 0x1 #define SPEAKER_FRONT_RIGHT 0x2 #define SPEAKER_FRONT_CENTER 0x4 #define SPEAKER_LOW_FREQUENCY 0x8 #define SPEAKER_BACK_LEFT 0x10 #define SPEAKER_BACK_RIGHT 0x20 #define SPEAKER_FRONT_LEFT_OF_CENTER 0x40 #define SPEAKER_FRONT_RIGHT_OF_CENTER 0x80 #define SPEAKER_BACK_CENTER 0x100 #define SPEAKER_SIDE_LEFT 0x200 #define SPEAKER_SIDE_RIGHT 0x400 #define SPEAKER_TOP_CENTER 0x800 #define SPEAKER_TOP_FRONT_LEFT 0x1000 #define SPEAKER_TOP_FRONT_CENTER 0x2000 #define SPEAKER_TOP_FRONT_RIGHT 0x4000 #define SPEAKER_TOP_BACK_LEFT 0x8000 #define SPEAKER_TOP_BACK_CENTER 0x10000 #define SPEAKER_TOP_BACK_RIGHT 0x20000 #define SPEAKER_RESERVED 0x80000000 /* SNDDRV Public Function Protocols */ /* Start the Sound Driver Thread */ int snddrv_start( int rate, int chans ); /* Exit the Sound Driver */ int snddrv_exit(); /* Increase Sound Volume */ int snddrv_volume_up(); /* Decrease Sound Volume */ int snddrv_volume_down(); #endif <file_sep>/firmware/bootloader/src/main.c /** * DreamShell boot loader * Main * (c)2011-2023 SWAT <http://www.dc-swat.ru> */ #include "main.h" #include "fs.h" KOS_INIT_FLAGS(INIT_DEFAULT/* | INIT_NET*/); extern uint8 romdisk[]; pvr_init_params_t params = { { PVR_BINSIZE_16, PVR_BINSIZE_0, PVR_BINSIZE_32, PVR_BINSIZE_0, PVR_BINSIZE_0 }, 512 * 1024 }; const char title[28] = "DreamShell boot loader v"VERSION; //#define EMU //#define BIOS_MODE int FileExists(const char *fn) { file_t f; f = fs_open(fn, O_RDONLY); if(f == FILEHND_INVALID) { return 0; } fs_close(f); return 1; } int DirExists(const char *dir) { file_t f; f = fs_open(dir, O_DIR | O_RDONLY); if(f == FILEHND_INVALID) { return 0; } fs_close(f); return 1; } int flashrom_get_region_only() { int start, size; uint8 region[6] = { 0 }; region[2] = *(uint8 *)0xa021a002; /* Find the partition */ if(flashrom_info(FLASHROM_PT_SYSTEM, &start, &size) < 0) { dbglog(DBG_ERROR, "%s: can't find partition %d\n", __func__, FLASHROM_PT_SYSTEM); } else { /* Read the first 5 characters of that partition */ if(flashrom_read(start, region, 5) < 0) { dbglog(DBG_ERROR, "%s: can't read partition %d\n", __func__, FLASHROM_PT_SYSTEM); } } if(region[2] == 0x58 || region[2] == 0x30) { spiral_color = 0x44ed1800; return FLASHROM_REGION_JAPAN; } else if(region[2] == 0x59 || region[2] == 0x31) { spiral_color = 0x44ed1800; return FLASHROM_REGION_US; } else if(region[2] == 0x5A || region[2] == 0x32) { spiral_color = 0x443370d4; return FLASHROM_REGION_EUROPE; } else { spiral_color = 0x44000000; dbglog(DBG_ERROR, "%s: Unknown region code %02x\n", __func__, region[2]); return FLASHROM_REGION_UNKNOWN; } } int is_hacked_bios() { return (*(uint16 *)0xa0000000) == 0xe6ff; } int is_custom_bios() { return (*(uint16 *)0xa0000004) == 0x4318; } int is_no_syscalls() { return (*(uint16 *)0xac000100) != 0x2f06; } #ifdef BIOS_MODE //int is_no_syscalls() { // return (*(uint16 *)0x8c000100) != 0x2f06; //} static int setup_syscalls() { file_t fd; size_t fd_size; int (*sc)(int, int, int, int); dbglog(DBG_INFO, "Loading and setup syscalls...\n"); fd = fs_open(RES_PATH"/syscalls.bin", O_RDONLY); if(fd != FILEHND_INVALID) { fd_size = fs_total(fd); dbgio_dev_select("null"); dcache_flush_range(0x8c000000, fd_size); icache_flush_range(0x8c000000, fd_size); if(fs_read(fd, (uint8*)0x8c000000, fd_size) < 0) { fs_close(fd); dbgio_dev_select("fb"); dbglog(DBG_ERROR, "Error at loading syscalls\n"); return -1; } else { fs_close(fd); dcache_flush_range(0x8c000000, fd_size); icache_flush_range(0x8c000000, fd_size); dbgio_dev_select("fb"); *((uint32 *)&sc) = *((uint32 *)0x8c0000b0); if(sc(0, 0, 0, 0)) { dbglog(DBG_ERROR, "Error in sysinfo syscall\n"); return -1; } dbglog(DBG_INFO, "Syscalls successfully installed\n"); return 0; } } else { dbglog(DBG_ERROR, "Can't open file with syscalls\n"); } return -1; } #endif int start_pressed = 0; static void start_callback(void) { if(!start_pressed) { dbglog(DBG_INFO, "Enter the boot menu...\n"); start_pressed = 1; } } static void show_boot_message(void) { dbglog(DBG_INFO, " %s\n", title); dbglog(DBG_INFO, " !!! Press START to enter the boot menu !!!\n\n"); } int main(int argc, char **argv) { cont_btn_callback(0, CONT_START, (cont_btn_callback_t)start_callback); if(vid_check_cable() == CT_VGA) { vid_set_mode(DM_640x480_VGA, PM_RGB565); } else if(flashrom_get_region_only() == FLASHROM_REGION_EUROPE) { vid_set_mode(DM_640x480_PAL_IL, PM_RGB565); } else { vid_set_mode(DM_640x480_NTSC_IL, PM_RGB565); } #ifndef EMU #ifdef BIOS_MODE if(!fs_romdisk_mount(RES_PATH, (const uint8 *)romdisk, 0)) { dbgio_dev_select("fb"); show_boot_message(); if(is_custom_bios()/* && is_no_syscalls()*/) { setup_syscalls(); // cdrom_init(); // fs_iso9660_init(); } } else { dbgio_dev_select("fb"); show_boot_message(); } InitIDE(); InitSDCard(); #else int ird = 1; dbgio_dev_select("fb"); show_boot_message(); if(!InitIDE()) { ird = 0; } if(!InitSDCard()) { ird = 0; } if(ird && is_custom_bios()) { InitRomdisk(); } #endif dbgio_disable(); #else dbgio_dev_select("scif"); show_boot_message(); #endif if(!start_pressed) { menu_init(); loading_core(1); } pvr_init(&params); #ifdef BIOS_MODE spiral_init(); fs_romdisk_unmount(RES_PATH); #else if(!fs_romdisk_mount(RES_PATH, (const uint8 *)romdisk, 0)) { spiral_init(); fs_romdisk_unmount(RES_PATH); } #endif if(!start_pressed) init_menu_txr(); else menu_init(); pvr_set_bg_color(192.0/255.0, 192.0/255.0, 192.0/255.0); while(1) { pvr_wait_ready(); pvr_scene_begin(); pvr_list_begin(PVR_LIST_TR_POLY); spiral_frame(); menu_frame(); pvr_list_finish(); pvr_scene_finish(); } return 0; } <file_sep>/modules/isofs/gdi.c /** * Copyright (c) 2014-2015 by SWAT <<EMAIL>> www.dc-swat.ru * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <kos.h> #include "console.h" #include "utils.h" #include "isofs/gdi.h" #include "internal.h" //#define DEBUG 1 static char *fs_gets(file_t fd, char *buffer, int count) { uint8 ch; char *cp; int rc; cp = buffer; while(count-- > 1) { rc = fs_read(fd, &ch, 1); if(rc < 0) { *cp = 0; return NULL; } else if(!rc) { break; } *cp++ = ch; if (ch == '\n') break; } *cp = 0; return buffer; } static int check_gdi_image(file_t fd) { char line[NAME_MAX]; uint32 track_count; fs_seek(fd, 0, SEEK_SET); if(fs_gets(fd, line, NAME_MAX) == NULL) { #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Not a GDI image\n", __func__); #endif return -1; } track_count = strtoul(line, NULL, 0); if(track_count == 0 || track_count > 99) { #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Invalid GDI image\n", __func__); #endif return -1; } return (int)track_count; } GDI_header_t *gdi_open(file_t fd, const char *filename) { int track_count; if((track_count = check_gdi_image(fd)) < 0) { return NULL; } #ifdef DEBUG dbglog(DBG_DEBUG, "%s: %d tracks in image\n", __func__, track_count); #endif int track_no, i, rc; char line[NAME_MAX], fname[NAME_MAX / 2]; char *path = NULL; GDI_header_t *hdr; hdr = (GDI_header_t*)malloc(sizeof(GDI_header_t)); if(hdr == NULL) { return NULL; } memset_sh4(hdr, 0, sizeof(GDI_header_t)); hdr->track_count = (uint32)track_count; hdr->track_fd = FILEHND_INVALID; hdr->track_current = GDI_MAX_TRACKS; path = getFilePath(filename); for(i = 0; i < hdr->track_count; i++) { if(fs_gets(fd, line, sizeof(line)) == NULL) { #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Unexpected end of file\n", __func__); #endif goto error; } hdr->tracks[i] = (GDI_track_t*)malloc(sizeof(GDI_track_t)); if(hdr->tracks[i] == NULL) { goto error; } #ifdef DEBUG dbglog(DBG_DEBUG, "%s: %s", __func__, line); #endif rc = sscanf(line, "%d %ld %ld %ld %s %ld", &track_no, &hdr->tracks[i]->start_lba, &hdr->tracks[i]->flags, &hdr->tracks[i]->sector_size, fname, &hdr->tracks[i]->offset); if(rc < 6) { #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Invalid line in GDI: %s\n", __func__, line); #endif goto error; } snprintf(hdr->tracks[i]->filename, NAME_MAX, "%s/%s", path, fname); } free(path); return hdr; error: if(path) { free(path); } gdi_close(hdr); return NULL; } int gdi_close(GDI_header_t *hdr) { if(!hdr) { return -1; } int i; for(i = 0; i < hdr->track_count; i++) { if(hdr->tracks[i] != NULL) { free(hdr->tracks[i]); } } if(hdr->track_fd != FILEHND_INVALID) { fs_close(hdr->track_fd); } free(hdr); return 0; } int gdi_get_toc(GDI_header_t *hdr, CDROM_TOC *toc) { int i, ft_no = 0; uint8 ctrl = 0, adr = 1; GDI_track_t *first_track = hdr->tracks[0]; for(i = 0; i < hdr->track_count; i++) { toc->entry[i] = ((hdr->tracks[i]->flags & 0x0F) << 28) | adr << 24 | (hdr->tracks[i]->start_lba + 150); if(hdr->tracks[i]->start_lba == 45000) { first_track = hdr->tracks[i]; ft_no = i+1; } #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Track%d %08lx\n", __func__, i, toc->entry[i]); #endif } for(i = hdr->track_count - 1; i > -1; i--) { if(hdr->tracks[i]->start_lba == 45000) { first_track = hdr->tracks[i]; break; } } GDI_track_t *last_track = hdr->tracks[hdr->track_count - 1]; uint32 track_size = FileSize(last_track->filename) / last_track->sector_size; ctrl = first_track->flags & 0x0F; toc->first = ctrl << 28 | adr << 24 | ft_no << 16; ctrl = last_track->flags & 0x0F; toc->last = ctrl << 28 | adr << 24 | hdr->track_count << 16; toc->leadout_sector = ctrl << 28 | adr << 24 | (last_track->start_lba + track_size + 150); for(i = hdr->track_count; i < 99; i++) { toc->entry[i] = -1; } #ifdef DEBUG dbglog(DBG_DEBUG, "%s:\n First track %08lx\n Last track %08lx\n Leadout %08lx\n", __func__, toc->first, toc->last, toc->leadout_sector); #endif return 0; } GDI_track_t *gdi_get_track(GDI_header_t *hdr, uint32 lba) { int i; for(i = hdr->track_count - 1; i > -1; i--) { if(hdr->tracks[i]->start_lba <= lba) { #ifdef DEBUG dbglog(DBG_DEBUG, "%s: %ld found in track #%d\n", __func__, lba, i + 1); #endif if(hdr->track_current != i) { #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Opening %s\n", __func__, hdr->tracks[i]->filename); #endif if(hdr->track_fd != FILEHND_INVALID) { fs_close(hdr->track_fd); } hdr->track_fd = fs_open(hdr->tracks[i]->filename, O_RDONLY); if(hdr->track_fd < 0) { #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Can't open %s\n", __func__, hdr->tracks[i]->filename); #endif return NULL; } hdr->track_current = i; } return hdr->tracks[i]; } } return NULL; } uint32 gdi_get_offset(GDI_header_t *hdr, uint32 lba, uint16 *sector_size) { GDI_track_t *track = gdi_get_track(hdr, lba); if(track == NULL) { return -1; } uint32 offset = (lba - track->start_lba) * track->sector_size; *sector_size = gdi_track_sector_size(track); return offset; } int gdi_read_sectors(GDI_header_t *hdr, uint8 *buff, uint32 start, uint32 count) { uint16 sector_size; uint32 offset = gdi_get_offset(hdr, start, &sector_size); if(offset == (uint32)-1) { return -1; } #ifdef DEBUG dbglog(DBG_DEBUG, "%s: %ld %ld at %ld mode %d\n", __func__, start, count, offset, sector_size); #endif fs_seek(hdr->track_fd, offset, SEEK_SET); return read_sectors_data(hdr->track_fd, count, sector_size, buff); } <file_sep>/modules/ftpd/lftpd/private/lftpd_log.h #pragma once //#define DEBUG 1 #define lftpd_log_error(format, ...) lftpd_log_internal("ERROR", format, ##__VA_ARGS__) #define lftpd_log_info(format, ...) lftpd_log_internal("INFO", format, ##__VA_ARGS__) #ifdef DEBUG #define lftpd_log_debug(format, ...) lftpd_log_internal("DEBUG", format, ##__VA_ARGS__) #else #define lftpd_log_debug(format, ...) #endif void lftpd_log_internal(const char* level, const char* format, ...); <file_sep>/modules/mp3/libmp3/xingmp3/mhead.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /*------------ mhead.c ---------------------------------------------- mpeg audio extract info from mpeg header portable version (adapted from c:\eco\mhead.c add Layer III mods 6/18/97 re mux restart, 32 bit ints mod 5/7/98 parse mpeg 2.5 ---------------------------------------------------------------------*/ #include <float.h> #include <math.h> #include "L3.h" #include "mhead.h" /* mpeg header structure */ static int mp_br_table[2][16] = {{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0}}; static int mp_sr20_table[2][4] = {{441, 480, 320, -999}, {882, 960, 640, -999}}; static int mp_br_tableL1[2][16] = {{0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0},/* mpeg2 */ {0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0}}; static int mp_br_tableL3[2][16] = {{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, /* mpeg 2 */ {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0}}; static int find_sync(unsigned char *buf, int n); static int sync_scan(unsigned char *buf, int n, int i0); static int sync_test(unsigned char *buf, int n, int isync, int padbytes); // jdw /*--------------------------------------------------------------*/ int head_info(unsigned char *buf, unsigned int n, MPEG_HEAD * h) { int framebytes; int mpeg25_flag; if (n > 10000) n = 10000; /* limit scan for free format */ h->sync = 0; //if ((buf[0] == 0xFF) && ((buf[1] & 0xF0) == 0xF0)) if ((buf[0] == 0xFF) && ((buf[0+1] & 0xF0) == 0xF0)) { mpeg25_flag = 0; // mpeg 1 & 2 } else if ((buf[0] == 0xFF) && ((buf[0+1] & 0xF0) == 0xE0)) { mpeg25_flag = 1; // mpeg 2.5 } else return 0; // sync fail h->sync = 1; if (mpeg25_flag) h->sync = 2; //low bit clear signals mpeg25 (as in 0xFFE) h->id = (buf[0+1] & 0x08) >> 3; h->option = (buf[0+1] & 0x06) >> 1; h->prot = (buf[0+1] & 0x01); h->br_index = (buf[0+2] & 0xf0) >> 4; h->sr_index = (buf[0+2] & 0x0c) >> 2; h->pad = (buf[0+2] & 0x02) >> 1; h->private_bit = (buf[0+2] & 0x01); h->mode = (buf[0+3] & 0xc0) >> 6; h->mode_ext = (buf[0+3] & 0x30) >> 4; h->cr = (buf[0+3] & 0x08) >> 3; h->original = (buf[0+3] & 0x04) >> 2; h->emphasis = (buf[0+3] & 0x03); // if( mpeg25_flag ) { // if( h->sr_index == 2 ) return 0; // fail 8khz //} /* compute framebytes for Layer I, II, III */ if (h->option < 1) return 0; if (h->option > 3) return 0; framebytes = 0; if (h->br_index > 0) { if (h->option == 3) { /* layer I */ framebytes = 240 * mp_br_tableL1[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; framebytes = 4 * framebytes; } else if (h->option == 2) { /* layer II */ framebytes = 2880 * mp_br_table[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; } else if (h->option == 1) { /* layer III */ if (h->id) { // mpeg1 framebytes = 2880 * mp_br_tableL3[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; } else { // mpeg2 if (mpeg25_flag) { // mpeg2.2 framebytes = 2880 * mp_br_tableL3[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; } else { framebytes = 1440 * mp_br_tableL3[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; } } } } else framebytes = find_sync(buf, n); /* free format */ return framebytes; } int head_info3(unsigned char *buf, unsigned int n, MPEG_HEAD *h, int *br, unsigned int *searchForward) { unsigned int pBuf = 0; // jdw insertion... while ((pBuf < n) && !((buf[pBuf] == 0xFF) && ((buf[pBuf+1] & 0xF0) == 0xF0 || (buf[pBuf+1] & 0xF0) == 0xE0))) { pBuf++; } if (pBuf == n) return 0; *searchForward = pBuf; return head_info2(&(buf[pBuf]),n,h,br); } /*--------------------------------------------------------------*/ int head_info2(unsigned char *buf, unsigned int n, MPEG_HEAD * h, int *br) { int framebytes; /*--- return br (in bits/sec) in addition to frame bytes ---*/ *br = 0; /*-- assume fail --*/ framebytes = head_info(buf, n, h); if (framebytes == 0) return 0; if (h->option == 1) { /* layer III */ if (h->br_index > 0) *br = 1000 * mp_br_tableL3[h->id][h->br_index]; else { if (h->id) // mpeg1 *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (144 * 20); else { // mpeg2 if ((h->sync & 1) == 0) // flags mpeg25 *br = 500 * framebytes * mp_sr20_table[h->id][h->sr_index] / (72 * 20); else *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (72 * 20); } } } if (h->option == 2) { /* layer II */ if (h->br_index > 0) *br = 1000 * mp_br_table[h->id][h->br_index]; else *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (144 * 20); } if (h->option == 3) { /* layer I */ if (h->br_index > 0) *br = 1000 * mp_br_tableL1[h->id][h->br_index]; else *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (48 * 20); } return framebytes; } /*--------------------------------------------------------------*/ static int compare(unsigned char *buf, unsigned char *buf2) { if (buf[0] != buf2[0]) return 0; if (buf[1] != buf2[1]) return 0; return 1; } /*----------------------------------------------------------*/ /*-- does not scan for initial sync, initial sync assumed --*/ static int find_sync(unsigned char *buf, int n) { int i0, isync, nmatch, pad; int padbytes, option; /* mod 4/12/95 i0 change from 72, allows as low as 8kbits for mpeg1 */ i0 = 24; padbytes = 1; option = (buf[1] & 0x06) >> 1; if (option == 3) { padbytes = 4; i0 = 24; /* for shorter layer I frames */ } pad = (buf[2] & 0x02) >> 1; n -= 3; /* need 3 bytes of header */ while (i0 < 2000) { isync = sync_scan(buf, n, i0); i0 = isync + 1; isync -= pad; if (isync <= 0) return 0; nmatch = sync_test(buf, n, isync, padbytes); if (nmatch > 0) return isync; } return 0; } /*------------------------------------------------------*/ /*---- scan for next sync, assume start is valid -------*/ /*---- return number bytes to next sync ----------------*/ static int sync_scan(unsigned char *buf, int n, int i0) { int i; for (i = i0; i < n; i++) if (compare(buf, buf + i)) return i; return 0; } /*------------------------------------------------------*/ /*- test consecutative syncs, input isync without pad --*/ static int sync_test(unsigned char *buf, int n, int isync, int padbytes) { int i, nmatch, pad; nmatch = 0; for (i = 0;;) { pad = padbytes * ((buf[i + 2] & 0x02) >> 1); i += (pad + isync); if (i > n) break; if (!compare(buf, buf + i)) return -nmatch; nmatch++; } return nmatch; } <file_sep>/include/audio/mp3.h /** * \file mp3.h * \brief MP3 playing * \date 2004-2014 * \author SWAT * \copyright http://www.dc-swat.ru */ #ifndef _DS_MP3_H #define _DS_MP3_H int sndmp3_start(const char * fname, int loop); int sndmp3_start_block(const char * fname); int sndmp3_stop(); int sndmp3_fastforward(); int sndmp3_rewind(); int sndmp3_restart(); int sndmp3_pause(); #endif <file_sep>/include/aicaos/aicaos.h /** * \file aicaos.h * \brief AICAOS for DreamShell * \date 2004-2013 * \author SWAT www.dc-swat.ru */ #ifndef _AICAOS_H #define _AICAOS_H #include "aica_common.h" #include "aica_sh4.h" AICA_SHARED(arm_ping); #endif /* _AICAOS_H */ <file_sep>/modules/opkg/libini/libini.c #include <errno.h> #include <stdbool.h> #include <stdio.h> #include "ini.h" struct INI { const char *buf, *end, *curr; bool free_buf_on_exit; }; static struct INI *_ini_open_mem(const char *buf, size_t len, bool free_buf_on_exit) { struct INI *ini = malloc(sizeof(*ini)); if (!ini) { perror("Unable to allocate memory"); return NULL; } ini->buf = ini->curr = buf; ini->end = buf + len; ini->free_buf_on_exit = free_buf_on_exit; return ini; } struct INI *ini_open_mem(const char *buf, size_t len) { return _ini_open_mem(buf, len, false); } struct INI *ini_open(const char *file) { FILE *f; char *buf; size_t len; struct INI *ini = NULL; f = fopen(file, "r"); if (!f) { perror("Unable to open file"); return NULL; } fseek(f, 0, SEEK_END); len = ftell(f); if (!len) { fprintf(stderr, "ERROR: File is empty\n"); goto error_fclose; } buf = malloc(len); if (!buf) { perror("Unable to allocate memory"); goto error_fclose; } rewind(f); if (fread(buf, 1, len, f) < len) { perror("Unable to read file"); goto error_fclose; } ini = _ini_open_mem(buf, len, true); error_fclose: fclose(f); return ini; } void ini_close(struct INI *ini) { if (ini->free_buf_on_exit) free((char *) ini->buf); free(ini); } static bool skip_comments(struct INI *ini) { const char *curr = ini->curr; const char *end = ini->end; while (curr != end) { if (*curr == '\n') curr++; else if (*curr == '#') do { curr++; } while (curr != end && *curr != '\n'); else break; } ini->curr = curr; return curr == end; } static bool skip_line(struct INI *ini) { const char *curr = ini->curr; const char *end = ini->end; for (; curr != end && *curr != '\n'; curr++); if (curr == end) { ini->curr = end; return true; } else { ini->curr = curr + 1; return false; } } int ini_next_section(struct INI *ini, const char **name, size_t *name_len) { const char *_name; if (ini->curr == ini->end) return 0; /* EOF: no more sections */ if (ini->curr == ini->buf) { if (skip_comments(ini) || *ini->curr != '[') { fprintf(stderr, "Malformed INI file (missing section header)\n"); return -EIO; } } else while (*ini->curr != '[' && !skip_line(ini)); if (ini->curr == ini->end) return 0; /* EOF: no more sections */ _name = ++ini->curr; do { ini->curr++; if (ini->curr == ini->end || *ini->curr == '\n') { fprintf(stderr, "Malformed INI file (malformed section header)\n"); return -EIO; } } while (*ini->curr != ']'); if (name && name_len) { *name = _name; *name_len = ini->curr - _name; } ini->curr++; return 1; } int ini_read_pair(struct INI *ini, const char **key, size_t *key_len, const char **value, size_t *value_len) { size_t _key_len = 0; const char *_key, *_value, *curr, *end = ini->end; if (skip_comments(ini)) return 0; curr = _key = ini->curr; if (*curr == '[') return 0; while (true) { curr++; if (curr == end || *curr == '\n') { fprintf(stderr, "ERROR: Unexpected end of line\n"); return -EIO; } else if (*curr == '=') { if (!_key_len) _key_len = curr - _key; curr++; break; } else if (*curr <= ' ' && !_key_len) _key_len = curr - _key; } /* Skip whitespaces. */ while (curr != end && (*curr == ' ' || *curr == '\t')) curr++; if (curr == end) { fprintf(stderr, "ERROR: Unexpected end of line\n"); return -EIO; } _value = curr++; while (curr != end && *curr != '\n') curr++; if (curr == end) { fprintf(stderr, "ERROR: Unexpected end of line\n"); return -EIO; } *value = _value; *value_len = curr - _value; *key = _key; *key_len = _key_len; ini->curr = ++curr; return 1; } <file_sep>/firmware/isoldr/loader/kos/kos/net.h /* KallistiOS ##version## include/kos/net.h Copyright (C)2002,2004 <NAME> $Id: net.h,v 1.8 2003/06/19 04:30:23 bardtx Exp $ */ #ifndef __KOS_NET_H #define __KOS_NET_H #include <sys/cdefs.h> __BEGIN_DECLS #include <arch/types.h> /* All functions in this header return < 0 on failure, and 0 on success. */ /* Structure describing one usable network device; this is pretty ethernet centric, though I suppose you could stuff other things into this system like PPP. */ typedef struct knetif { /* Long description of the device */ const char *descr; /* Interface flags */ uint32 flags; /* The device's MAC address */ uint8 mac_addr[6]; /* The device's IP address (if any) */ uint8 ip_addr[4]; /* All of the following callback functions should return a negative value on failure, and a zero or positive value on success. Some functions have special values, as noted. */ /* Attempt to detect the device */ int (*if_detect)(struct knetif * self); /* Initialize the device */ int (*if_init)(struct knetif * self); /* Shutdown the device */ int (*if_shutdown)(struct knetif * self); /* Start the device (after init or stop) */ int (*if_start)(struct knetif * self); /* Stop (hibernate) the device */ int (*if_stop)(struct knetif * self); /* Queue a packet for transmission; see special return values below the structure */ int (*if_tx)(struct knetif * self, const uint8 * data, int len); /* Poll for queued receive packets, if neccessary. Returns non-zero if we need to exit the current polling loop (if any). */ int (*if_rx_poll)(struct knetif * self); /* Set flags; you should generally manipulate flags through here so that the driver gets a chance to act on the info. */ int (*if_set_flags)(struct knetif * self, uint32 flags_and, uint32 flags_or); } netif_t; /* Flags for netif_t */ #define NETIF_NO_FLAGS 0x00000000 #define NETIF_REGISTERED 0x00000001 /* Is it registered? */ #define NETIF_DETECTED 0x00000002 /* Is it detected? */ #define NETIF_INITIALIZED 0x00000004 /* Has it been initialized? */ #define NETIF_RUNNING 0x00000008 /* Has start() been called? */ #define NETIF_PROMISC 0x00010000 /* Promiscuous mode */ #define NETIF_NEEDSPOLL 0x01000000 /* Needs to be polled for input */ /* Return types for if_tx */ #define NETIF_TX_OK 0 #define NETIF_TX_ERROR -1 #define NETIF_TX_AGAIN -2 /***** net_core.c *********************************************************/ // Net input callback: returns non-zero if we need to exit the current net // polling loop (if any). int net_input(struct knetif * dev, int pkt_size); /* Init */ int net_init(); /* Shutdown */ void net_shutdown(); __END_DECLS #endif /* __KOS_NET_H */ <file_sep>/firmware/aica/codec/systime.h #ifndef systime_h_ #define systime_h_ #define TCK 10000 /* Timer Clock */ #define PIV ((MCK/TCK/16)-1) /* Periodic Interval Value */ extern volatile unsigned long systime_value; extern void systime_init(void); extern unsigned long systime_get(void); extern unsigned long systime_get_ms(void); #endif <file_sep>/modules/isofs/fs_iso9660.c /* DreamShell ##version## fs_iso9660.c - Virtual ISO9660 filesystem Copyright (C)2000,2001,2003 <NAME> Copyright (C)2001 <NAME> Copyright (C)2002 Bero Copyright (C)2011-2023 SWAT */ #include <ds.h> #include <isofs/isofs.h> #include <isofs/ciso.h> #include <isofs/cdi.h> #include <isofs/gdi.h> #include "internal.h" /* List of cache blocks (ordered least recently used to most recently) */ #define NUM_CACHE_BLOCKS 4 #ifndef MAX_ISO_FILES # define MAX_ISO_FILES 16 #endif /* Holds the data for one cache block, and a pointer to the next one. As sectors are read from the disc, they are added to the front of this cache. As the cache fills up, sectors are removed from the end of it. */ typedef struct { int32 sector; /* CD sector */ uint8 data[2048]; /* Sector data */ } cache_block_t; /* ISO Directory entry */ typedef struct { uint8 length; /* 711 */ uint8 ext_attr_length; /* 711 */ uint8 extent[8]; /* 733 */ uint8 size[8]; /* 733 */ uint8 date[7]; /* 7x711 */ uint8 flags; uint8 file_unit_size; /* 711 */ uint8 interleave; /* 711 */ uint8 vol_sequence[4]; /* 723 */ uint8 name_len; /* 711 */ char name[1]; } virt_iso_dirent_t; typedef struct isofs { SLIST_ENTRY(isofs) list; vfs_handler_t *vfs; const char *fn; file_t fd; CDROM_TOC toc; uint32 session_base; uint32 root_extent; /* Root directory extent */ uint32 root_size; /* Root directory size in bytes */ virt_iso_dirent_t root_dirent; /* Root dirent */ int joliet; cache_block_t *icache[NUM_CACHE_BLOCKS]; /* inode cache */ cache_block_t *dcache[NUM_CACHE_BLOCKS]; /* data cache */ mutex_t cache_mutex; /* Cache modification mutex */ uint32 type; CISO_header_t *ciso; CDI_header_t *cdi; GDI_header_t *gdi; } isofs_t; /* File handles.. I could probably do this with a linked list, but I'm just too lazy right now. =) */ static struct { uint32 first_extent; /* First sector */ int dir; /* >0 if a directory */ uint32 ptr; /* Current read position in bytes */ uint32 size; /* Length of file in bytes */ dirent_t dirent; /* A static dirent to pass back to clients */ int broken; /* >0 if the CD has been swapped out since open */ isofs_t *ifs; } fh[MAX_ISO_FILES]; typedef SLIST_HEAD(isofs_list, isofs) isofs_list_t; static isofs_list_t virt_iso_list; /* Mutex for file handles */ static mutex_t fh_mutex = MUTEX_INITIALIZER; static int inited = 0; static int virt_iso_init_percd(isofs_t *ifs); static int virt_iso_reset(isofs_t *ifs); static void virt_iso_break_all(isofs_t *ifs); /********************************************************************************/ /* Low-level Joliet utils */ /* Joliet UCS is big endian */ static void utf2ucs(uint8 * ucs, const uint8 * utf) { int c; do { c = *utf++; if (c <= 0x7f) { } else if (c < 0xc0) { c = (c & 0x1f) << 6; c |= (*utf++) & 0x3f; } else { c = (c & 0x0f) << 12; c |= ((*utf++) & 0x3f) << 6; c |= (*utf++) & 0x3f; } *ucs++ = c >> 8; *ucs++ = c & 0xff; } while (c); } static void ucs2utfn(uint8 * utf, const uint8 * ucs, size_t len) { int c; len = len / 2; while (len) { len--; c = (*ucs++) << 8; c |= *ucs++; if (c == ';') break; if (c <= 0x7f) { *utf++ = c; } else if (c <= 0x7ff) { *utf++ = 0xc0 | (c >> 6); *utf++ = 0x80 | (c & 0x3f); } else { *utf++ = 0xe0 | (c >> 12); *utf++ = 0x80 | ((c >> 6) & 0x3f); *utf++ = 0x80 | (c & 0x3f); } } *utf = 0; } static int ucscompare(const uint8 * isofn, const uint8 * normalfn, int isosize) { int i, c0, c1 = 0; /* Compare ISO name */ for (i=0; i<isosize; i+=2) { c0 = ((int)isofn[i] << 8) | ((int)isofn[i+1]); c1 = ((int)normalfn[i] << 8) | ((int)normalfn[i+1]); if (c0 == ';') break; /* Otherwise, compare the chars normally */ if (tolower(c0) != tolower(c1)) return -1; } c1 = ((int)normalfn[i] << 8) | (normalfn[i+1]); /* Catch ISO name shorter than normal name */ if (c1 != '/' && c1 != '\0') return -1; else return 0; } static int isjoliet(char * p) { if (p[0] == '%' && p[1] == '/') { switch (p[2]) { case '@': return 1; case 'C': return 2; case 'E': return 3; } } return 0; } /********************************************************************************/ /* Low-level ISO utils */ /* Util function to reverse the byte order of a uint32 */ /* static uint32 ntohl_32(const void *data) { const uint8 *d = (const uint8*)data; return (d[0] << 24) | (d[1] << 16) | (d[2] << 8) | (d[3] << 0); } */ /* This seems kinda silly, but it's important since it allows us to do unaligned accesses on a buffer */ static uint32 htohl_32(const void *data) { const uint8 *d = (const uint8*)data; return (d[0] << 0) | (d[1] << 8) | (d[2] << 16) | (d[3] << 24); } /* Read red-book section 7.1.1 number (8 bit) */ /* static uint8 virt_iso_711(const uint8 *from) { return (*from & 0xff); } */ /* Read red-book section 7.3.3 number (32 bit LE / 32 bit BE) */ static uint32 virt_iso_733(const uint8 *from) { return htohl_32(from); } /* Read sectors data */ static int read_data(uint32 sector, uint32 count, void *data, isofs_t *ifs) { switch(ifs->type) { case ISOFS_IMAGE_TYPE_CSO: case ISOFS_IMAGE_TYPE_ZSO: return ciso_read_sectors(ifs->ciso, ifs->fd, data, (sector + 150) - ifs->session_base, count); case ISOFS_IMAGE_TYPE_CDI: return cdi_read_sectors(ifs->cdi, ifs->fd, data, sector, count); case ISOFS_IMAGE_TYPE_GDI: return gdi_read_sectors(ifs->gdi, data, sector, count); case ISOFS_IMAGE_TYPE_ISO: default: fs_seek(ifs->fd, (((sector + 150) - ifs->session_base) * 2048), SEEK_SET); return read_sectors_data(ifs->fd, count, 2048, data); } } #define ROOT_DIRECTORY_HORIZON 64 // TODO: CSO/ZSO static int isofile_read(file_t fd, off_t offset, size_t size, uint8 *buff) { fs_seek(fd, offset, SEEK_SET); return fs_read(fd, buff, size); } static int isofile_find_lba(isofs_t *ifs) { uint32 sec; uint8 buf1[0x22], buf2[0x22]; for (sec = 16; sec < ROOT_DIRECTORY_HORIZON; sec++) { if (isofile_read(ifs->fd, sec << 11, 6, buf1) < 0) return 150; if (!memcmp(buf1, "\001CD001", 6)) break; else if(!memcmp(buf1, "\377CD001", 6)) return 150; } if (sec >= ROOT_DIRECTORY_HORIZON) return 150; #ifdef DEBUG ds_printf("DS_ISOFS: PVD is at %d\n", sec); #endif if (isofile_read(ifs->fd, (sec << 11) + 0x9c, 0x22, buf1) < 0) return -1; while (++sec < ROOT_DIRECTORY_HORIZON) { if (!isofile_read(ifs->fd, sec << 11, 0x22, buf2)) return 150; if (!memcmp(buf1, buf2, 0x12) && !memcmp(buf1 + 0x19, buf2 + 0x19, 0x9)) break; } if (sec >= ROOT_DIRECTORY_HORIZON) return 150; #ifdef DEBUG ds_printf("DS_ISOFS: Root directory is at %d\n", sec); #endif sec = ((((((buf1[5]<<8)|buf1[4])<<8)|buf1[3])<<8)|buf1[2])+150-sec; #ifdef DEBUG ds_printf("DS_ISOFS: Session offset is %d\n", sec); #endif // ifs->session_base = sec; return sec; } /********************************************************************************/ /* Low-level block cacheing routines. This implements a simple queue-based LRU/MRU cacheing system. Whenever a block is requested, it will be placed on the MRU end of the queue. As more blocks are loaded than can fit in the cache, blocks are deleted from the LRU end. */ /* Graduate a block from its current position to the MRU end of the cache */ static void bgrad_cache(cache_block_t **cache, int block) { int i; cache_block_t *tmp; /* Don't try it with the end block */ if (block < 0 || block >= (NUM_CACHE_BLOCKS-1)) return; /* Make a copy and scoot everything down */ tmp = cache[block]; for (i=block; i<(NUM_CACHE_BLOCKS - 1); i++) cache[i] = cache[i+1]; cache[NUM_CACHE_BLOCKS-1] = tmp; } static int bread_cache(cache_block_t **cache, uint32 sector, isofs_t *ifs) { int i, j, rv; #ifdef DEBUG ds_printf("%s: %d\n", __func__, sector); #endif rv = -1; mutex_lock(&ifs->cache_mutex); /* Look for a pre-existing cache block */ for (i=NUM_CACHE_BLOCKS-1; i>=0; i--) { if (cache[i]->sector == sector) { bgrad_cache(cache, i); rv = NUM_CACHE_BLOCKS - 1; goto bread_exit; } } /* If not, look for an open cache slot; if we find one, use it */ for (i=0; i<NUM_CACHE_BLOCKS; i++) { if (cache[i]->sector == -1) break; } /* If we didn't find one, kick an LRU block out of cache */ if (i >= NUM_CACHE_BLOCKS) { i = 0; } j = read_data(sector, 1, cache[i]->data, ifs); if (j < 0) { #ifdef DEBUG ds_printf("DS_ERROR: Can't read sector %d\n", sector); #endif goto bread_exit; } cache[i]->sector = sector; /* Move it to the most-recently-used position */ bgrad_cache(cache, i); rv = NUM_CACHE_BLOCKS - 1; /* Return the new cache block index */ bread_exit: mutex_unlock(&ifs->cache_mutex); return rv; } /* read data block */ static int bdread(uint32 sector, isofs_t *ifs) { return bread_cache(ifs->dcache, sector, ifs); } /* read inode block */ static int biread(uint32 sector, isofs_t *ifs) { return bread_cache(ifs->icache, sector, ifs); } /* Clear both caches */ static void bclear(isofs_t *ifs) { int i; mutex_lock(&ifs->cache_mutex); for (i = 0; i < NUM_CACHE_BLOCKS; i++) { ifs->icache[i]->sector = -1; ifs->dcache[i]->sector = -1; } mutex_unlock(&ifs->cache_mutex); } /********************************************************************************/ /* Higher-level ISO9660 primitives */ //#define IPBIN_TOC_OFFSET 260 static int get_lba_from_mki(isofs_t *ifs) { ds_printf("DS_ISOFS: Searching MKI string...\n"); int lba = -1; int s = 17; uint8 mki[2048]; char mkisofs[256]; while(s < 25) { if(ifs->ciso != NULL) { ciso_read_sectors(ifs->ciso, ifs->fd, mki, s, 1); // } else if(ifs->cdi != NULL) { // cdi_read_sectors(ifs->cdi, ifs->fd, mki, s, 1); // } else if(ifs->gdi != NULL) { // gdi_read_sectors(ifs->gdi, mki, s, 1); } else { fs_seek(ifs->fd, s << 1, SEEK_SET); fs_read(ifs->fd, mki, sizeof(mki)); } /* MKI Mon Aug 20 14:10:58 2001 mkisofs 1.13a03 -l -C 0,11700 -V BASS2_ECH -o tmp.iso bass MKI Wed Mar 2 22:34:30 2011 mkisofs 1.15a12 -V DC_GAME -G sys/katana/IP.BIN -joliet -rock -l -o image.iso ./cd. MKI Tue Nov 20 06:14:40 2007 mkisofs 2.01-bootcd.ru -C 0,11702 -V D2_A -sort Temp_SORT.TXT -l -o DATA.ISO FILE */ if(mki[0] == 0x4D && mki[1] == 0x4B && mki[2] == 0x49 && mki[3] == 0x20) { ds_printf("DS_ISOFS: %s\n", mki); if(sscanf((char*)mki+29, "mkisofs %[^,],%d", mkisofs, &lba) > 1) { ds_printf("DS_ISOFS: Detected LBA: %d + 150\n", lba); lba += 150; break; } else { lba = 0; ds_printf("DS_ISOFS: Can't find LBA from MKI.\n"); break; } } s++; } return lba; } /* static int get_toc_and_lba(isofs_t *ifs) { uint8 ipbin[2048]; int i, lba = 150, mk = 0; if(ifs->ciso != NULL) { ciso_read_sectors(ifs->ciso, ifs->fd, ipbin, 0, 1); } else if(ifs->cdi != NULL) { cdi_get_toc(ifs->cdi, &ifs->toc); return cdrom_locate_data_track(&ifs->toc); } else if(ifs->gdi != NULL) { gdi_get_toc(ifs->gdi, &ifs->toc); return 45150; } else { fs_seek(ifs->fd, 0, SEEK_SET); if(!fs_read(ifs->fd, ipbin, 2048)) { ds_printf("DS_ERROR: Can't read IP.BIN from ISO\n"); return lba; } } if(ipbin[0x0] == 'S' && ipbin[0x1] == 'E' && ipbin[(IPBIN_TOC_OFFSET)-1] == 0x31) { memcpy_sh4(&ifs->toc, ipbin + IPBIN_TOC_OFFSET, sizeof(CDROM_TOC)); //lba = cdrom_locate_data_track(&toc) + 150; for (i = 0; i < 99; i++) { if(TOC_CTRL(ifs->toc.entry[i]) == 4) { lba = TOC_LBA(ifs->toc.entry[i]); if(lba >= 45150) { mk = get_lba_from_mki(ifs); if(mk > 150) { return mk; } else if(mk < 0) { return lba; } else { return isofile_find_lba(ifs); } } break; } } } else { mk = get_lba_from_mki(ifs); if(mk > 0) { return mk; } else { return 150; } } return lba; } */ static int get_toc_and_lba(isofs_t *ifs) { int lba = 150; switch(ifs->type) { case ISOFS_IMAGE_TYPE_CDI: cdi_get_toc(ifs->cdi, &ifs->toc); return cdrom_locate_data_track(&ifs->toc); case ISOFS_IMAGE_TYPE_GDI: gdi_get_toc(ifs->gdi, &ifs->toc); return 45150; case ISOFS_IMAGE_TYPE_CSO: case ISOFS_IMAGE_TYPE_ZSO: lba = get_lba_from_mki(ifs); if(lba <= 0) { lba = 150; // TODO: isofile_find_lba(ifs); } spoof_multi_toc_cso(&ifs->toc, ifs->ciso, lba); break; case ISOFS_IMAGE_TYPE_ISO: default: lba = get_lba_from_mki(ifs); if(lba <= 0) { lba = isofile_find_lba(ifs); } if(lba >= 45150) { spoof_multi_toc_3track_gd(&ifs->toc); } else { spoof_multi_toc_iso(&ifs->toc, ifs->fd, lba); } break; } return lba; } /* Per-disc initialization; this is done every time it's discovered that a new CD has been inserted. */ static int virt_iso_init_percd(isofs_t *ifs) { int i, blk; /* Start off with no cached blocks and no open files*/ // virt_iso_reset(ifs); ifs->session_base = get_toc_and_lba(ifs); ds_printf("DS_ISOFS: Session base: %d\n", ifs->session_base); //dbglog(DBG_DEBUG, "virt_iso_init_percd: session base = %d\n", ifs->session_base); /* Check for joliet extensions */ ifs->joliet = 0; for (i=1; i<=3; i++) { blk = biread(ifs->session_base + i + 16 - 150, ifs); if (blk < 0) return blk; if (memcmp((char *)ifs->icache[blk]->data, "\02CD001", 6) == 0) { ifs->joliet = isjoliet((char *)ifs->icache[blk]->data+88); // ds_printf("DS_ISOFS: joliet level %d extensions detected\n", ifs->joliet); if (ifs->joliet) break; } } /* If that failed, go after standard/RockRidge ISO */ if (!ifs->joliet) { /* Grab and check the volume descriptor */ blk = biread(ifs->session_base + 16 - 150, ifs); if (blk < 0) return i; if (memcmp((char*)ifs->icache[blk]->data, "\01CD001", 6)) { ds_printf("DS_ERROR: CD/GD image is not ISO9660\n"); return -1; } } /* Locate the root directory */ memcpy_sh4(&ifs->root_dirent, ifs->icache[blk]->data+156, sizeof(virt_iso_dirent_t)); ifs->root_extent = virt_iso_733(ifs->root_dirent.extent); ifs->root_size = virt_iso_733(ifs->root_dirent.size); return 0; } /* Compare an ISO9660 filename against a normal filename. This takes into account the version code on the end and is not case sensitive. Also takes into account the trailing period that some CD burning software adds. */ static int fncompare(const char *isofn, int isosize, const char *normalfn) { int i; /* Compare ISO name */ for (i=0; i<isosize; i++) { /* Weed out version codes */ if (isofn[i] == ';') break; /* Deal with crap '.' at end of filenames */ if (isofn[i] == '.' && (i == (isosize-1) || isofn[i+1] == ';')) break; /* Otherwise, compare the chars normally */ if (tolower((int)isofn[i]) != tolower((int)normalfn[i])) return -1; } /* Catch ISO name shorter than normal name */ if (normalfn[i] != '/' && normalfn[i] != '\0') return -1; else return 0; } /* Locate an ISO9660 object in the given directory; this can be a directory or a file, it works fine for either one. Pass in: fn: object filename (relative to the passed directory) dir: 0 if looking for a file, 1 if looking for a dir dir_extent: directory extent to start with dir_size: directory size (in bytes) It will return a pointer to a transient dirent buffer (i.e., don't expect this buffer to stay around much longer than the call itself). */ static virt_iso_dirent_t *find_object(const char *fn, int dir, uint32 dir_extent, uint32 dir_size, isofs_t *ifs) { int i, c; virt_iso_dirent_t *de; /* RockRidge */ int len; uint8 *pnt; char rrname[NAME_MAX]; int rrnamelen; int size_left; /* We need this to be signed for our while loop to end properly */ size_left = (int)dir_size; /* Joliet */ uint8 * ucsname = (uint8 *)rrname; /* If this is a Joliet CD, then UCSify the name */ if (ifs->joliet) utf2ucs(ucsname, (uint8 *)fn); while (size_left > 0) { c = biread(dir_extent, ifs); if (c < 0) return NULL; for (i=0; i<2048 && i<size_left; ) { /* Locate the current dirent */ de = (virt_iso_dirent_t *)(ifs->icache[c]->data + i); if (!de->length) break; /* Try the Joliet filename if the CD is a Joliet disc */ if (ifs->joliet) { if (!ucscompare((uint8 *)de->name, ucsname, de->name_len)) { if (!((dir << 1) ^ de->flags)) return de; } } else { /* Assume no Rock Ridge name */ rrnamelen = 0; /* Check for Rock Ridge NM extension */ len = de->length - sizeof(virt_iso_dirent_t) + sizeof(de->name) - de->name_len; pnt = (uint8*)de + sizeof(virt_iso_dirent_t) - sizeof(de->name) + de->name_len; if ((de->name_len & 1) == 0) { pnt++; len--; } while ((len >= 4) && ((pnt[3] == 1) || (pnt[3] == 2))) { if (strncmp((char *)pnt, "NM", 2) == 0) { rrnamelen = pnt[2] - 5; strncpy(rrname, (char *)(pnt+5), rrnamelen); rrname[rrnamelen] = 0; } len -= pnt[2]; pnt += pnt[2]; } /* Check the filename against the requested one */ if (rrnamelen > 0) { char *p = strchr(fn, '/'); int fnlen; if (p) fnlen = p - fn; else fnlen = strlen(fn); if (!strncasecmp(rrname, fn, fnlen) && ! *(rrname + fnlen)) { if (!((dir << 1) ^ de->flags)) return de; } } else { if (!fncompare(de->name, de->name_len, fn)) { if (!((dir << 1) ^ de->flags)) return de; } } } i += de->length; } dir_extent++; size_left -= 2048; } return NULL; } /* Locate an ISO9660 object anywhere on the disc, starting at the root, and expecting a fully qualified path name. This is analogous to find_object but it searches with the path in mind. fn: object filename (relative to the passed directory) dir: 0 if looking for a file, 1 if looking for a dir dir_extent: directory extent to start with dir_size: directory size (in bytes) It will return a pointer to a transient dirent buffer (i.e., don't expect this buffer to stay around much longer than the call itself). */ static virt_iso_dirent_t *find_object_path(const char *fn, int dir, virt_iso_dirent_t *start, isofs_t *ifs) { char *cur; /* If the object is in a sub-tree, traverse the trees looking for the right directory */ while ((cur = strchr(fn, '/'))) { if (cur != fn) { /* Note: trailing path parts don't matter since find_object only compares based on the FN length on the disc. */ start = find_object(fn, 1, virt_iso_733(start->extent), virt_iso_733(start->size), ifs); if (start == NULL) return NULL; } fn = cur + 1; } /* Locate the file in the resulting directory */ if (*fn) { start = find_object(fn, dir, virt_iso_733(start->extent), virt_iso_733(start->size), ifs); return start; } else { if (!dir) return NULL; else return start; } } /********************************************************************************/ /* File primitives */ /* Break all of our open file descriptor. This is necessary when the disc is changed so that we don't accidentally try to keep on doing stuff with the old info. As files are closed and re-opened, the broken flag will be cleared. */ static void virt_iso_break_all(isofs_t *ifs) { int i; mutex_lock(&fh_mutex); for (i = 0; i < MAX_ISO_FILES; i++) { if(ifs == fh[i].ifs) { fh[i].broken = 1; } } mutex_unlock(&fh_mutex); } /* Open a file or directory */ static void * virt_iso_open(vfs_handler_t * vfs, const char *fn, int mode) { file_t fd; virt_iso_dirent_t *de; isofs_t *ifs = (isofs_t *)vfs->privdata; /* Make sure they don't want to open things as writeable */ if ((mode & O_MODE_MASK) != O_RDONLY) return 0; /* Find the file we want */ de = find_object_path(fn, (mode & O_DIR)?1:0, &ifs->root_dirent, ifs); if (!de) return 0; /* Find a free file handle */ mutex_lock(&fh_mutex); for (fd=0; fd<MAX_ISO_FILES; fd++) if (fh[fd].first_extent == 0) { fh[fd].first_extent = -1; break; } mutex_unlock(&fh_mutex); if (fd >= MAX_ISO_FILES) return 0; /* Fill in the file handle and return the fd */ fh[fd].first_extent = virt_iso_733(de->extent); fh[fd].dir = (mode & O_DIR)?1:0; fh[fd].ptr = 0; fh[fd].size = virt_iso_733(de->size); fh[fd].broken = 0; fh[fd].ifs = ifs; return (void *)fd; } /* Close a file or directory */ static int virt_iso_close(void * h) { file_t fd = (file_t)h; /* Check that the fd is valid */ if (fd < MAX_ISO_FILES) { /* No need to lock the mutex: this is an atomic op */ fh[fd].first_extent = 0; } return 0; } /* Read from a file */ static ssize_t virt_iso_read(void * h, void *buf, size_t bytes) { int rv, toread, thissect, c; uint8 * outbuf; file_t fd = (file_t)h; /* Check that the fd is valid */ if (fd >= MAX_ISO_FILES || fh[fd].first_extent == 0 || fh[fd].broken) return -1; rv = 0; outbuf = (uint8 *)buf; /* Read zero or more sectors into the buffer from the current pos */ while (bytes > 0) { /* Figure out how much we still need to read */ toread = (bytes > (fh[fd].size - fh[fd].ptr)) ? fh[fd].size - fh[fd].ptr : bytes; if (toread == 0) break; /* How much more can we read in the current sector? */ thissect = 2048 - (fh[fd].ptr % 2048); /* If we're on a sector boundary and we have more than one full sector to read, then short-circuit the cache here and use the multi-sector reads from the image */ if (thissect == 2048 && toread >= 2048) { /* Round it off to an even sector count */ thissect = toread / 2048; toread = thissect * 2048; #ifdef DEBUG ds_printf("%s: Short-circuit read for %d sectors\n", __func__, thissect); #endif /* Do the read */ c = read_data(fh[fd].first_extent + fh[fd].ptr/2048, thissect, outbuf, fh[fd].ifs); if (c < 0) { return -1; } } else { toread = (toread > thissect) ? thissect : toread; // uint8 tmp[2048]; /* Do the read */ c = bdread(fh[fd].first_extent + fh[fd].ptr/2048, fh[fd].ifs); // c = read_data(fh[fd].first_extent + fh[fd].ptr/2048, 1, tmp, fh[fd].ifs) < 0) if (c < 0) { return -1; } memcpy_sh4(outbuf, fh[fd].ifs->dcache[c]->data + (fh[fd].ptr % 2048), toread); // memcpy_sh4(outbuf, tmp + (fh[fd].ptr % 2048), toread); } /* Adjust pointers */ outbuf += toread; fh[fd].ptr += toread; bytes -= toread; rv += toread; } return rv; } /* Seek elsewhere in a file */ static off_t virt_iso_seek(void * h, off_t offset, int whence) { file_t fd = (file_t)h; /* Check that the fd is valid */ if (fd>=MAX_ISO_FILES || fh[fd].first_extent==0 || fh[fd].broken) return -1; /* Update current position according to arguments */ switch (whence) { case SEEK_SET: fh[fd].ptr = offset; break; case SEEK_CUR: fh[fd].ptr += offset; break; case SEEK_END: fh[fd].ptr = fh[fd].size + offset; break; default: return -1; } /* Check bounds */ if (fh[fd].ptr < 0) fh[fd].ptr = 0; if (fh[fd].ptr > fh[fd].size) fh[fd].ptr = fh[fd].size; return fh[fd].ptr; } /* Tell where in the file we are */ static off_t virt_iso_tell(void * h) { file_t fd = (file_t)h; if (fd>=MAX_ISO_FILES || fh[fd].first_extent==0 || fh[fd].broken) return -1; return fh[fd].ptr; } /* Tell how big the file is */ static size_t virt_iso_total(void * h) { file_t fd = (file_t)h; if (fd>=MAX_ISO_FILES || fh[fd].first_extent==0 || fh[fd].broken) return -1; return fh[fd].size; } /* Helper function for readdir: post-processes an ISO filename to make it a bit prettier. */ static void fn_postprocess(char *fnin) { char * fn = fnin; while (*fn && *fn != ';') { *fn = tolower((int)*fn); fn++; } *fn = 0; /* Strip trailing dots */ if (fn > fnin && fn[-1] == '.') { fn[-1] = 0; } } /* Read a directory entry */ static dirent_t *virt_iso_readdir(void * h) { int c; virt_iso_dirent_t *de; /* RockRidge */ int len; uint8 *pnt; file_t fd = (file_t)h; if (fd>=MAX_ISO_FILES || fh[fd].first_extent==0 || !fh[fd].dir || fh[fd].broken) return NULL; /* Scan forwards until we find the next valid entry, an end-of-entry mark, or run out of dir size. */ c = -1; de = NULL; while(fh[fd].ptr < fh[fd].size) { /* Get the current dirent block */ c = biread(fh[fd].first_extent + fh[fd].ptr/2048, fh[fd].ifs); if (c < 0) return NULL; de = (virt_iso_dirent_t *)(fh[fd].ifs->icache[c]->data + (fh[fd].ptr%2048)); if (de->length) break; /* Skip to the next sector */ fh[fd].ptr += 2048 - (fh[fd].ptr%2048); } if (fh[fd].ptr >= fh[fd].size) return NULL; /* If we're at the first, skip the two blank entries */ if (!de->name[0] && de->name_len == 1) { fh[fd].ptr += de->length; de = (virt_iso_dirent_t *)(fh[fd].ifs->icache[c]->data + (fh[fd].ptr%2048)); fh[fd].ptr += de->length; de = (virt_iso_dirent_t *)(fh[fd].ifs->icache[c]->data + (fh[fd].ptr%2048)); if (!de->length) return NULL; } if (fh[fd].ifs->joliet) { ucs2utfn((uint8 *)fh[fd].dirent.name, (uint8 *)de->name, de->name_len); } else { /* Fill out the VFS dirent */ strncpy(fh[fd].dirent.name, de->name, de->name_len); fh[fd].dirent.name[de->name_len] = 0; fn_postprocess(fh[fd].dirent.name); /* Check for Rock Ridge NM extension */ len = de->length - sizeof(virt_iso_dirent_t) + sizeof(de->name) - de->name_len; pnt = (uint8*)de + sizeof(virt_iso_dirent_t) - sizeof(de->name) + de->name_len; if ((de->name_len & 1) == 0) { pnt++; len--; } while ((len >= 4) && ((pnt[3] == 1) || (pnt[3] == 2))) { if (strncmp((char *)pnt, "NM", 2) == 0) { strncpy(fh[fd].dirent.name, (char *)(pnt+5), pnt[2] - 5); fh[fd].dirent.name[pnt[2] - 5] = 0; } len -= pnt[2]; pnt += pnt[2]; } } if (de->flags & 2) { fh[fd].dirent.size = -1; fh[fd].dirent.attr = O_DIR; } else { fh[fd].dirent.size = virt_iso_733(de->size); fh[fd].dirent.attr = 0; } fh[fd].ptr += de->length; return &fh[fd].dirent; } static int virt_iso_rewinddir(void * h) { file_t fd = (file_t)h; if(fd >= MAX_ISO_FILES || fh[fd].first_extent == 0 || !fh[fd].dir || fh[fd].broken) { errno = EBADF; return -1; } /* Rewind to the beginning of the directory. */ fh[fd].ptr = 0; return 0; } static int virt_iso_reset(isofs_t *ifs) { virt_iso_break_all(ifs); bclear(ifs); return 0; } /** * Needed for isoldr module */ static int virt_iso_ioctl(void * hnd, int cmd, va_list ap) { file_t fd = (file_t)hnd; #ifdef DEBUG ds_printf("%s: %d\n", __func__, cmd); #endif void *data = va_arg(ap, void *); switch(cmd) { case ISOFS_IOCTL_RESET: virt_iso_reset(fh[fd].ifs); break; case ISOFS_IOCTL_GET_FD_LBA: memcpy_sh4(data, &fh[fd].first_extent, sizeof(uint32)); break; case ISOFS_IOCTL_GET_DATA_TRACK_FILENAME: { if(fh[fd].ifs->gdi != NULL) { GDI_track_t *trk = gdi_get_track(fh[fd].ifs->gdi, fh[fd].ifs->session_base - 150); memcpy_sh4(data, trk->filename, sizeof(trk->filename)); } else { return -1; } break; } case ISOFS_IOCTL_GET_DATA_TRACK_FILENAME2: { if(fh[fd].ifs->gdi != NULL) { GDI_track_t *trk = gdi_get_track(fh[fd].ifs->gdi, fh[fd].first_extent); char *p = strrchr(trk->filename, '/'); char *fn = (char*)data; strncpy(fn, p + 1, 11); fn[11] = 0; } else { return -1; } break; } case ISOFS_IOCTL_GET_DATA_TRACK_LBA: memcpy_sh4(data, &fh[fd].ifs->session_base, sizeof(uint32)); break; case ISOFS_IOCTL_GET_DATA_TRACK_LBA2: { if(fh[fd].ifs->gdi != NULL) { GDI_track_t *trk = gdi_get_track(fh[fd].ifs->gdi, fh[fd].first_extent); uint32 lba = trk->start_lba + 150; memcpy_sh4(data, &lba, sizeof(uint32)); } else { return -1; } break; } case ISOFS_IOCTL_GET_DATA_TRACK_OFFSET: { memset_sh4(data, 0, sizeof(uint32)); if(fh[fd].ifs->cdi != NULL) { uint16 ssz = 0; uint32 offset = cdi_get_offset(fh[fd].ifs->cdi, fh[fd].ifs->session_base - 150, &ssz); memcpy_sh4(data, &offset, sizeof(uint32)); } break; } case ISOFS_IOCTL_GET_DATA_TRACK_SECTOR_SIZE: { uint32 sec_size; if(fh[fd].ifs->cdi != NULL) { CDI_track_t *ctrk = cdi_get_track(fh[fd].ifs->cdi, fh[fd].ifs->session_base - 150); sec_size = cdi_track_sector_size(ctrk); } else if(fh[fd].ifs->gdi != NULL) { GDI_track_t *gtrk = gdi_get_track(fh[fd].ifs->gdi, fh[fd].ifs->session_base - 150); sec_size = gdi_track_sector_size(gtrk); } else { sec_size = 2048; } memcpy_sh4(data, &sec_size, sizeof(sec_size)); break; } case ISOFS_IOCTL_GET_IMAGE_TYPE: { memcpy_sh4(data, &fh[fd].ifs->type, sizeof(uint32)); break; } case ISOFS_IOCTL_GET_IMAGE_HEADER_PTR: { uint32 lnk = 0; if(fh[fd].ifs->cdi != NULL) { lnk = (uint32)fh[fd].ifs->cdi; } else if(fh[fd].ifs->gdi != NULL) { lnk = (uint32)fh[fd].ifs->gdi; } else if(fh[fd].ifs->ciso != NULL) { lnk = (uint32)fh[fd].ifs->ciso; } else { return -1; } memcpy_sh4(data, &lnk, sizeof(uint32)); break; } case ISOFS_IOCTL_GET_IMAGE_FD: { memcpy_sh4(data, &fh[fd].ifs->fd, sizeof(uint32)); break; } case ISOFS_IOCTL_GET_TOC_DATA: memcpy_sh4(data, &fh[fd].ifs->toc, sizeof(CDROM_TOC)); break; case ISOFS_IOCTL_GET_BOOT_SECTOR_DATA: { if(read_data(fh[fd].ifs->session_base - 150, 1, data, fh[fd].ifs) < 0) { return -1; } break; } case ISOFS_IOCTL_GET_CDDA_OFFSET: { if(fh[fd].ifs->cdi == NULL) { return -1; } uint32 *offset = (uint32 *)data; uint16 ssz = 0; int i; for(i = 2; i < 99; i++) { if(fh[fd].ifs->toc.entry[i] == (uint32)-1) break; if(TOC_CTRL(fh[fd].ifs->toc.entry[i]) == 0) { offset[i] = cdi_get_offset(fh[fd].ifs->cdi, TOC_LBA(fh[fd].ifs->toc.entry[i]), &ssz); } } break; } case ISOFS_IOCTL_GET_TRACK_SECTOR_COUNT: { uint32 val = *(uint32*)data; uint32 sec_size = 2048; if(!val) { val = fh[fd].ifs->session_base - 150; } else { val -= 150; } if(fh[fd].ifs->cdi != NULL) { CDI_track_t *ctrk = cdi_get_track(fh[fd].ifs->cdi, val); sec_size = cdi_track_sector_size(ctrk); val = ctrk->total_length / sec_size; } else if(fh[fd].ifs->gdi != NULL) { GDI_track_t *gtrk = gdi_get_track(fh[fd].ifs->gdi, val); sec_size = gdi_track_sector_size(gtrk); val = fs_total(fh[fd].ifs->gdi->track_fd) / sec_size; } else if(fh[fd].ifs->ciso != NULL) { val = fh[fd].ifs->ciso->total_bytes / fh[fd].ifs->ciso->block_size; } else { val = fs_total(fh[fd].ifs->fd) / sec_size; } memcpy_sh4(data, &val, sizeof(uint32)); break; } default: return -1; } return 0; } static int virt_iso_fcntl(void *h, int cmd, va_list ap) { file_t fd = (file_t)h; int rv = -1; (void)ap; if(fd >= MAX_ISO_FILES || !fh[fd].first_extent || fh[fd].broken) { errno = EBADF; return -1; } switch(cmd) { case F_GETFL: rv = O_RDONLY; if(fh[fd].dir) rv |= O_DIR; break; case F_SETFL: case F_GETFD: case F_SETFD: rv = 0; break; default: errno = EINVAL; } return rv; } static int virt_iso_fstat(void *h, struct stat *st) { file_t fd = (file_t)h; if(fd >= MAX_ISO_FILES || !fh[fd].first_extent || fh[fd].broken) { errno = EBADF; return -1; } memset(st, 0, sizeof(struct stat)); if(fh[fd].dir) { st->st_size = 0; st->st_dev = 'c' | ('d' << 8); st->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH; st->st_nlink = 1; st->st_blksize = 2048; } else { st->st_size = fh[fd].size; st->st_dev = 'c' | ('d' << 8); st->st_mode = S_IFREG | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH; st->st_nlink = 1; st->st_blksize = 2048; } return 0; } /* Put everything together */ static vfs_handler_t vh = { /* Name handler */ { { 0 }, /* name */ 0, /* tbfi */ 0x00010000, /* Version 1.0 */ 0, /* flags */ NMMGR_TYPE_VFS, /* VFS handler */ NMMGR_LIST_INIT }, 0, NULL, /* no cacheing, privdata */ virt_iso_open, virt_iso_close, virt_iso_read, NULL, /* write XXX */ virt_iso_seek, virt_iso_tell, virt_iso_total, virt_iso_readdir, virt_iso_ioctl, NULL, /* rename XXX */ NULL, /* unlink XXX */ NULL, /* mmap XXX */ NULL, /* complete */ NULL, /* stat XXX */ NULL, /* mkdir XXX */ NULL, /* rmdir XXX */ virt_iso_fcntl, NULL, /* poll */ NULL, /* link */ NULL, /* symlink */ NULL, /* seek64 */ NULL, /* tell64 */ NULL, /* total64 */ NULL, /* readlink */ virt_iso_rewinddir, virt_iso_fstat }; /* Initialize the file system */ int fs_iso_init() { if(inited) { return 0; } /* Reset fd's */ memset(fh, 0, sizeof(fh)); /* Mark the first as active so we can have an error FD of zero */ fh[0].first_extent = -1; SLIST_INIT(&virt_iso_list); mutex_init(&fh_mutex, MUTEX_TYPE_NORMAL); inited = 1; return 0; } /* De-init the file system */ int fs_iso_shutdown() { if(!inited) { return 0; } isofs_t *c, *n; int i; mutex_lock(&fh_mutex); c = SLIST_FIRST(&virt_iso_list); while(c) { n = SLIST_NEXT(c, list); nmmgr_handler_remove(&c->vfs->nmmgr); if(c->ciso != NULL) { ciso_close(c->ciso); } if(c->cdi != NULL) { cdi_close(c->cdi); } if(c->gdi != NULL) { gdi_close(c->gdi); } fs_close(c->fd); /* Dealloc cache block space */ mutex_lock(&c->cache_mutex); for(i = 0; i < NUM_CACHE_BLOCKS; i++) { free(c->icache[i]); free(c->dcache[i]); } mutex_unlock(&c->cache_mutex); mutex_destroy(&c->cache_mutex); free(c->vfs); free(c); c = n; } SLIST_INIT(&virt_iso_list); inited = 0; mutex_unlock(&fh_mutex); mutex_destroy(&fh_mutex); return 0; } int fs_iso_mount(const char *mountpoint, const char *filename) { isofs_t *ifs; vfs_handler_t *vfs; file_t fd; int i; if(mountpoint == NULL) { return -1; } fd = fs_open(filename, O_RDONLY); if(fd < 0) { return -1; } vfs = (vfs_handler_t*) malloc(sizeof(vfs_handler_t)); if(vfs == NULL) { fs_close(fd); return -1; } ifs = (isofs_t*) malloc(sizeof(isofs_t)); if(ifs == NULL) { fs_close(fd); free(vfs); return -1; } memcpy_sh4(vfs, &vh, sizeof(vfs_handler_t)); strncpy(vfs->nmmgr.pathname, mountpoint, NAME_MAX); vfs->privdata = (void*)ifs; memset_sh4(ifs, 0, sizeof(isofs_t)); ifs->fd = fd; ifs->vfs = vfs; ifs->ciso = ciso_open(fd); if(ifs->ciso != NULL) { switch(ifs->ciso->magic[0]) { case 'Z': ifs->type = ISOFS_IMAGE_TYPE_ZSO; break; case 'C': default: ifs->type = ISOFS_IMAGE_TYPE_CSO; break; } } else { ifs->cdi = cdi_open(fd); if(ifs->cdi != NULL) { ifs->type = ISOFS_IMAGE_TYPE_CDI; } else { ifs->gdi = gdi_open(fd, filename); if(ifs->gdi != NULL) { ifs->type = ISOFS_IMAGE_TYPE_GDI; } else { ifs->type = ISOFS_IMAGE_TYPE_ISO; } } } ifs->session_base = 0; /* Allocate cache block space */ for (i = 0; i < NUM_CACHE_BLOCKS; i++) { ifs->icache[i] = malloc(sizeof(cache_block_t)); ifs->icache[i]->sector = -1; ifs->dcache[i] = malloc(sizeof(cache_block_t)); ifs->dcache[i]->sector = -1; } mutex_init(&ifs->cache_mutex, MUTEX_TYPE_DEFAULT); if(virt_iso_init_percd(ifs) < 0) { if(ifs->ciso != NULL) { ciso_close(ifs->ciso); } if(ifs->cdi != NULL) { cdi_close(ifs->cdi); } if(ifs->gdi != NULL) { gdi_close(ifs->gdi); } fs_close(fd); free(ifs->vfs); /* Dealloc cache block space */ for (i = 0; i < NUM_CACHE_BLOCKS; i++) { free(ifs->icache[i]); free(ifs->dcache[i]); } mutex_destroy(&ifs->cache_mutex); free(ifs); return -1; } mutex_lock(&fh_mutex); SLIST_INSERT_HEAD(&virt_iso_list, ifs, list); nmmgr_handler_add(&ifs->vfs->nmmgr); // TODO check for errors mutex_unlock(&fh_mutex); #ifdef DEBUG ds_printf("DS_ISOFS: Mounted %s\n", mountpoint); #endif return 0; } int fs_iso_unmount(const char *mountpoint) { isofs_t *n; int i; if(mountpoint == NULL) { return -1; } mutex_lock(&fh_mutex); SLIST_FOREACH(n, &virt_iso_list, list) { if (!strncasecmp(mountpoint, n->vfs->nmmgr.pathname, NAME_MAX)) { nmmgr_handler_remove(&n->vfs->nmmgr); // TODO check for errors free(n->vfs); if(n->ciso != NULL) { ciso_close(n->ciso); } if(n->cdi != NULL) { cdi_close(n->cdi); } if(n->gdi != NULL) { gdi_close(n->gdi); } fs_close(n->fd); /* Dealloc cache block space */ mutex_lock(&n->cache_mutex); for (i = 0; i < NUM_CACHE_BLOCKS; i++) { free(n->icache[i]); free(n->dcache[i]); } mutex_unlock(&n->cache_mutex); mutex_destroy(&n->cache_mutex); SLIST_REMOVE(&virt_iso_list, n, isofs, list); free(n); #ifdef DEBUG ds_printf("DS_ISOFS: Unmounted %s\n", mountpoint); #endif mutex_unlock(&fh_mutex); return 0; } } mutex_unlock(&fh_mutex); return -1; } <file_sep>/sdk/bin/src/wav2adpcm/Makefile # Makefile for the wav2adpcm program. ifeq ($(LBITS),64) INCS = -I/usr/include/x86_64-linux-gnu -I/usr/include/$(gcc -print-multiarch) LIBS = -L/usr/lib32 CC = gcc -m32 $(INCS) LD = gcc -m32 $(LIBS) else CC = gcc LD = gcc endif CFLAGS = -O2 -Wall INSTALL = install DESTDIR = ../.. all: wav2adpcm install : wav2adpcm $(INSTALL) -m 755 wav2adpcm $(DESTDIR)/wav2adpcm run : wav2adpcm @./wav2adpcm pcm.wav adpcm.wav clean: rm -rf *.o rm -rf wav2adpcm <file_sep>/firmware/aica/codec/keys.c /* from http://www.mikrocontroller.net/topic/48465 */ #include "AT91SAM7S64.h" #include "Board.h" #include "keys.h" #include "interrupt_utils.h" #include <stdio.h> #define KEY_INPUT (*AT91C_PIOA_PDSR) #define REPEAT_MASK (1<<KEY1) // repeat: key1 #define REPEAT_START 50 // * 10ms #define REPEAT_NEXT 22 // * 10ms volatile unsigned long key_state; // debounced and inverted key state: // bit = 1: key pressed volatile unsigned long key_press; // key press detect volatile unsigned long key_rpt; // key long press and repeat void process_keys(void) // every 10ms { static unsigned long ct0, ct1, rpt; unsigned long i; i = key_state ^ ~KEY_INPUT; // key changed ? ct0 = ~( ct0 & i ); // reset or count ct0 ct1 = ct0 ^ (ct1 & i); // reset or count ct1 i &= ct0 & ct1; // count until roll over ? key_state ^= i; // then toggle debounced state key_press |= key_state & i; // 0->1: key press detect if( (key_state & REPEAT_MASK) == 0 ) // check repeat function rpt = REPEAT_START; // start delay if( --rpt == 0 ){ rpt = REPEAT_NEXT; // repeat delay key_rpt |= key_state & REPEAT_MASK; } } long get_key_press( long key_mask ) { unsigned state; state = disableIRQ(); key_mask &= key_press; // read key(s) key_press ^= key_mask; // clear key(s) restoreIRQ(state); return key_mask; } long get_key_rpt( long key_mask ) { unsigned state; state = disableIRQ(); key_mask &= key_rpt; // read key(s) key_rpt ^= key_mask; // clear key(s) restoreIRQ(state); return key_mask; } long get_key_short( long key_mask ) { long x; unsigned state; state = disableIRQ(); x = get_key_press( ~key_state & key_mask ); restoreIRQ(state); return x; } long get_key_long( long key_mask ) { return get_key_press( get_key_rpt( key_mask )); } void key_init(void) { // enable PIO *AT91C_PIOA_PER = (1<<KEY0)|(1<<KEY1); // disable output *AT91C_PIOA_ODR = (1<<KEY0)|(1<<KEY1); } <file_sep>/include/plx/sprite.h /* Parallax for KallistiOS ##version## sprite.h (c)2002 <NAME> */ #ifndef __PARALLAX_SPRITE #define __PARALLAX_SPRITE #include <sys/cdefs.h> __BEGIN_DECLS /** \file Here we define the basic sprite functions. These, like the primitive functions, are all inlined for speed (and DR usability). A sprite is basically just a quad. There are two axes of variation here, like in the primitives: - Whether you use DR or plx_prim for submission - Whether you use the matrix math for special effects Each function asks for the width and height of the quad, which allows you to either pass in the texture's width and height for a raw sprite, or scale the values for easy scaling without any matrix math. Full matrix math will allow for 3D usage, rotations, etc. All sprite quads are assumed to be textured (though of course you can submit quads with u/v values without using a texture, in which case it will be ignored by the hardware). It is also assumed that you have already submitted the polygon header for the given texture. Like the primitives, each function has a suffix that describes its function. The first letter is f or i, for float or integer color values. The second value is n for no matrix or m for matrix. The third is whether it uses DR (d) or plx_prim (p). If you need anything more complex (like custom u/v coords) then do it manually using the plx_vert_* functions. */ #include "prim.h" #include "texture.h" #include "matrix.h" /********************************************************* DR VERSIONS ***/ /** Submit a quad using the given coordinates, color, and UV values via DR. The coordinates are at the center point. */ static inline void plx_spr_fnd(plx_dr_state_t * state, float wi, float hi, float x, float y, float z, float a, float r, float g, float b) { float w = wi / 2.0f; float h = hi / 2.0f; plx_vert_ffd(state, PLX_VERT, x - w, y + h, z, a, r, g, b, 0.0f, 1.0f); plx_vert_ffd(state, PLX_VERT, x - w, y - h, z, a, r, g, b, 0.0f, 0.0f); plx_vert_ffd(state, PLX_VERT, x + w, y + h, z, a, r, g, b, 1.0f, 1.0f); plx_vert_ffd(state, PLX_VERT_EOS, x + w, y - h, z, a, r, g, b, 1.0f, 0.0f); } /** Like plx_spr_fnd, but with integer color. */ static inline void plx_spr_ind(plx_dr_state_t * state, float wi, float hi, float x, float y, float z, uint32 color) { float w = wi / 2.0f; float h = hi / 2.0f; plx_vert_ifd(state, PLX_VERT, x - w, y + h, z, color, 0.0f, 1.0f); plx_vert_ifd(state, PLX_VERT, x - w, y - h, z, color, 0.0f, 0.0f); plx_vert_ifd(state, PLX_VERT, x + w, y + h, z, color, 1.0f, 1.0f); plx_vert_ifd(state, PLX_VERT_EOS, x + w, y - h, z, color, 1.0f, 0.0f); } /** Like plx_spr_fnd, but using matrix math. */ static inline void plx_spr_fmd(plx_dr_state_t * state, float wi, float hi, float xi, float yi, float zi, float a, float r, float g, float b) { float w = wi / 2.0f; float h = hi / 2.0f; float x, y, z; x = xi-w; y = yi+h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ffd(state, PLX_VERT, x, y, z, a, r, g, b, 0.0f, 1.0f); x = xi-w; y = yi-h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ffd(state, PLX_VERT, x, y, z, a, r, g, b, 0.0f, 0.0f); x = xi+w; y = yi+h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ffd(state, PLX_VERT, x, y, z, a, r, g, b, 1.0f, 1.0f); x = xi+w; y = yi-h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ffd(state, PLX_VERT_EOS, x, y, z, a, r, g, b, 1.0f, 0.0f); } /** Like plx_spr_fmd, but using integer colors. */ static inline void plx_spr_imd(plx_dr_state_t * state, float wi, float hi, float xi, float yi, float zi, uint32 color) { float w = wi / 2.0f; float h = hi / 2.0f; float x, y, z; x = xi-w; y = yi+h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ifd(state, PLX_VERT, x, y, z, color, 0.0f, 1.0f); x = xi-w; y = yi-h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ifd(state, PLX_VERT, x, y, z, color, 0.0f, 0.0f); x = xi+w; y = yi+h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ifd(state, PLX_VERT, x, y, z, color, 1.0f, 1.0f); x = xi+w; y = yi-h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ifd(state, PLX_VERT_EOS, x, y, z, color, 1.0f, 0.0f); } /**************************************************** PVR_PRIM VERSIONS ***/ /** Like plx_spr_fnd, but using pvr_prim. */ static inline void plx_spr_fnp( float wi, float hi, float x, float y, float z, float a, float r, float g, float b) { float w = wi / 2.0f; float h = hi / 2.0f; plx_vert_ffp(PLX_VERT, x - w, y + h, z, a, r, g, b, 0.0f, 1.0f); plx_vert_ffp(PLX_VERT, x - w, y - h, z, a, r, g, b, 0.0f, 0.0f); plx_vert_ffp(PLX_VERT, x + w, y + h, z, a, r, g, b, 1.0f, 1.0f); plx_vert_ffp(PLX_VERT_EOS, x + w, y - h, z, a, r, g, b, 1.0f, 0.0f); } /** Like plx_spr_ind, but using pvr_prim. */ static inline void plx_spr_inp( float wi, float hi, float x, float y, float z, uint32 color) { float w = wi / 2.0f; float h = hi / 2.0f; plx_vert_ifp(PLX_VERT, x - w, y + h, z, color, 0.0f, 1.0f); plx_vert_ifp(PLX_VERT, x - w, y - h, z, color, 0.0f, 0.0f); plx_vert_ifp(PLX_VERT, x + w, y + h, z, color, 1.0f, 1.0f); plx_vert_ifp(PLX_VERT_EOS, x + w, y - h, z, color, 1.0f, 0.0f); } /** Like plx_spr_fmd, but using pvr_prim. */ static inline void plx_spr_fmp( float wi, float hi, float xi, float yi, float zi, float a, float r, float g, float b) { float w = wi / 2.0f; float h = hi / 2.0f; float x, y, z; x = xi-w; y = yi+h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ffp(PLX_VERT, x, y, z, a, r, g, b, 0.0f, 1.0f); x = xi-w; y = yi-h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ffp(PLX_VERT, x, y, z, a, r, g, b, 0.0f, 0.0f); x = xi+w; y = yi+h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ffp(PLX_VERT, x, y, z, a, r, g, b, 1.0f, 1.0f); x = xi+w; y = yi-h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ffp(PLX_VERT_EOS, x, y, z, a, r, g, b, 1.0f, 0.0f); } /** Like plx_spr_imd, but using pvr_prim. */ static inline void plx_spr_imp( float wi, float hi, float xi, float yi, float zi, uint32 color) { float w = wi / 2.0f; float h = hi / 2.0f; float x, y, z; x = xi-w; y = yi+h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ifp(PLX_VERT, x, y, z, color, 0.0f, 1.0f); x = xi-w; y = yi-h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ifp(PLX_VERT, x, y, z, color, 0.0f, 0.0f); x = xi+w; y = yi+h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ifp(PLX_VERT, x, y, z, color, 1.0f, 1.0f); x = xi+w; y = yi-h; z = zi; plx_mat_tfip_2d(x, y, z); plx_vert_ifp(PLX_VERT_EOS, x, y, z, color, 1.0f, 0.0f); } __END_DECLS #endif /* __PARALLAX_SPRITE */ <file_sep>/commands/vmu/main.c /* DreamShell ##version## vmu.c Copyright (C) 2009-2016 SWAT */ #include "ds.h" const static unsigned short DS_pal[16]= { 0xF000,0xF655,0xF300,0xFECC,0xFCBB,0xF443,0xFA99,0xF222, 0xFA88,0xF500,0xF988,0xF100,0xF877,0xF844,0xF700,0xF500 }; const static unsigned char DS_data[32*32/2]= { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x22,0xB0,0x00,0x00,0x00,0x55,0x5B,0x00,0x00,0xB1,0x17,0x00,0x00,0x00,0x00,0x00, 0xB2,0x22,0x22,0xB0,0x05,0x38,0x63,0x10,0x05,0x3A,0xC4,0x50,0x00,0x00,0x00,0x00, 0x00,0x00,0xB2,0x29,0x25,0x40,0x07,0x37,0x04,0x10,0x00,0x00,0x00,0x00,0x00,0x00, 0x22,0x22,0x22,0x22,0xFD,0x4E,0x92,0x88,0x04,0xCB,0xBB,0xBB,0xB0,0x00,0x00,0x00, 0x00,0xBB,0xBB,0xBB,0xB5,0x42,0x9F,0x14,0x2D,0x34,0xC9,0x22,0x99,0x92,0x22,0x22, 0x00,0x00,0x00,0x00,0x05,0x40,0x00,0x14,0xBB,0x91,0x43,0x52,0x22,0x99,0x92,0x22, 0x00,0x00,0x00,0x00,0x05,0x40,0x00,0xC6,0x00,0x00,0xBA,0x42,0x22,0x22,0x22,0x22, 0x00,0x00,0x00,0x00,0x05,0x40,0x00,0x35,0x00,0x00,0x01,0x40,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x05,0x31,0x14,0xA0,0x06,0x15,0x13,0x50,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x0B,0x1C,0xC5,0x00,0x05,0xC6,0xA7,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }; int main(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s option args...\n\n" "Options: \n" " -c, --convert -Convert file\n" " -d, --dump -Dump VMU\n", argv[0]); ds_printf(" -r, --restore -Restore dump\n" " -s, --size -Set VMU size(in blocks)\n" " -p, --printinfo -Print VMU info\n\n"); ds_printf("Arguments: \n" " -a, --address -VMU address\n" " -n, --normal -Convert to normal file\n" " -v, --vmu -Convert to VMU file\n"); ds_printf(" -i, --info -VMU file description\n" " -f, --file -In file\n" " -o, --out -Out file\n\n"); ds_printf("Examples: %s -c -v -f /cd/file.txt -o /vmu/a1/DSFILE00.DSV -i Test vmu file\n" " %s --convert --normal --file /vmu/a1/DSFILE00.DSV --out /ram/file.txt\n" " %s -d -a A1 -o /ram/dump.vmd\n" " %s --restore --address A1 --file /ram/dump.vmd\n" " %s -p -s 240\n", argv[0], argv[0], argv[0], argv[0], argv[0]); return CMD_NO_ARG; } int port, unit, i, siz; maple_device_t *dev = NULL; uint8 *vmdata; file_t f; file_t fd; int convert = 0, dump = 0, restore = 0, normal = 0, vmu = 0, printinf = 0; int vmsize = 0; char *file = NULL, *out = NULL, *addr = NULL, **preinfo = NULL; struct cfg_option options[] = { {"convert", 'c', NULL, CFG_BOOL, (void *) &convert, 0}, {"dump", 'd', NULL, CFG_BOOL, (void *) &dump, 0}, {"restore", 'r', NULL, CFG_BOOL, (void *) &restore, 0}, {"printinfo", 'p', NULL, CFG_BOOL, (void *) &printinf, 0}, {"size", 's', NULL, CFG_INT, (void *) &vmsize, 0}, {"address", 'a', NULL, CFG_STR, (void *) &addr, 0}, {"normal", 'n', NULL, CFG_BOOL, (void *) &normal, 0}, {"vmu", 'v', NULL, CFG_BOOL, (void *) &normal, 0}, {"info", 'i', NULL, CFG_STR+CFG_MULTI+CFG_LEFTOVER_ARGS, (void *) &preinfo, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, {"out", 'o', NULL, CFG_STR, (void *) &out, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(dump || restore || vmsize > 0) { if(addr == NULL) { ds_printf("DS_ERROR: Too few arguments. (VMU address)\n"); return CMD_NO_ARG; } port = addr[0] - 'A'; unit = addr[1] - '0'; dev = maple_enum_dev(port, unit); if (!dev || !(dev->info.functions & MAPLE_FUNC_MEMCARD)) { ds_printf("DS_ERROR: No device, or device not a VMU\n"); return CMD_ERROR; } } if(printinf || vmsize > 0) { vmu_root_t vmroot; memset(&vmroot, 0, sizeof(vmu_root_t)); vmufs_root_read(dev, &vmroot); if(printinf) { ds_printf("\n VMU (%s) Info: \n\n" " Type: %s\n" " FAT location: %d\n" " FAT size in blocks: %d\n" " Directory location: %d\n" " Directory size in blocks: %d\n" " Icon shape for this VMS: %d\n" " Number of user blocks: %d\n", addr, vmroot.use_custom ? "custom" : "standard", vmroot.fat_loc, vmroot.fat_size, vmroot.dir_loc, vmroot.dir_size, vmroot.icon_shape, vmroot.blk_cnt); } if(vmsize > 0) { ds_printf("%sDS_PROCESS: Current size %d blocks, set to %d blocks...\n", printinf ? "\n" : "", (int)vmroot.blk_cnt, vmsize); vmroot.blk_cnt = (uint16)vmsize; vmufs_root_write(dev, &vmroot); } } if(dump) { if(out == NULL) { ds_printf("DS_ERROR: Too few arguments. (out file)\n"); return CMD_NO_ARG; } f = fs_open(out, O_WRONLY | O_CREAT | O_TRUNC); if(f < 0) { ds_printf("DS_ERROR: Can't open %s", out); return CMD_ERROR; } vmdata = (uint8 *) malloc(512); memset(vmdata, 0, 512); ds_printf("DS_PROCESS: %s dumping...\n", addr); for (i = 0; i < 256; i++) { if (vmu_block_read(dev, i, vmdata) < 0) { ds_printf("DS_ERROR: Failed to read block %d\n", i); fs_close(f); free(vmdata); return CMD_ERROR; } fs_write(f, vmdata, 512); } fs_close(f); free(vmdata); ds_printf("DS_OK: Dumping complete.\n"); return CMD_OK; } if(restore) { if(file == NULL) { ds_printf("DS_ERROR: Too few arguments. (file)\n"); return CMD_NO_ARG; } f = fs_open(file, O_RDONLY); if(f < 0) { ds_printf("DS_ERROR: Can't open %s", file); return CMD_ERROR; } vmdata = (uint8 *) malloc(512); memset(vmdata, 0, 512); i = 0; ds_printf("DS_PROCESS: Restore %s to %s...\n", file, addr); while((siz = fs_read(f, vmdata, 512)) > 0) { if(vmu_block_write(dev, i, vmdata) < 0) { ds_printf("DS_ERROR: Failed to write block %d\n", i); fs_close(f); free(vmdata); return CMD_ERROR; } i++; } fs_close(f); free(vmdata); ds_printf("DS_OK: Restore complete.\n"); return CMD_OK; } if(convert) { uint8 *pkg_out; vmu_pkg_t pkg; int pkg_size; char info[32]; if(out == NULL || file == NULL) { ds_printf("DS_ERROR: Too few arguments. \n"); return CMD_NO_ARG; } f = fs_open(file, O_RDONLY); if(f < 0) { ds_printf("DS_ERROR: Can't open %s\n", file); return CMD_ERROR; } fd = fs_open(out, O_CREAT | O_WRONLY); if(fd < 0) { ds_printf("DS_ERROR: Can't open %s\n", out); return CMD_ERROR; } siz = fs_total(f); vmdata = (uint8 *) malloc(siz); fs_read(f, vmdata, siz); fs_close(f); if(vmu) { ds_printf("DS_PROCESS: Convert %s to VMU file...\n", file); strcpy(pkg.desc_short, "DreamShell File"); memset(info, 0, sizeof(info)); if(preinfo == NULL) { strcpy(pkg.desc_long, "No description"); } else { strcpy(info, preinfo[0]); strcat(info, " "); for(i = 1; preinfo[i]; i++) { strcat(info, preinfo[i]); strcat(info, " "); } strcpy(pkg.desc_long, info); } strcpy(pkg.app_id, "DreamShell File"); pkg.icon_cnt = 1; pkg.icon_anim_speed = 0; memcpy(pkg.icon_pal, DS_pal, 32); pkg.icon_data = DS_data; pkg.eyecatch_type = VMUPKG_EC_16BIT; //VMUPKG_EC_NONE; pkg.data_len = siz; pkg.data = vmdata; vmu_pkg_build(&pkg, &pkg_out, &pkg_size); fs_unlink(out); fs_write(fd, pkg_out, pkg_size); fs_close(fd); free(vmdata); free(pkg_out); return CMD_OK; } if(normal) { ds_printf("DS_PROCESS: Convert %s to normal file...\n", file); vmu_pkg_parse(vmdata, &pkg); fs_write(fd, pkg.data, pkg.data_len); fs_close(fd); free(vmdata); return CMD_OK; } ds_printf("DS_ERROR: Too few arguments. (convert to?)\n"); return CMD_OK; } if(!printinf || vmsize == 0) { ds_printf("DS_ERROR: There is no option.\n"); } return CMD_OK; } <file_sep>/lib/lua/src/Makefile # makefile for building Lua # see ../INSTALL for installation instructions # see ../Makefile and luaconf.h for further customization # == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT ======================= # Your platform. See PLATS for possible values. PLAT= posix CC= sh-elf-gcc CFLAGS= $(KOS_CFLAGS) AR= sh-elf-ar rcu RANLIB= sh-elf-ranlib RM= rm -f LIBS= $(KOS_LIBS) MYCFLAGS= $(KOS_CFLAGS) MYLDFLAGS= $(KOS_LDFLAGS) MYLIBS= $(KOS_LIBS) # == END OF USER SETTINGS. NO NEED TO CHANGE ANYTHING BELOW THIS LINE ========= PLATS= aix ansi bsd freebsd generic linux macosx mingw posix solaris LUA_A= ../../liblua_5.1.4-2.a CORE_O= lapi.o lcode.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o \ lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o \ lundump.o lvm.o lzio.o LIB_O= lauxlib.o lbaselib.o ldblib.o liolib.o lmathlib.o loslib.o ltablib.o \ lstrlib.o loadlib.o linit.o LUA_T= lua LUA_O= lua.o LUAC_T= luac LUAC_O= luac.o print.o ALL_O= $(CORE_O) $(LIB_O) #$(LUA_O) $(LUAC_O) ALL_T= $(LUA_A) #$(LUA_T) $(LUAC_T) ALL_A= $(LUA_A) default: $(PLAT) all: $(ALL_T) o: $(ALL_O) a: $(ALL_A) $(LUA_A): $(CORE_O) $(LIB_O) $(AR) $@ $? $(RANLIB) $@ $(LUA_T): $(LUA_O) $(LUA_A) $(CC) -o $@ $(MYLDFLAGS) $(LUA_O) $(LUA_A) $(LIBS) $(LUAC_T): $(LUAC_O) $(LUA_A) $(CC) -o $@ $(MYLDFLAGS) $(LUAC_O) $(LUA_A) $(LIBS) clean: $(RM) $(ALL_T) $(ALL_O) depend: @$(CC) $(CFLAGS) -MM l*.c print.c echo: @echo "PLAT = $(PLAT)" @echo "CC = $(CC)" @echo "CFLAGS = $(CFLAGS)" @echo "AR = $(AR)" @echo "RANLIB = $(RANLIB)" @echo "RM = $(RM)" @echo "MYCFLAGS = $(MYCFLAGS)" @echo "MYLDFLAGS = $(MYLDFLAGS)" @echo "MYLIBS = $(MYLIBS)" # convenience targets for popular platforms none: @echo "Please choose a platform:" @echo " $(PLATS)" aix: $(MAKE) all CC="xlc" CFLAGS="-O2 -DLUA_USE_POSIX -DLUA_USE_DLOPEN" MYLIBS="-ldl" MYLDFLAGS="-brtl -bexpall" ansi: $(MAKE) all MYCFLAGS=-DLUA_ANSI bsd: $(MAKE) all MYCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" MYLIBS="-Wl,-E" freebsd: $(MAKE) all MYCFLAGS="-DLUA_USE_LINUX" MYLIBS="-Wl,-E -lreadline" generic: $(MAKE) all MYCFLAGS= linux: $(MAKE) all MYCFLAGS=-DLUA_USE_LINUX MYLIBS="-Wl,-E -ldl -lreadline -lhistory -lncurses" macosx: $(MAKE) all MYCFLAGS=-DLUA_USE_LINUX MYLIBS="-lreadline" # use this on Mac OS X 10.3- # $(MAKE) all MYCFLAGS=-DLUA_USE_MACOSX mingw: $(MAKE) "LUA_A=lua51.dll" "LUA_T=lua.exe" \ "AR=$(CC) -shared -o" "RANLIB=strip --strip-unneeded" \ "MYCFLAGS=-DLUA_BUILD_AS_DLL" "MYLIBS=" "MYLDFLAGS=-s" lua.exe $(MAKE) "LUAC_T=luac.exe" luac.exe posix: $(MAKE) all MYCFLAGS=-DLUA_USE_POSIX solaris: $(MAKE) all MYCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" MYLIBS="-ldl" # list targets that do not create files (but not all makes understand .PHONY) .PHONY: all $(PLATS) default o a clean depend echo none # DO NOT DELETE lapi.o: lapi.c lua.h luaconf.h lapi.h lobject.h llimits.h ldebug.h \ lstate.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h \ lundump.h lvm.h lauxlib.o: lauxlib.c lua.h luaconf.h lauxlib.h lbaselib.o: lbaselib.c lua.h luaconf.h lauxlib.h lualib.h lcode.o: lcode.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \ lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h lgc.h \ ltable.h ldblib.o: ldblib.c lua.h luaconf.h lauxlib.h lualib.h ldebug.o: ldebug.c lua.h luaconf.h lapi.h lobject.h llimits.h lcode.h \ llex.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h \ lfunc.h lstring.h lgc.h ltable.h lvm.h ldo.o: ldo.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \ lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lparser.h lstring.h \ ltable.h lundump.h lvm.h ldump.o: ldump.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h \ lzio.h lmem.h lundump.h lfunc.o: lfunc.c lua.h luaconf.h lfunc.h lobject.h llimits.h lgc.h lmem.h \ lstate.h ltm.h lzio.h lgc.o: lgc.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \ lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h linit.o: linit.c lua.h luaconf.h lualib.h lauxlib.h liolib.o: liolib.c lua.h luaconf.h lauxlib.h lualib.h llex.o: llex.c lua.h luaconf.h ldo.h lobject.h llimits.h lstate.h ltm.h \ lzio.h lmem.h llex.h lparser.h lstring.h lgc.h ltable.h lmathlib.o: lmathlib.c lua.h luaconf.h lauxlib.h lualib.h lmem.o: lmem.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \ ltm.h lzio.h lmem.h ldo.h loadlib.o: loadlib.c lua.h luaconf.h lauxlib.h lualib.h lobject.o: lobject.c lua.h luaconf.h ldo.h lobject.h llimits.h lstate.h \ ltm.h lzio.h lmem.h lstring.h lgc.h lvm.h lopcodes.o: lopcodes.c lopcodes.h llimits.h lua.h luaconf.h loslib.o: loslib.c lua.h luaconf.h lauxlib.h lualib.h lparser.o: lparser.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \ lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h \ lfunc.h lstring.h lgc.h ltable.h lstate.o: lstate.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \ ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h llex.h lstring.h ltable.h lstring.o: lstring.c lua.h luaconf.h lmem.h llimits.h lobject.h lstate.h \ ltm.h lzio.h lstring.h lgc.h lstrlib.o: lstrlib.c lua.h luaconf.h lauxlib.h lualib.h ltable.o: ltable.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \ ltm.h lzio.h lmem.h ldo.h lgc.h ltable.h ltablib.o: ltablib.c lua.h luaconf.h lauxlib.h lualib.h ltm.o: ltm.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h lzio.h \ lmem.h lstring.h lgc.h ltable.h lua.o: lua.c lua.h luaconf.h lauxlib.h lualib.h luac.o: luac.c lua.h luaconf.h lauxlib.h ldo.h lobject.h llimits.h \ lstate.h ltm.h lzio.h lmem.h lfunc.h lopcodes.h lstring.h lgc.h \ lundump.h lundump.o: lundump.c lua.h luaconf.h ldebug.h lstate.h lobject.h \ llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h lundump.h lvm.o: lvm.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \ lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h ltable.h lvm.h lzio.o: lzio.c lua.h luaconf.h llimits.h lmem.h lstate.h lobject.h ltm.h \ lzio.h print.o: print.c ldebug.h lstate.h lua.h luaconf.h lobject.h llimits.h \ ltm.h lzio.h lmem.h lopcodes.h lundump.h # (end of Makefile) <file_sep>/modules/mp3/libmp3/libmp3/sndmp3.c /* KallistiOS ##version## sndmp3.c Copyright (C)2000,2004 <NAME> An MP3 player using sndstream and XingMP3 */ /* This library is designed to be called from another program in a thread. It expects an input filename, and it will do all the setup and playback work. This requires a working math library for m4-single-only (such as newlib). */ #include <kos.h> #include <assert.h> #include <mp3/sndserver.h> #include <mp3/sndmp3.h> /************************************************************************/ #include <mhead.h> /* From xingmp3 */ #include <port.h> /* From xingmp3 */ /* Conversion codes: generally you won't play with this stuff */ #define CONV_NORMAL 0 #define CONV_MIXMONO 1 #define CONV_DROPRIGHT 2 #define CONV_DROPLEFT 3 #define CONV_8BIT 8 /* Reduction codes: once again, generally won't play with these */ #define REDUCT_NORMAL 0 #define REDUCT_HALF 1 #define REDUCT_QUARTER 2 /* Bitstream buffer: this is for input data */ #define BS_SIZE (64*1024) #define BS_WATER (16*1024) /* 8 sectors */ static char *bs_buffer = NULL, *bs_ptr; static int bs_count; /* PCM buffer: for storing data going out to the SPU */ #define PCM_WATER 65536 /* Amt to send to the SPU */ #define PCM_SIZE (PCM_WATER+16384) /* Total buffer size */ static char *pcm_buffer = NULL, *pcm_ptr; static int pcm_count, pcm_discard; static snd_stream_hnd_t stream_hnd = -1; /* MPEG file */ static uint32 mp3_fd; static int frame_bytes; static MPEG mpeg; static MPEG_HEAD head; static int bitrate; static DEC_INFO decinfo; /* Name of last played MP3 file */ static char mp3_last_fn[256]; /* Checks to make sure we have some data available in the bitstream buffer; if there's less than a certain "water level", shift the data back and bring in some more. */ static int bs_fill() { int n; /* Make sure we don't underflow */ if (bs_count < 0) bs_count = 0; /* Pull in some more data if we need it */ if (bs_count < BS_WATER) { /* Shift everything back */ memcpy(bs_buffer, bs_ptr, bs_count); /* Read in some more data */ // printf("fs_read(%d,%x,%d)\r\n", mp3_fd, bs_buffer+bs_count, BS_SIZE - bs_count); n = fs_read(mp3_fd, bs_buffer+bs_count, BS_SIZE - bs_count); // printf("==%d\r\n", n); if (n <= 0) return -1; /* Shift pointers back */ bs_count += n; bs_ptr = bs_buffer; } return 0; } /* Empties out the last (now-used) frame of data from the PCM buffer */ static int pcm_empty(int size) { if (pcm_count >= size) { /* Shift everything back */ memcpy(pcm_buffer, pcm_buffer + size, pcm_count - size); /* Shift pointers back */ pcm_count -= size; pcm_ptr = pcm_buffer + pcm_count; } return 0; } /* This callback is called each time the sndstream driver needs some more data. It will tell us how much it needs in bytes. */ static void* xing_callback(snd_stream_hnd_t hnd, int size, int * actual) { static int frames = 0; IN_OUT x; /* Check for file not started or file finished */ if (mp3_fd == 0) return NULL; /* Dump the last PCM packet */ pcm_empty(pcm_discard); /* Loop decoding until we have a full buffer */ while (pcm_count < size) { /* Pull in some more data (and check for EOF) */ if (bs_fill() < 0 || bs_count < frame_bytes) { printf("Decode completed\r\n"); goto errorout; } /* Decode a frame */ x = audio_decode(&mpeg, bs_ptr, (short*)pcm_ptr); if (x.in_bytes <= 0) { printf("Bad sync in MPEG file\r\n"); goto errorout; } bs_ptr += x.in_bytes; bs_count -= x.in_bytes; pcm_ptr += x.out_bytes; pcm_count += x.out_bytes; frames++; /*if (!(frames % 64)) { printf("Decoded %d frames \r", frames); }*/ } pcm_discard = *actual = size; /* Got it successfully */ return pcm_buffer; errorout: fs_close(mp3_fd); mp3_fd = 0; return NULL; } /* Open an MPEG stream and prepare for decode */ static int xing_init(const char *fn) { uint32 fd; /* Open the file */ mp3_fd = fd = fs_open(fn, O_RDONLY); if (fd < 0) { printf("Can't open input file %s\r\n", fn); printf("getwd() returns '%s'\r\n", fs_getwd()); return -1; } if (fn != mp3_last_fn) { if (fn[0] != '/') { strcpy(mp3_last_fn, fs_getwd()); strcat(mp3_last_fn, "/"); strcat(mp3_last_fn, fn); } else { strcpy(mp3_last_fn, fn); } } /* Allocate buffers */ if (bs_buffer == NULL) bs_buffer = malloc(BS_SIZE); bs_ptr = bs_buffer; bs_count = 0; if (pcm_buffer == NULL) pcm_buffer = malloc(PCM_SIZE); pcm_ptr = pcm_buffer; pcm_count = pcm_discard = 0; /* Fill bitstream buffer */ if (bs_fill() < 0) { printf("Can't read file header\r\n"); goto errorout; } /* Are we looking at a RIFF file? (stupid Windows encoders) */ if (bs_ptr[0] == 'R' && bs_ptr[1] == 'I' && bs_ptr[2] == 'F' && bs_ptr[3] == 'F') { /* Found a RIFF header, scan through it until we find the data section */ printf("Skipping stupid RIFF header\r\n"); while (bs_ptr[0] != 'd' || bs_ptr[1] != 'a' || bs_ptr[2] != 't' || bs_ptr[3] != 'a') { bs_ptr++; if (bs_ptr >= (bs_buffer + BS_SIZE)) { printf("Indeterminately long RIFF header\r\n"); goto errorout; } } /* Skip 'data' and length */ bs_ptr += 8; bs_count -= (bs_ptr - bs_buffer); printf("Final index is %d\r\n", (bs_ptr - bs_buffer)); } if (((uint8)bs_ptr[0] != 0xff) && (!((uint8)bs_ptr[1] & 0xe0))) { printf("Definitely not an MPEG file\r\n"); goto errorout; } /* Initialize MPEG engines */ mpeg_init(&mpeg); mpeg_eq_init(&mpeg); /* Parse MPEG header */ frame_bytes = head_info2(bs_ptr, bs_count, &head, &bitrate); if (frame_bytes == 0) { printf("Bad or unsupported MPEG file\r\n"); goto errorout; } /* Print out some info about it */ { static char *layers[] = { "invalid", "3", "2", "1" }; static char *modes[] = { "stereo", "joint-stereo", "dual", "mono" }; static int srs[] = { 22050, 24000, 16000, 1, 44100, 48000, 32000, 1 }; printf("Opened stream %s for decoding:\r\n", fn); printf(" %dKbps Layer %s %s at %dHz\r\n", bitrate/1000, layers[head.option], modes[head.mode], srs[4*head.id + head.sr_index]); } /* Initialize audio decoder */ if (!audio_decode_init(&mpeg, &head, frame_bytes, REDUCT_NORMAL, 0, CONV_NORMAL, 44100)) { printf("Failed to initialize decoder\r\n"); goto errorout; } audio_decode_info(&mpeg, &decinfo); printf("Output Sampling rate = %ld\r\n", decinfo.samprate); printf("Output Channels = %d\r\n", decinfo.channels); printf("Output Bits = %d\r\n", decinfo.bits); printf("Output Type = %d\r\n", decinfo.type); /* if (decinfo.samprate != 44100) { printf("Currently cannot process %ld sampling rate\r\n", decinfo.samprate); goto errorout; } */ printf("XingMP3 initialized successfully\r\n"); return 0; errorout: printf("Exiting on error\r\n"); if (bs_buffer) { free(bs_buffer); bs_buffer = NULL; } if (pcm_buffer) { free(pcm_buffer); pcm_buffer = NULL; } fs_close(fd); mp3_fd = 0; return -1; } static void xing_shutdown() { if (bs_buffer) { free(bs_buffer); bs_buffer = NULL; } if (pcm_buffer) { free(pcm_buffer); pcm_buffer = NULL; } if (mp3_fd) { fs_close(mp3_fd); mp3_fd = 0; } } /************************************************************************/ #include <dc/sound/stream.h> /* Status flag */ #define STATUS_INIT 0 #define STATUS_READY 1 #define STATUS_STARTING 2 #define STATUS_PLAYING 3 #define STATUS_STOPPING 4 #define STATUS_QUIT 5 #define STATUS_ZOMBIE 6 #define STATUS_REINIT 7 static volatile int sndmp3_status; /* Wait until the MP3 thread is started and ready */ void sndmp3_wait_start() { while (sndmp3_status != STATUS_READY) ; } /* Semaphore to halt sndmp3 until a command comes in */ static semaphore_t *sndmp3_halt_sem; /* Loop flag */ static volatile int sndmp3_loop; /* Call this function as a thread to handle playback. Playback will stop and this thread will return when you call sndmp3_shutdown(). */ static void sndmp3_thread() { int sj; stream_hnd = snd_stream_alloc(NULL, SND_STREAM_BUFFER_MAX); assert( stream_hnd != -1 ); /* Main command loop */ while(sndmp3_status != STATUS_QUIT) { switch(sndmp3_status) { case STATUS_INIT: sndmp3_status = STATUS_READY; break; case STATUS_READY: printf("sndserver: waiting on semaphore\r\n"); sem_wait(sndmp3_halt_sem); printf("sndserver: released from semaphore\r\n"); break; case STATUS_STARTING: /* Initialize streaming driver */ if (snd_stream_reinit(stream_hnd, xing_callback) < 0) { sndmp3_status = STATUS_READY; } else { snd_stream_start(stream_hnd, decinfo.samprate, decinfo.channels - 1); sndmp3_status = STATUS_PLAYING; } break; case STATUS_REINIT: /* Re-initialize streaming driver */ snd_stream_reinit(stream_hnd, NULL); sndmp3_status = STATUS_READY; break; case STATUS_PLAYING: { sj = jiffies; if (snd_stream_poll(stream_hnd) < 0) { if (sndmp3_loop) { printf("sndserver: restarting '%s'\r\n", mp3_last_fn); if (xing_init(mp3_last_fn) < 0) { sndmp3_status = STATUS_STOPPING; mp3_last_fn[0] = 0; } } else { printf("sndserver: not restarting\r\n"); snd_stream_stop(stream_hnd); sndmp3_status = STATUS_READY; mp3_last_fn[0] = 0; } // stream_start(); } else thd_sleep(50); break; } case STATUS_STOPPING: snd_stream_stop(stream_hnd); sndmp3_status = STATUS_READY; break; } } /* Done: clean up */ xing_shutdown(); snd_stream_stop(stream_hnd); snd_stream_destroy(stream_hnd); sndmp3_status = STATUS_ZOMBIE; } /* Start playback (implies song load) */ int sndmp3_start(const char *fn, int loop) { /* Can't start again if already playing */ if (sndmp3_status == STATUS_PLAYING) return -1; /* Initialize MP3 engine */ if (fn) { if (xing_init(fn) < 0) return -1; /* Set looping status */ sndmp3_loop = loop; } /* Wait for player thread to be ready */ while (sndmp3_status != STATUS_READY) thd_pass(); /* Tell it to start */ if (fn) sndmp3_status = STATUS_STARTING; else sndmp3_status = STATUS_REINIT; sem_signal(sndmp3_halt_sem); return 0; } /* Stop playback (implies song unload) */ void sndmp3_stop() { if (sndmp3_status == STATUS_READY) return; sndmp3_status = STATUS_STOPPING; while (sndmp3_status != STATUS_READY) thd_pass(); xing_shutdown(); mp3_last_fn[0] = 0; } /* Shutdown the player */ void sndmp3_shutdown() { sndmp3_status = STATUS_QUIT; sem_signal(sndmp3_halt_sem); while (sndmp3_status != STATUS_ZOMBIE) thd_pass(); spu_disable(); } /* Adjust the MP3 volume */ void sndmp3_volume(int vol) { snd_stream_volume(stream_hnd, vol); } /* Setup a service */ /* #include <kallisti/svcmpx.h> #include "sfxmgr.h" #include "sndsrv_abi.h" static abi_sndsrv_t ssabi; static void sndmp3_svc_init() { memset(&ssabi, 0, sizeof(ssabi)); ssabi.hdr.version = ABI_MAKE_VER(1,0,0); ssabi.shutdown = sndmp3_shutdown; ssabi.mp3_start = sndmp3_start; ssabi.mp3_stop = sndmp3_stop; ssabi.mp3_volume = sndmp3_volume; ssabi.sfx_load = sfx_load; ssabi.sfx_play = sfx_play; ssabi.sfx_unload_all = sfx_unload_all; svcmpx->add_handler("sndsrv", &ssabi); } */ /* The main loop for the sound server */ void sndmp3_mainloop() { /* Allocate a semaphore for temporarily halting sndmp3 */ sndmp3_halt_sem = sem_create(0); /* Setup an ABI for other programs */ /* sndmp3_svc_init(); */ /* Initialize sound program for apps that don't need music */ // snd_stream_init(NULL); /* Go into the main thread wait loop */ sndmp3_status=STATUS_INIT; sndmp3_thread(); /* Free the semaphore */ sem_destroy(sndmp3_halt_sem); /* Thread exited, so we were requested to quit */ /* svcmpx->remove_handler("sndsrv"); */ } <file_sep>/modules/ffmpeg/mpg123.c /** * @file mpg123.c * Mpeg audio 1,2,3 codec support via libmpg123. * @author SWAT */ #include "libavcodec/avcodec.h" #include "libavformat/avformat.h" #include "mpg123/config.h" #include "mpg123/compat.h" #include "mpg123/mpg123.h" typedef struct MPADecodeContext { mpg123_handle *mh; } MPADecodeContext; static int decode_init(AVCodecContext * avctx) { MPADecodeContext *s = avctx->priv_data; int err = 0; mpg123_init(); s->mh = mpg123_new(NULL, &err); if(s->mh == NULL) { printf("Can't init mpg123: %s\n", mpg123_strerror(s->mh)); return -1; } //mpg123_param(s->mh, MPG123_VERBOSE, 2, 0); /* Open the MP3 context */ err = mpg123_open_feed(s->mh); if(err != MPG123_OK) { printf("Can't open mpg123\n"); return -1; } return 0; } static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPacket *avpkt) { MPADecodeContext *s = avctx->priv_data; int ret; size_t outsize = 0; uint8 *outp = data; ret = mpg123_decode(s->mh, (uint8*)avpkt->data, avpkt->size, outp, 65536, &outsize); *data_size = outsize; if(ret == MPG123_NEW_FORMAT) { //printf("MPG123 new format from ffmpeg\n"); long rate; int channels, enc; struct mpg123_frameinfo decinfo; mpg123_getformat(s->mh, &rate, &channels, &enc); //mpg123_feed(s->mh, (uint8*)avpkt->data, avpkt->size); mpg123_info(s->mh, &decinfo); avctx->channels = channels; avctx->sample_rate = rate; avctx->bit_rate = decinfo.bitrate; avctx->frame_size = decinfo.framesize; //avctx->frame_bits = 16; avctx->sample_fmt = SAMPLE_FMT_U8; //printf("Output Sampling rate = %ld\r\n", decinfo.rate); //printf("Output Bitrate = %d\r\n", decinfo.bitrate); //printf("Output Frame size = %d\r\n", decinfo.framesize); //return avpkt->size; } if(ret == MPG123_ERR) { //printf("mpg123: %s\n", mpg123_plain_strerror(ret)); return -1; } //printf("mpg123: %s\n", mpg123_plain_strerror(ret)); while(ret != MPG123_ERR && ret != MPG123_NEED_MORE) { /* Get all decoded audio that is available now before feeding more input. */ ret = mpg123_decode(s->mh, NULL, 0, outp, 65536, &outsize); //printf("mpg123: %s\n", mpg123_plain_strerror(ret)); if(ret != MPG123_ERR && ret != MPG123_NEED_MORE) { *data_size += outsize; outp += outsize; } } return avpkt->size; } static int decode_close(AVCodecContext *avctx) { MPADecodeContext *s = avctx->priv_data; if(s->mh != NULL) { mpg123_close(s->mh); } mpg123_exit(); return 0; } AVCodec mp1_decoder = { "mp1", AVMEDIA_TYPE_AUDIO, CODEC_ID_MP1, sizeof(MPADecodeContext), decode_init, NULL, decode_close, decode_frame, CODEC_CAP_PARSE_ONLY, NULL, NULL, NULL, NULL, "MP1 (MPEG audio layer 1)" }; AVCodec mp2_decoder = { "mp2", AVMEDIA_TYPE_AUDIO, CODEC_ID_MP2, sizeof(MPADecodeContext), decode_init, NULL, decode_close, decode_frame, CODEC_CAP_PARSE_ONLY, NULL, NULL, NULL, NULL, "MP2 (MPEG audio layer 2)" }; AVCodec mp3_decoder = { "mp3", AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3, sizeof(MPADecodeContext), decode_init, NULL, decode_close, decode_frame, CODEC_CAP_PARSE_ONLY, NULL, NULL, NULL, NULL, "MP3 (MPEG audio layer 3)" }; <file_sep>/firmware/isoldr/loader/kos/src/maple.c /* This file is part of the Dreamcast function library. * Please see libdream.c for further details. * * (c)2000 <NAME> */ #include <string.h> #include <dc/maple.h> /* * This module handles low-level communication/initialization of the maple * bus. Specific devices aren't handled by this module, rather, the modules * implementing specific devices can use this module to access them. * * Thanks to <NAME> for information on the maple bus. * * Ported from KallistiOS for libdream by <NAME> */ /* macro for poking maple mem */ #define MAPLE(x) (*(unsigned long *)((0xa05f6c00)+(x))) /* dma transfer buffer */ uint32 *dmabuffer, dmabuffer_real[1024+1024+4+4+32]; /* a few small internal functions to make code slightly more readable */ void maple_enable_bus() { MAPLE(0x14) = 1; } void maple_disable_bus() { MAPLE(0x14) = 0; } void maple_start_dma() { MAPLE(0x18) = 1; } int maple_dma_in_progress() { return MAPLE(0x18) & 1; } /* set timeout to timeout, and bitrate to 2Mbps (what it must be) */ void maple_set_timeout(int timeout) { MAPLE(0x80) = (timeout << 16) | 0; } /* set the DMA ptr */ void maple_set_dma_ptr(unsigned long *ptr) { MAPLE(0x04) = ((uint32) ptr) & 0xfffffff; } /* initialize the maple bus. */ void maple_init(int quiet) { /* reset hardware */ MAPLE(0x8c) = 0x6155404f; MAPLE(0x10) = 0; maple_set_timeout(50000); /* buffer for dma transfers; room for a send and recv buffer */ dmabuffer = (uint32*)( (((uint32)dmabuffer_real) + 31) & ~31 ); maple_enable_bus(); maple_rescan_bus(quiet); } /* turn off the maple bus, free mem */ void maple_shutdown() { maple_disable_bus(); } /* use the information in tdesc to place a new transfer descriptor, followed by a num of frames onto buffer, and return the new ptr into buff */ uint32 *maple_add_trans(maple_tdesc_t tdesc, uint32 *buffer) { int i; /* build the transfer descriptor's first word */ *buffer++ = tdesc.length | (tdesc.port << 16) | (tdesc.lastdesc << 31); /* transfer descriptor second word: address to receive buffer */ *buffer++ = ((uint32) tdesc.recvaddr) & 0xfffffff; /* add each of the frames in this transfer */ for (i = 0; i < tdesc.numframes; i++) { /* frame header */ *buffer++ = (tdesc.frames[i].cmd & 0xff) | (tdesc.frames[i].to << 8) | (tdesc.frames[i].from << 16) | (tdesc.frames[i].datalen << 24); /* parameter data, if any exists */ if (tdesc.frames[i].datalen > 0) { memcpy(buffer, tdesc.frames[i].data, tdesc.frames[i].datalen * 4); buffer += tdesc.frames[i].datalen; } } return buffer; } /* read information at buffer and turn it into a maple_frame_t */ void maple_read_frame(uint32 *buffer, maple_frame_t *frame) { uint8 *b = (uint8 *) buffer; frame->cmd = b[0]; frame->to = b[1]; frame->from = b[2]; frame->datalen = b[3]; frame->data = &b[4]; } /* create a maple address, -1 on error */ uint8 maple_create_addr(uint8 port, uint8 unit) { uint8 addr; if (port > 3 || unit > 5) return -1; addr = port << 6; if (unit != 0) addr |= (1 << (unit - 1)) & 0x1f; else addr |= 0x20; return addr; } /* initiate a dma transfer and block until it's completed, return -1 if error (currently only if DMA is already in progress) */ int maple_dodma_block() { if (maple_dma_in_progress()) return -1; /* enable maple dma transfer bit */ maple_start_dma(); /* wait for it to clear (indicating the end of the transfer */ while (maple_dma_in_progress()) ; return 0; } /* little funct to send a single command on the maple bus, and block until recving a response, returns -1 on error */ int maple_docmd_block(int8 cmd, uint8 addr, uint8 datalen, void *data, maple_frame_t *retframe) { uint32 *sendbuff, *recvbuff; maple_tdesc_t tdesc; maple_frame_t frame; /* setup buffer ptrs, into dmabuffer and set uncacheable */ sendbuff = (uint32 *) dmabuffer; recvbuff = (uint32 *) (dmabuffer + 1024); sendbuff = (uint32 *) ((uint32) sendbuff | 0xa0000000); recvbuff = (uint32 *) ((uint32) recvbuff | 0xa0000000); /* setup tdesc/frame */ tdesc.lastdesc = 1; tdesc.port = addr >> 6; tdesc.length = datalen; tdesc.recvaddr = recvbuff; tdesc.numframes = 1; tdesc.frames = &frame; frame.cmd = cmd; frame.data = data; frame.datalen = datalen; frame.from = tdesc.port << 6; frame.to = addr; /* make sure no DMA is in progress */ if (maple_dma_in_progress()) { printf("docmd_block: dma already in progress\r\n"); return -1; } maple_set_dma_ptr(sendbuff); maple_add_trans(tdesc, sendbuff); /* do the dma, blocking till it finishes */ if (maple_dodma_block() == -1) { printf("docmd_block: dodma_block failed\r\n"); return -1; } maple_read_frame(recvbuff, retframe); return 0; } /* Rescan the maple bus to recognize VMUs, etc */ static int func_codes[4][6] = { {0} }; int maple_rescan_bus(int quiet) { int port, unit, to; maple_frame_t frame; if (!quiet) printf("Rescanning maple bus:\r\n"); for (port=0; port<4; port++) for (unit=0; unit<6; unit++) { to = 1000; do { if (maple_docmd_block(MAPLE_COMMAND_DEVINFO, maple_create_addr(port, unit), 0, NULL, &frame) == -1) return -1; to--; if (to <= 0) { printf(" %c%c: timeout\r\n", 'a'+port, '0'+unit); break; } } while (frame.cmd == MAPLE_RESPONSE_AGAIN); if (frame.cmd == MAPLE_RESPONSE_DEVINFO) { maple_devinfo_t *di = (maple_devinfo_t*)frame.data; di->product_name[29] = '\0'; func_codes[port][unit] = di->func; if (!quiet) printf(" %c%c: %s (%08x)\r\n", 'a'+port, '0'+unit, di->product_name, di->func); } else func_codes[port][unit] = 0; } return 0; } /* A couple of convienence functions to load maple peripherals */ /* First with a given function code... */ uint8 maple_device_addr(int code) { int port, unit; for (port=0; port<4; port++) for (unit=0; unit<6; unit++) { if (func_codes[port][unit] & code) return maple_create_addr(port, unit); } return 0; } /* First controller */ uint8 maple_controller_addr() { return maple_device_addr(MAPLE_FUNC_CONTROLLER); } /* First mouse */ uint8 maple_mouse_addr() { return maple_device_addr(MAPLE_FUNC_MOUSE); } /* First keyboard */ uint8 maple_kb_addr() { return maple_device_addr(MAPLE_FUNC_KEYBOARD); } /* First LCD unit */ uint8 maple_lcd_addr() { return maple_device_addr(MAPLE_FUNC_LCD); } /* First VMU */ uint8 maple_vmu_addr() { return maple_device_addr(MAPLE_FUNC_MEMCARD); } <file_sep>/resources/lua/startup.lua ----------------------------------------- -- -- -- @name: Startup script -- -- @author: SWAT -- -- @url: http://www.dc-swat.ru -- -- -- ----------------------------------------- -- -- Internal DreamShell lua functions: -- -- OpenModule Open module file and return ID -- CloseModule Close module by ID -- GetModuleByName Get module ID by module NAME -- -- AddApp Add app by XML file, return app NAME -- OpenApp Open app by NAME (second argument for args) -- CloseApp Close app by NAME (second argument for change unload flag) -- -- ShowConsole -- HideConsole -- SetDebugIO Set the debug output (scif, dclsocket, fb, ds, sd). By default is ds. -- Sleep Sleep in current thread (in ms) -- MapleAttached Check for attached maple device -- -- Bit library: bit.or, bit.and, bit.not, bit.xor -- File system library: lfs.chdir, lfs.currentdir, lfs.dir, lfs.mkdir, lfs.rmdir -- ------------------------------------------ local DreamShell = { initialized = false, modules = { --"tolua", --"tolua_2plus", --"luaDS", -- Depends: tolua --"luaKOS", -- Depends: tolua --"luaSDL", -- Depends: tolua --"luaGUI", -- Depends: tolua --"luaMXML", -- Depends: tolua --"luaSTD", -- Depends: tolua --"sqlite3", --"luaSQL", -- Depends: sqlite3 --"luaSocket", --"luaTask", --"bzip2", --"minilzo", --"zip", -- Depends: bzip2 --"http", --"httpd", --"telnetd", --"mongoose", --"ppp", --"mpg123", --"oggvorbis", --"adx", --"s3m", --"xvid", --"SDL_mixer", -- Depends: oggvorbis --"ffmpeg", -- Depends: oggvorbis, mpg123, bzip2 --"opengl", --"isofs", -- Depends: minilzo --"isoldr", -- Depends: isofs --"SDL_net", --"opkg", -- Depends: minilzo --"aicaos", --"gumbo", --"ini", --"bflash", --"openssl", --"bitcoin" }, Initialize = function(self) os.execute("env USER Default"); local path = os.getenv("PATH"); print(os.getenv("HOST") .. " " .. os.getenv("VERSION") .. "\n"); print(os.getenv("ARCH") .. ": " .. os.getenv("BOARD_ID") .. "\n"); print("Date: " .. os.date() .. "\n"); print("Base path: " .. path .. "\n"); print("User: " .. os.getenv("USER") .. "\n"); local emu = os.getenv("EMU"); if emu ~= nil then print("Emulator: " .. emu .. "\n"); end print("\n"); os.execute("net --init"); if not MapleAttached("Keyboard") then table.insert(self.modules, "vkb"); end table.foreach(self.modules, function(k, name) print("DS_PROCESS: Loading module " .. name .. "...\n"); if not OpenModule(path .. "/modules/" .. name .. ".klf") then print("DS_ERROR: Can't load module " .. path .. "/modules/" .. name .. ".klf\n"); end end); self:InstallingApps(path .. "/apps"); self.initialized = true; OpenApp(os.getenv("APP")); end, InstallingApps = function(self, path) print("DS_PROCESS: Installing apps...\n"); local name = nil; local list = {}; for ent in lfs.dir(path) do if ent ~= nil and ent.name ~= ".." and ent.name ~= "." and ent.attr ~= 0 then table.insert(list, ent.name); end end table.sort(list, function(a, b) return a > b end); for index, directory in ipairs(list) do name = AddApp(path .. "/" .. directory .. "/app.xml"); if not name then print("DS_ERROR: " .. directory .. "\n"); else print("DS_OK: " .. name .. "\n"); end end return true; end }; if not DreamShell.initialized then DreamShell:Initialize(); end <file_sep>/modules/luaSocket/Makefile # # luaSocket module for DreamShell # Copyright (C) 2011-2014 SWAT # http://www.dc-swat.ru # TARGET_NAME = luaSocket OBJS = module.o \ src/luasocket.o \ src/timeout.o \ src/buffer.o \ src/io.o \ src/auxiliar.o \ src/options.o \ src/inet.o \ src/tcp.o \ src/udp.o \ src/except.o \ src/select.o \ src/usocket.o \ src/mime.o DBG_LIBS = -lds EXPORTS_FILE = exports.txt VER_MAJOR = 2 VER_MINOR = 0 VER_MICRO = 1 all: rm-elf include ../../sdk/Makefile.loadable KOS_CFLAGS += -I./src -I$(DS_SDK)/include/lua install_lua: cp src/ltn12.lua $(DS_BUILD)/lua/lib/ltn12.lua cp src/socket.lua $(DS_BUILD)/lua/lib/socket.lua cp src/mime.lua $(DS_BUILD)/lua/lib/mime.lua mkdir -p $(DS_BUILD)/lua/lib/socket cp src/http.lua $(DS_BUILD)/lua/lib/socket/http.lua cp src/url.lua $(DS_BUILD)/lua/lib/socket/url.lua cp src/tp.lua $(DS_BUILD)/lua/lib/socket/tp.lua cp src/ftp.lua $(DS_BUILD)/lua/lib/socket/ftp.lua cp src/smtp.lua $(DS_BUILD)/lua/lib/socket/smtp.lua rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) install_lua -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/firmware/isoldr/loader/mmu.c /** * DreamShell ISO Loader * SH4 MMU * (c)2015-2016 SWAT <http://www.dc-swat.ru> */ #include <string.h> #include <arch/irq.h> #include <arch/cache.h> #include <dc/sq.h> #include <main.h> #define MMUCR *((vuint32*)0xff000010) //static int old_irq, old_mmu; int mmu_enabled(void) { uint32 val = MMUCR; return val & 0x01; } /* void mmu_disable(void) { old_irq = irq_disable(); old_mmu = MMUCR; uint32 val = old_mmu; // Diable MMU val &= ~0x01; // Set SQ mode // val &= ~(1 << 9); MMUCR = val; } void mmu_restore() { MMUCR = old_mmu; irq_restore(old_irq); } void enable_sq() { uint32 val = MMUCR; LOGFF("SQ = %d\n", val & 0x200); val &= ~(1 << 9); LOGFF("SQ = %d\n", val & 0x200); MMUCR = val; val = MMUCR; LOGFF("SQ = %d\n", val & 0x200); } void mmu_memcpy(void *dest, const void *src, size_t count) { uint32 addr = (uint32)dest; if(!(addr & 0xF0000000) && mmu_enabled()) { // LOGFF("0x%08lx -> 0x%08lx %ld bytes, MMUCR: 0x%08lx\n", (uint32)src, addr, count, MMUCR); // if(addr & 0x1F) { //// mmu_disable(); //// memcpy(dest, src, count); //// dcache_purge_range(addr, count); //// mmu_restore(); // void *ncdest = (void *)(addr | 0xE0000000); // memcpy(ncdest, src, count); // dcache_purge_range((uint32)ncdest, count); // } else { //// enable_sq(); sq_cpy(dest, src, count); // } } else { memcpy(dest, src, count); } } */ <file_sep>/modules/mp3/libmp3/xingmp3/cupini.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /*========================================================= initialization for cup.c - include to cup.c mpeg audio decoder portable "c" mod 8/6/96 add 8 bit output mod 5/10/95 add quick (low precision) window mod 5/16/95 sb limit for reduced samprate output changed from 94% to 100% of Nyquist sb mod 11/15/95 for Layer I =========================================================*/ /*-- compiler bug, floating constant overflow w/ansi --*/ #ifdef _MSC_VER #pragma warning(disable:4056) #endif /* Read Only */ static long steps[18] = { 0, 3, 5, 7, 9, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535}; /* ABCD_INDEX = lookqt[mode][sr_index][br_index] */ /* -1 = invalid */ /* Read Only */ static signed char lookqt[4][3][16] = { {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks stereo */ {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks joint stereo */ {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks dual chan */ {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ // mono extended beyond legal br index // 1,2,2,0,0,0,1,1,1,1,1,1,1,1,1,-1, /* 44ks single chan */ // 0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,-1, /* 48ks */ // 1,3,3,0,0,0,1,1,1,1,1,1,1,1,1,-1, /* 32ks */ // legal mono {{1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}, /* 44ks single chan */ {0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1}, /* 48ks */ {1, 3, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}}, /* 32ks */ }; /* Read Only */ static long sr_table[8] = {22050L, 24000L, 16000L, 1L, 44100L, 48000L, 32000L, 1L}; /* bit allocation table look up */ /* table per mpeg spec tables 3b2a/b/c/d /e is mpeg2 */ /* look_bat[abcd_index][4][16] */ /* Read Only */ static unsigned char look_bat[5][4][16] = { /* LOOK_BATA */ {{0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17}, {0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* LOOK_BATB */ {{0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17}, {0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* LOOK_BATC */ {{0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* LOOK_BATD */ {{0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* LOOK_BATE */ {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, }; /* look_nbat[abcd_index]][4] */ /* Read Only */ static unsigned char look_nbat[5][4] = { {3, 8, 12, 4}, {3, 8, 12, 7}, {2, 0, 6, 0}, {2, 0, 10, 0}, {4, 0, 7, 19}, }; void sbt_mono(MPEG *m, float *sample, short *pcm, int n); void sbt_dual(MPEG *m, float *sample, short *pcm, int n); void sbt_dual_mono(MPEG *m, float *sample, short *pcm, int n); void sbt_dual_left(MPEG *m, float *sample, short *pcm, int n); void sbt_dual_right(MPEG *m, float *sample, short *pcm, int n); void sbt16_mono(MPEG *m, float *sample, short *pcm, int n); void sbt16_dual(MPEG *m, float *sample, short *pcm, int n); void sbt16_dual_mono(MPEG *m, float *sample, short *pcm, int n); void sbt16_dual_left(MPEG *m, float *sample, short *pcm, int n); void sbt16_dual_right(MPEG *m, float *sample, short *pcm, int n); void sbt8_mono(MPEG *m, float *sample, short *pcm, int n); void sbt8_dual(MPEG *m, float *sample, short *pcm, int n); void sbt8_dual_mono(MPEG *m, float *sample, short *pcm, int n); void sbt8_dual_left(MPEG *m, float *sample, short *pcm, int n); void sbt8_dual_right(MPEG *m, float *sample, short *pcm, int n); /*--- 8 bit output ---*/ void sbtB_mono(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB_dual(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB_dual_mono(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB_dual_left(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB_dual_right(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB16_mono(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB16_dual(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB16_dual_mono(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB16_dual_left(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB16_dual_right(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB8_mono(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB8_dual(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB8_dual_mono(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB8_dual_left(MPEG *m, float *sample, unsigned char *pcm, int n); void sbtB8_dual_right(MPEG *m, float *sample, unsigned char *pcm, int n); static SBT_FUNCTION_F sbt_table[2][3][5] = { {{sbt_mono, sbt_dual, sbt_dual_mono, sbt_dual_left, sbt_dual_right}, {sbt16_mono, sbt16_dual, sbt16_dual_mono, sbt16_dual_left, sbt16_dual_right}, {sbt8_mono, sbt8_dual, sbt8_dual_mono, sbt8_dual_left, sbt8_dual_right}}, {{(SBT_FUNCTION_F) sbtB_mono, (SBT_FUNCTION_F) sbtB_dual, (SBT_FUNCTION_F) sbtB_dual_mono, (SBT_FUNCTION_F) sbtB_dual_left, (SBT_FUNCTION_F) sbtB_dual_right}, {(SBT_FUNCTION_F) sbtB16_mono, (SBT_FUNCTION_F) sbtB16_dual, (SBT_FUNCTION_F) sbtB16_dual_mono, (SBT_FUNCTION_F) sbtB16_dual_left, (SBT_FUNCTION_F) sbtB16_dual_right}, {(SBT_FUNCTION_F) sbtB8_mono, (SBT_FUNCTION_F) sbtB8_dual, (SBT_FUNCTION_F) sbtB8_dual_mono, (SBT_FUNCTION_F) sbtB8_dual_left, (SBT_FUNCTION_F) sbtB8_dual_right}}, }; static int out_chans[5] = {1, 2, 1, 1, 1}; int audio_decode_initL1(MPEG_HEAD * h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); void sbt_init(MPEG *m); IN_OUT L1audio_decode(void *mv, unsigned char *bs, signed short *pcm); IN_OUT L2audio_decode(void *mv, unsigned char *bs, signed short *pcm); IN_OUT L3audio_decode(void *mv, unsigned char *bs, unsigned char *pcm); static AUDIO_DECODE_ROUTINE decode_routine_table[4] = { L2audio_decode, (AUDIO_DECODE_ROUTINE)L3audio_decode, L2audio_decode, L1audio_decode,}; extern void cup3_init(MPEG *m); void mpeg_init(MPEG *m) { // Init everything but the equalizer stuff -- that is done in the // function below. This is seperate, because we don't want to reset // the eq when we reset the decoder memset(m, 0, sizeof(MPEG) - sizeof(eq_info)); m->cup.nsb_limit = 6; m->cup.nbat[0] = 3; m->cup.nbat[1] = 8; m->cup.nbat[3] = 12; m->cup.nbat[4] = 7; m->cup.sbt = sbt_mono; m->cup.first_pass = 1; m->cup.first_pass_L1 = 1; m->cup.audio_decode_routine = L2audio_decode; m->cup.cs_factorL1 = m->cup.cs_factor[0]; m->cup.nbatL1 = 32; m->cupl.band_limit = 576; m->cupl.band_limit21 = 567; m->cupl.band_limit12 = 576; m->cupl.band_limit_nsb = 32; m->cupl.nsb_limit=32; m->cup.sample = (float *)&m->cupl.sample; m->csbt.first_pass = 1; cup3_init(m); } void mpeg_eq_init(MPEG *m) { int i; m->eq.enableEQ = 0; for(i = 0; i < 32; i++) m->eq.equalizer[i] = 1.0; m->eq.EQ_gain_adjust = 1.0; } /*---------------------------------------------------------*/ static void table_init(MPEG *m) { int i, j; int code; /*-- c_values (dequant) --*/ for (i = 1; i < 18; i++) m->cup.look_c_value[i] = 2.0F / steps[i]; /*-- scale factor table, scale by 32768 for 16 pcm output --*/ for (i = 0; i < 64; i++) m->cup.sf_table[i] = (float) (32768.0 * 2.0 * pow(2.0, -i / 3.0)); /*-- grouped 3 level lookup table 5 bit token --*/ for (i = 0; i < 32; i++) { code = i; for (j = 0; j < 3; j++) { m->cup.group3_table[i][j] = (char) ((code % 3) - 1); code /= 3; } } /*-- grouped 5 level lookup table 7 bit token --*/ for (i = 0; i < 128; i++) { code = i; for (j = 0; j < 3; j++) { m->cup.group5_table[i][j] = (char) ((code % 5) - 2); code /= 5; } } /*-- grouped 9 level lookup table 10 bit token --*/ for (i = 0; i < 1024; i++) { code = i; for (j = 0; j < 3; j++) { m->cup.group9_table[i][j] = (short) ((code % 9) - 4); code /= 9; } } } /*---------------------------------------------------------*/ int L1audio_decode_init(MPEG *m, MPEG_HEAD * h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); int L3audio_decode_init(MPEG *m, MPEG_HEAD * h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); /*---------------------------------------------------------*/ /* mpeg_head defined in mhead.h frame bytes is without pad */ int audio_decode_init(MPEG *m, MPEG_HEAD * h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit) { int i, j, k; int abcd_index; long samprate; int limit; int bit_code; if (m->cup.first_pass) { table_init(m); m->cup.first_pass = 0; } /* select decoder routine Layer I,II,III */ m->cup.audio_decode_routine = decode_routine_table[h->option & 3]; if (h->option == 3) /* layer I */ return L1audio_decode_init(m, h, framebytes_arg, reduction_code, transform_code, convert_code, freq_limit); if (h->option == 1) /* layer III */ return L3audio_decode_init(m, h, framebytes_arg, reduction_code, transform_code, convert_code, freq_limit); transform_code = transform_code; /* not used, asm compatability */ bit_code = 0; if (convert_code & 8) bit_code = 1; convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ if (reduction_code < 0) reduction_code = 0; if (reduction_code > 2) reduction_code = 2; if (freq_limit < 1000) freq_limit = 1000; m->cup.framebytes = framebytes_arg; /* check if code handles */ if (h->option != 2) return 0; /* layer II only */ if (h->sr_index == 3) return 0; /* reserved */ /* compute abcd index for bit allo table selection */ if (h->id) /* mpeg 1 */ abcd_index = lookqt[h->mode][h->sr_index][h->br_index]; else abcd_index = 4; /* mpeg 2 */ if (abcd_index < 0) return 0; // fail invalid Layer II bit rate index for (i = 0; i < 4; i++) for (j = 0; j < 16; j++) m->cup.bat[i][j] = look_bat[abcd_index][i][j]; for (i = 0; i < 4; i++) m->cup.nbat[i] = look_nbat[abcd_index][i]; m->cup.max_sb = m->cup.nbat[0] + m->cup.nbat[1] + m->cup.nbat[2] + m->cup.nbat[3]; /*----- compute nsb_limit --------*/ samprate = sr_table[4 * h->id + h->sr_index]; m->cup.nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; /*- caller limit -*/ /*---- limit = 0.94*(32>>reduction_code); ----*/ limit = (32 >> reduction_code); if (limit > 8) limit--; if (m->cup.nsb_limit > limit) m->cup.nsb_limit = limit; if (m->cup.nsb_limit > m->cup.max_sb) m->cup.nsb_limit = m->cup.max_sb; m->cup.outvalues = 1152 >> reduction_code; if (h->mode != 3) { /* adjust for 2 channel modes */ for (i = 0; i < 4; i++) m->cup.nbat[i] *= 2; m->cup.max_sb *= 2; m->cup.nsb_limit *= 2; } /* set sbt function */ k = 1 + convert_code; if (h->mode == 3) { k = 0; } m->cup.sbt = sbt_table[bit_code][reduction_code][k]; m->cup.outvalues *= out_chans[k]; if (bit_code) m->cup.outbytes = m->cup.outvalues; else m->cup.outbytes = sizeof(short) * m->cup.outvalues; m->cup.decinfo.channels = out_chans[k]; m->cup.decinfo.outvalues = m->cup.outvalues; m->cup.decinfo.samprate = samprate >> reduction_code; if (bit_code) m->cup.decinfo.bits = 8; else m->cup.decinfo.bits = sizeof(short) * 8; m->cup.decinfo.framebytes = m->cup.framebytes; m->cup.decinfo.type = 0; /* clear sample buffer, unused sub bands must be 0 */ for (i = 0; i < 2304; i++) m->cup.sample[i] = 0.0F; /* init sub-band transform */ sbt_init(m); return 1; } /*---------------------------------------------------------*/ void audio_decode_info(MPEG *m, DEC_INFO * info) { *info = m->cup.decinfo; /* info return, call after init */ } /*---------------------------------------------------------*/ void decode_table_init(MPEG *m) { /* dummy for asm version compatability */ } /*---------------------------------------------------------*/ <file_sep>/src/drivers/enc28j60.c /* KallistiOS ##version## drivers/enc28j60.c Copyright (C) 2011-2014 SWAT */ #include <stdio.h> #include <string.h> #include <assert.h> #include <dc/asic.h> #include <dc/flashrom.h> #include <arch/irq.h> #include <arch/timer.h> #include <kos/net.h> #include <kos/netcfg.h> #include "drivers/enc28j60.h" #include "drivers/spi.h" /** * partitioning of the internal 8kB tx/rx buffers */ #define RX_START 0x0000 /* do not change this! */ #define TX_END (0x2000 - 1) /* do not change this! */ #define TX_START 0x1a00 #define RX_END (TX_START - 1) /** * register addresses consist of three parts: * bits 4-0: real address * bits 6-5: bank number * bit 7: skip a dummy byte (for mac/phy access) */ #define MASK_ADDR 0x1f #define MASK_BANK 0x60 #define MASK_DBRD 0x80 #define SHIFT_ADDR 0 #define SHIFT_BANK 5 #define SHIFT_DBRD 7 /* bank independent */ #define EIE 0x1b #define EIR 0x1c #define ESTAT 0x1d #define ECON2 0x1e #define ECON1 0x1f /* bank 0 */ #define ERDPTL (0x00 | 0x00) #define ERDPTH (0x01 | 0x00) #define EWRPTL (0x02 | 0x00) #define EWRPTH (0x03 | 0x00) #define ETXSTL (0x04 | 0x00) #define ETXSTH (0x05 | 0x00) #define ETXNDL (0x06 | 0x00) #define ETXNDH (0x07 | 0x00) #define ERXSTL (0x08 | 0x00) #define ERXSTH (0x09 | 0x00) #define ERXNDL (0x0a | 0x00) #define ERXNDH (0x0b | 0x00) #define ERXRDPTL (0x0c | 0x00) #define ERXRDPTH (0x0d | 0x00) #define ERXWRPTL (0x0e | 0x00) #define ERXWRPTH (0x0f | 0x00) #define EDMASTL (0x10 | 0x00) #define EDMASTH (0x11 | 0x00) #define EDMANDL (0x12 | 0x00) #define EDMANDH (0x13 | 0x00) #define EDMADSTL (0x14 | 0x00) #define EDMADSTH (0x15 | 0x00) #define EDMACSL (0x16 | 0x00) #define EDMACSH (0x17 | 0x00) /* bank 1 */ #define EHT0 (0x00 | 0x20) #define EHT1 (0x01 | 0x20) #define EHT2 (0x02 | 0x20) #define EHT3 (0x03 | 0x20) #define EHT4 (0x04 | 0x20) #define EHT5 (0x05 | 0x20) #define EHT6 (0x06 | 0x20) #define EHT7 (0x07 | 0x20) #define EPMM0 (0x08 | 0x20) #define EPMM1 (0x09 | 0x20) #define EPMM2 (0x0a | 0x20) #define EPMM3 (0x0b | 0x20) #define EPMM4 (0x0c | 0x20) #define EPMM5 (0x0d | 0x20) #define EPMM6 (0x0e | 0x20) #define EPMM7 (0x0f | 0x20) #define EPMCSL (0x10 | 0x20) #define EPMCSH (0x11 | 0x20) #define EPMOL (0x14 | 0x20) #define EPMOH (0x15 | 0x20) #define EWOLIE (0x16 | 0x20) #define EWOLIR (0x17 | 0x20) #define ERXFCON (0x18 | 0x20) #define EPKTCNT (0x19 | 0x20) /* bank 2 */ #define MACON1 (0x00 | 0x40 | 0x80) #define MACON2 (0x01 | 0x40 | 0x80) #define MACON3 (0x02 | 0x40 | 0x80) #define MACON4 (0x03 | 0x40 | 0x80) #define MABBIPG (0x04 | 0x40 | 0x80) #define MAIPGL (0x06 | 0x40 | 0x80) #define MAIPGH (0x07 | 0x40 | 0x80) #define MACLCON1 (0x08 | 0x40 | 0x80) #define MACLCON2 (0x09 | 0x40 | 0x80) #define MAMXFLL (0x0a | 0x40 | 0x80) #define MAMXFLH (0x0b | 0x40 | 0x80) #define MAPHSUP (0x0d | 0x40 | 0x80) #define MICON (0x11 | 0x40 | 0x80) #define MICMD (0x12 | 0x40 | 0x80) #define MIREGADR (0x14 | 0x40 | 0x80) #define MIWRL (0x16 | 0x40 | 0x80) #define MIWRH (0x17 | 0x40 | 0x80) #define MIRDL (0x18 | 0x40 | 0x80) #define MIRDH (0x19 | 0x40 | 0x80) /* bank 3 */ #define MAADR1 (0x00 | 0x60 | 0x80) #define MAADR0 (0x01 | 0x60 | 0x80) #define MAADR3 (0x02 | 0x60 | 0x80) #define MAADR2 (0x03 | 0x60 | 0x80) #define MAADR5 (0x04 | 0x60 | 0x80) #define MAADR4 (0x05 | 0x60 | 0x80) #define EBSTSD (0x06 | 0x60) #define EBSTCON (0x07 | 0x60) #define EBSTCSL (0x08 | 0x60) #define EBSTCSH (0x09 | 0x60) #define MISTAT (0x0a | 0x60 | 0x80) #define EREVID (0x12 | 0x60) #define ECOCON (0x15 | 0x60) #define EFLOCON (0x17 | 0x60) #define EPAUSL (0x18 | 0x60) #define EPAUSH (0x19 | 0x60) /* phy */ #define PHCON1 0x00 #define PHSTAT1 0x01 #define PHID1 0x02 #define PHID2 0x03 #define PHCON2 0x10 #define PHSTAT2 0x11 #define PHIE 0x12 #define PHIR 0x13 #define PHLCON 0x14 /* EIE */ #define EIE_INTIE 7 #define EIE_PKTIE 6 #define EIE_DMAIE 5 #define EIE_LINKIE 4 #define EIE_TXIE 3 #define EIE_WOLIE 2 #define EIE_TXERIE 1 #define EIE_RXERIE 0 /* EIR */ #define EIR_PKTIF 6 #define EIR_DMAIF 5 #define EIR_LINKIF 4 #define EIR_TXIF 3 #define EIR_WOLIF 2 #define EIR_TXERIF 1 #define EIR_RXERIF 0 /* ESTAT */ #define ESTAT_INT 7 #define ESTAT_LATECOL 4 #define ESTAT_RXBUSY 2 #define ESTAT_TXABRT 1 #define ESTAT_CLKRDY 0 /* ECON2 */ #define ECON2_AUTOINC 7 #define ECON2_PKTDEC 6 #define ECON2_PWRSV 5 #define ECON2_VRPS 4 /* ECON1 */ #define ECON1_TXRST 7 #define ECON1_RXRST 6 #define ECON1_DMAST 5 #define ECON1_CSUMEN 4 #define ECON1_TXRTS 3 #define ECON1_RXEN 2 #define ECON1_BSEL1 1 #define ECON1_BSEL0 0 /* EWOLIE */ #define EWOLIE_UCWOLIE 7 #define EWOLIE_AWOLIE 6 #define EWOLIE_PMWOLIE 4 #define EWOLIE_MPWOLIE 3 #define EWOLIE_HTWOLIE 2 #define EWOLIE_MCWOLIE 1 #define EWOLIE_BCWOLIE 0 /* EWOLIR */ #define EWOLIR_UCWOLIF 7 #define EWOLIR_AWOLIF 6 #define EWOLIR_PMWOLIF 4 #define EWOLIR_MPWOLIF 3 #define EWOLIR_HTWOLIF 2 #define EWOLIR_MCWOLIF 1 #define EWOLIR_BCWOLIF 0 /* ERXFCON */ #define ERXFCON_UCEN 7 #define ERXFCON_ANDOR 6 #define ERXFCON_CRCEN 5 #define ERXFCON_PMEN 4 #define ERXFCON_MPEN 3 #define ERXFCON_HTEN 2 #define ERXFCON_MCEN 1 #define ERXFCON_BCEN 0 /* MACON1 */ #define MACON1_LOOPBK 4 #define MACON1_TXPAUS 3 #define MACON1_RXPAUS 2 #define MACON1_PASSALL 1 #define MACON1_MARXEN 0 /* MACON2 */ #define MACON2_MARST 7 #define MACON2_RNDRST 6 #define MACON2_MARXRST 3 #define MACON2_RFUNRST 2 #define MACON2_MATXRST 1 #define MACON2_TFUNRST 0 /* MACON3 */ #define MACON3_PADCFG2 7 #define MACON3_PADCFG1 6 #define MACON3_PADCFG0 5 #define MACON3_TXCRCEN 4 #define MACON3_PHDRLEN 3 #define MACON3_HFRMEN 2 #define MACON3_FRMLNEN 1 #define MACON3_FULDPX 0 /* MACON4 */ #define MACON4_DEFER 6 #define MACON4_BPEN 5 #define MACON4_NOBKOFF 4 #define MACON4_LONGPRE 1 #define MACON4_PUREPRE 0 /* MAPHSUP */ #define MAPHSUP_RSTINTFC 7 #define MAPHSUP_RSTRMII 3 /* MICON */ #define MICON_RSTMII 7 /* MICMD */ #define MICMD_MIISCAN 1 #define MICMD_MIIRD 0 /* EBSTCON */ #define EBSTCON_PSV2 7 #define EBSTCON_PSV1 6 #define EBSTCON_PSV0 5 #define EBSTCON_PSEL 4 #define EBSTCON_TMSEL1 3 #define EBSTCON_TMSEL0 2 #define EBSTCON_TME 1 #define EBSTCON_BISTST 0 /* MISTAT */ #define MISTAT_NVALID 2 #define MISTAT_SCAN 1 #define MISTAT_BUSY 0 /* ECOCON */ #define ECOCON_COCON2 2 #define ECOCON_COCON1 1 #define ECOCON_COCON0 0 /* EFLOCON */ #define EFLOCON_FULDPXS 2 #define EFLOCON_FCEN1 1 #define EFLOCON_FCEN0 0 /* PHCON1 */ #define PHCON1_PRST 15 #define PHCON1_PLOOPBK 14 #define PHCON1_PPWRSV 11 #define PHCON1_PDPXMD 8 /* PHSTAT1 */ #define PHSTAT1_PFDPX 12 #define PHSTAT1_PHDPX 11 #define PHSTAT1_LLSTAT 2 #define PHSTAT1_JBSTAT 1 /* PHCON2 */ #define PHCON2_FRCLNK 14 #define PHCON2_TXDIS 13 #define PHCON2_JABBER 10 #define PHCON2_HDLDIS 8 /* PHSTAT2 */ #define PHSTAT2_TXSTAT 13 #define PHSTAT2_RXSTAT 12 #define PHSTAT2_COLSTAT 11 #define PHSTAT2_LSTAT 10 #define PHSTAT2_DPXSTAT 9 #define PHSTAT2_PLRITY 4 /* PHIE */ #define PHIE_PLINKIE 4 #define PHIE_PGEIE 1 /* PHIR */ #define PHIR_LINKIF 4 #define PHIR_PGIF 2 /* PHLCON */ #define PHLCON_LACFG3 11 #define PHLCON_LACFG2 10 #define PHLCON_LACFG1 9 #define PHLCON_LACFG0 8 #define PHLCON_LBCFG3 7 #define PHLCON_LBCFG2 6 #define PHLCON_LBCFG1 5 #define PHLCON_LBCFG0 4 #define PHLCON_LFRQ1 3 #define PHLCON_LFRQ0 2 #define PHLCON_STRCH 1 #define ENC28J60_FULL_DUPLEX 1 /** * \internal * Microchip ENC28J60 I/O implementation * */ #define enc28j60_rcr(address) spi_cc_send_byte(0x00 | (address)) #define enc28j60_rbm() spi_cc_send_byte(0x3a) #define enc28j60_wcr(address) spi_cc_send_byte(0x40 | (address)) #define enc28j60_wbm(address) spi_cc_send_byte(0x7a) #define enc28j60_bfs(address) spi_cc_send_byte(0x80 | (address)) #define enc28j60_bfc(address) spi_cc_send_byte(0xa0 | (address)) #define enc28j60_sc() spi_cc_send_byte(0xff) static int spi_cs = SPI_CS_ENC28J60; static int spi_reset = -1; static int old_spi_delay = SPI_DEFAULT_DELAY; #define enc28j60_select() do { \ spi_cs_on(spi_cs); \ old_spi_delay = spi_get_delay(); \ if(old_spi_delay != SPI_ENC28J60_DELAY) \ spi_set_delay(SPI_ENC28J60_DELAY); \ } while(0) #define enc28j60_deselect() do { \ if(old_spi_delay != SPI_ENC28J60_DELAY) \ spi_set_delay(old_spi_delay); \ spi_cs_off(spi_cs); \ } while(0) #define enc28j60_reset_on() spi_cs_on(spi_reset) #define enc28j60_reset_off() spi_cs_off(spi_reset) //#define ENC_DEBUG 1 /** * \internal * Initializes the SPI interface to the ENC28J60 chips. */ void enc28j60_io_init(int cs, int rs) { if(cs > -1) { spi_cs = cs; } if(rs > -1) { spi_reset = rs; } /* Initialize SPI */ spi_init(0); } /** * \internal * Forces a reset to the ENC28J60. * * After the reset a reinitialization is necessary. */ void enc28j60_reset() { enc28j60_reset_on(); thd_sleep(10); enc28j60_reset_off(); thd_sleep(10); } /** * \internal * Reads the value of a hardware register. * * \param[in] address The address of the register to read. * \returns The register value. */ uint8 enc28j60_read(uint8 address) { uint8 result; /* switch to register bank */ enc28j60_bank((address & MASK_BANK) >> SHIFT_BANK); /* read from address */ enc28j60_select(); enc28j60_rcr((address & MASK_ADDR) >> SHIFT_ADDR); if(address & MASK_DBRD) spi_cc_rec_byte(); result = spi_cc_rec_byte(); enc28j60_deselect(); return result; } /** * \internal * Writes the value of a hardware register. * * \param[in] address The address of the register to write. * \param[in] value The value to write into the register. */ void enc28j60_write(uint8 address, uint8 value) { /* switch to register bank */ enc28j60_bank((address & MASK_BANK) >> SHIFT_BANK); /* write to address */ enc28j60_select(); enc28j60_wcr((address & MASK_ADDR) >> SHIFT_ADDR); spi_cc_send_byte(value); enc28j60_deselect(); } /** * \internal * Clears bits in a hardware register. * * Performs a NAND operation on the current register value * and the given bitmask. * * \param[in] address The address of the register to alter. * \param[in] bits A bitmask specifiying the bits to clear. */ void enc28j60_clear_bits(uint8 address, uint8 bits) { /* switch to register bank */ enc28j60_bank((address & MASK_BANK) >> SHIFT_BANK); /* write to address */ enc28j60_select(); enc28j60_bfc((address & MASK_ADDR) >> SHIFT_ADDR); spi_cc_send_byte(bits); enc28j60_deselect(); } /** * \internal * Sets bits in a hardware register. * * Performs an OR operation on the current register value * and the given bitmask. * * \param[in] address The address of the register to alter. * \param[in] bits A bitmask specifiying the bits to set. */ void enc28j60_set_bits(uint8 address, uint8 bits) { /* switch to register bank */ enc28j60_bank((address & MASK_BANK) >> SHIFT_BANK); /* write to address */ enc28j60_select(); enc28j60_bfs((address & MASK_ADDR) >> SHIFT_ADDR); spi_cc_send_byte(bits); enc28j60_deselect(); } /** * \internal * Reads the value of a hardware PHY register. * * \param[in] address The address of the PHY register to read. * \returns The register value. */ uint16 enc28j60_read_phy(uint8 address) { enc28j60_write(MIREGADR, address); enc28j60_set_bits(MICMD, (1 << MICMD_MIIRD)); thd_sleep(10); while(enc28j60_read(MISTAT) & (1 << MISTAT_BUSY)); enc28j60_clear_bits(MICMD, (1 << MICMD_MIIRD)); return ((uint16_t) enc28j60_read(MIRDH)) << 8 | ((uint16_t) enc28j60_read(MIRDL)); } /** * \internal * Writes the value to a hardware PHY register. * * \param[in] address The address of the PHY register to write. * \param[in] value The value to write into the register. */ void enc28j60_write_phy(uint8 address, uint16 value) { enc28j60_write(MIREGADR, address); enc28j60_write(MIWRL, value & 0xff); enc28j60_write(MIWRH, value >> 8); thd_sleep(10); while(enc28j60_read(MISTAT) & (1 << MISTAT_BUSY)); } /** * \internal * Reads a byte from the RAM buffer at the current position. * * \returns The byte read from the current RAM position. */ uint8 enc28j60_read_buffer_byte() { uint8_t b; enc28j60_select(); enc28j60_rbm(); b = spi_cc_rec_byte(); enc28j60_deselect(); return b; } /** * \internal * Writes a byte to the RAM buffer at the current position. * * \param[in] b The data byte to write. */ void enc28j60_write_buffer_byte(uint8 b) { enc28j60_select(); enc28j60_wbm(); spi_cc_send_byte(b); enc28j60_deselect(); } /** * \internal * Reads multiple bytes from the RAM buffer. * * \param[out] buffer A pointer to the buffer which receives the data. * \param[in] buffer_len The buffer length and number of bytes to read. */ void enc28j60_read_buffer(uint8* buffer, uint16 buffer_len) { enc28j60_select(); enc28j60_rbm(); spi_cc_rec_data(buffer, buffer_len); enc28j60_deselect(); } /** * \internal * Writes multiple bytes to the RAM buffer. * * \param[in] buffer A pointer to the buffer containing the data to write. * \param[in] buffer_len The number of bytes to write. */ void enc28j60_write_buffer(const uint8* buffer, uint16 buffer_len) { enc28j60_select(); enc28j60_wbm(); spi_cc_send_data(buffer, buffer_len); enc28j60_deselect(); } /** * Switches the hardware register bank. * * \param[in] num The index of the register bank to switch to. */ void enc28j60_bank(uint8 num) { static uint8 bank = 0xff; if(num == bank) return; /* clear bank bits */ enc28j60_select(); enc28j60_bfc(ECON1); spi_cc_send_byte(0x03); enc28j60_deselect(); /* set bank bits */ enc28j60_select(); enc28j60_bfs(ECON1); spi_cc_send_byte(num); enc28j60_deselect(); bank = num; } /** * Reset and initialize the ENC28J60 and starts packet transmission/reception. * * \param[in] mac A pointer to a 6-byte buffer containing the MAC address. * \returns \c true on success, \c false on failure. */ int enc28j60_init(const uint8* mac) { /* init i/o */ enc28j60_io_init(spi_cs, spi_reset); /* reset device */ enc28j60_reset(); /* configure rx/tx buffers */ enc28j60_write(ERXSTL, RX_START & 0xff); enc28j60_write(ERXSTH, RX_START >> 8); enc28j60_write(ERXNDL, RX_END & 0xff); enc28j60_write(ERXNDH, RX_END >> 8); enc28j60_write(ERXWRPTL, RX_START & 0xff); enc28j60_write(ERXWRPTH, RX_START >> 8); enc28j60_write(ERXRDPTL, RX_START & 0xff); enc28j60_write(ERXRDPTH, RX_START >> 8); /* configure frame filters */ enc28j60_write(ERXFCON, (1 << ERXFCON_UCEN) | /* accept unicast packets */ (1 << ERXFCON_CRCEN) | /* accept packets with valid CRC only */ (0 << ERXFCON_PMEN) | /* no pattern matching */ (0 << ERXFCON_MPEN) | /* ignore magic packets */ (0 << ERXFCON_HTEN) | /* disable hash table filter */ (0 << ERXFCON_MCEN) | /* ignore multicast packets */ (1 << ERXFCON_BCEN) | /* accept broadcast packets */ (0 << ERXFCON_ANDOR) /* packets must meet at least one criteria */ ); /* configure MAC */ enc28j60_clear_bits(MACON2, (1 << MACON2_MARST)); enc28j60_write(MACON1, (0 << MACON1_LOOPBK) | #if ENC28J60_FULL_DUPLEX (1 << MACON1_TXPAUS) | (1 << MACON1_RXPAUS) | #else (0 << MACON1_TXPAUS) | (0 << MACON1_RXPAUS) | #endif (0 << MACON1_PASSALL) | (1 << MACON1_MARXEN) ); enc28j60_write(MACON3, (1 << MACON3_PADCFG2) | (1 << MACON3_PADCFG1) | (1 << MACON3_PADCFG0) | (1 << MACON3_TXCRCEN) | (0 << MACON3_PHDRLEN) | (0 << MACON3_HFRMEN) | (1 << MACON3_FRMLNEN) | #if ENC28J60_FULL_DUPLEX (1 << MACON3_FULDPX) #else (0 << MACON3_FULDPX) #endif ); enc28j60_write(MAMXFLL, 0xee); enc28j60_write(MAMXFLH, 0x05); #if ENC28J60_FULL_DUPLEX enc28j60_write(MABBIPG, 0x15); #else enc28j60_write(MABBIPG, 0x12); #endif enc28j60_write(MAIPGL, 0x12); #if !ENC28J60_FULL_DUPLEX enc28j60_write(MAIPGH, 0x0c); #endif enc28j60_write(MAADR0, mac[5]); enc28j60_write(MAADR1, mac[4]); enc28j60_write(MAADR2, mac[3]); enc28j60_write(MAADR3, mac[2]); enc28j60_write(MAADR4, mac[1]); enc28j60_write(MAADR5, mac[0]); /* configure PHY */ enc28j60_write_phy(PHLCON, (1 << PHLCON_LACFG3) | (1 << PHLCON_LACFG2) | (0 << PHLCON_LACFG1) | (1 << PHLCON_LACFG0) | (0 << PHLCON_LBCFG3) | (1 << PHLCON_LBCFG2) | (0 << PHLCON_LBCFG1) | (1 << PHLCON_LBCFG0) | (0 << PHLCON_LFRQ1) | (0 << PHLCON_LFRQ0) | (1 << PHLCON_STRCH) ); enc28j60_write_phy(PHCON1, (0 << PHCON1_PRST) | (0 << PHCON1_PLOOPBK) | (0 << PHCON1_PPWRSV) | #if ENC28J60_FULL_DUPLEX (1 << PHCON1_PDPXMD) #else (0 << PHCON1_PDPXMD) #endif ); enc28j60_write_phy(PHCON2, (0 << PHCON2_FRCLNK) | (0 << PHCON2_TXDIS) | (0 << PHCON2_JABBER) | (1 << PHCON2_HDLDIS) ); /* start receiving packets */ enc28j60_set_bits(ECON2, (1 << ECON2_AUTOINC)); enc28j60_set_bits(ECON1, (1 << ECON1_RXEN)); return 1; } int enc28j60_link_up() { uint16 phstat1 = enc28j60_read_phy(PHSTAT1); return phstat1 & (1 << PHSTAT1_LLSTAT); } /** * \internal * Microchip ENC28J60 packet handling * */ static uint16 packet_ptr = RX_START; /** * Fetches a pending packet from the RAM buffer of the ENC28J60. * * The packet is written into the given buffer and the size of the packet * (ethernet header plus payload, exclusive the CRC) is returned. * * Zero is returned in the following cases: * - There is no packet pending. * - The packet is too large to completely fit into the buffer. * - Some error occured. * * \param[out] buffer The pointer to the buffer which receives the packet. * \param[in] buffer_len The length of the buffer. * \returns The packet size in bytes on success, \c 0 in the cases noted above. */ uint16 enc28j60_receive_packet(uint8* buffer, uint16 buffer_len) { if(!enc28j60_read(EPKTCNT)) return 0; /* set read pointer */ enc28j60_write(ERDPTL, packet_ptr & 0xff); enc28j60_write(ERDPTH, packet_ptr >> 8); /* read pointer to next packet */ packet_ptr = ((uint16_t) enc28j60_read_buffer_byte()) | ((uint16_t) enc28j60_read_buffer_byte()) << 8; /* read packet length */ uint16 packet_len = ((uint16_t) enc28j60_read_buffer_byte()) | ((uint16_t) enc28j60_read_buffer_byte()) << 8; packet_len -= 4; /* ignore CRC */ /* read receive status */ enc28j60_read_buffer_byte(); enc28j60_read_buffer_byte(); /* read packet */ if(packet_len <= buffer_len) enc28j60_read_buffer(buffer, packet_len); /* free packet memory */ /* errata #13 */ uint16 packet_ptr_errata = packet_ptr - 1; if(packet_ptr_errata < RX_START || packet_ptr_errata > RX_END) packet_ptr_errata = RX_END; enc28j60_write(ERXRDPTL, packet_ptr_errata & 0xff); enc28j60_write(ERXRDPTH, packet_ptr_errata >> 8); /* decrement packet counter */ enc28j60_set_bits(ECON2, (1 << ECON2_PKTDEC)); if(packet_len <= buffer_len) return packet_len; else return 0; } /** * Writes a packet to the RAM buffer of the ENC28J60 and starts transmission. * * The packet buffer contains the ethernet header and the payload without CRC. * The checksum is automatically generated by the on-chip calculator. * * \param[in] buffer A pointer to the buffer containing the packet to be sent. * \param[in] buffer_len The length of the ethernet packet header plus payload. * \returns \c true if the packet was sent, \c false otherwise. */ int enc28j60_send_packet(const uint8* buffer, uint16 buffer_len) { if(!buffer || !buffer_len) return 0; /* errata #12 */ if(enc28j60_read(EIR) & (1 << EIR_TXERIF)) { enc28j60_set_bits(ECON1, (1 << ECON1_TXRST)); enc28j60_clear_bits(ECON1, (1 << ECON1_TXRST)); } /* wait until previous packet was sent */ while(enc28j60_read(ECON1) & (1 << ECON1_TXRTS)); /* set start of packet */ enc28j60_write(ETXSTL, TX_START & 0xff); enc28j60_write(ETXSTH, TX_START >> 8); /* set end of packet */ enc28j60_write(ETXNDL, (TX_START + buffer_len) & 0xff); enc28j60_write(ETXNDH, (TX_START + buffer_len) >> 8); /* set write pointer */ enc28j60_write(EWRPTL, TX_START & 0xff); enc28j60_write(EWRPTH, TX_START >> 8); /* per packet control byte */ enc28j60_write_buffer_byte(0x00); /* send packet */ enc28j60_write_buffer(buffer, buffer_len); /* start transmission */ enc28j60_set_bits(ECON1, (1 << ECON1_TXRTS)); return 1; } /****************************************************************************/ /* Netcore interface */ netif_t enc_if; static void set_ipv6_lladdr() { /* Set up the IPv6 link-local address. This is done in accordance with Section 4/5 of RFC 2464 based on the MAC Address of the adapter. */ enc_if.ip6_lladdr.__s6_addr.__s6_addr8[0] = 0xFE; enc_if.ip6_lladdr.__s6_addr.__s6_addr8[1] = 0x80; enc_if.ip6_lladdr.__s6_addr.__s6_addr8[8] = enc_if.mac_addr[0] ^ 0x02; enc_if.ip6_lladdr.__s6_addr.__s6_addr8[9] = enc_if.mac_addr[1]; enc_if.ip6_lladdr.__s6_addr.__s6_addr8[10] = enc_if.mac_addr[2]; enc_if.ip6_lladdr.__s6_addr.__s6_addr8[11] = 0xFF; enc_if.ip6_lladdr.__s6_addr.__s6_addr8[12] = 0xFE; enc_if.ip6_lladdr.__s6_addr.__s6_addr8[13] = enc_if.mac_addr[3]; enc_if.ip6_lladdr.__s6_addr.__s6_addr8[14] = enc_if.mac_addr[4]; enc_if.ip6_lladdr.__s6_addr.__s6_addr8[15] = enc_if.mac_addr[5]; } static int enc_if_detect(netif_t * self) { if (self->flags & NETIF_DETECTED) return 0; uint8 reg; /* init i/o */ enc28j60_io_init(spi_cs, spi_reset); /* reset device */ enc28j60_reset(); reg = enc28j60_read(EREVID); if(reg == 0x00 || reg == 0xff) { #ifdef ENC_DEBUG dbglog(DBG_DEBUG, "DS_ENC28J60: Can't detect rev: %02x\n", reg); #endif return -1; //return 0; } //#ifdef ENC_DEBUG dbglog(DBG_INFO, "DS_ENC28J60: Detected rev: %02x\n", reg); //#endif self->flags |= NETIF_DETECTED; return 0; } static int enc_if_init(netif_t * self) { if (self->flags & NETIF_INITIALIZED) return 0; //Initialise the device uint8 mac[6] = {'D', 'S', '4', 'N', 'E', 'T'}; enc28j60_init(mac); #ifdef ENC_DEBUG dbglog(DBG_DEBUG, "DS_ENC28J60: Inited\n"); #endif memcpy(self->mac_addr, mac, 6); set_ipv6_lladdr(); self->flags |= NETIF_INITIALIZED; return 0; } static int enc_if_shutdown(netif_t * self) { if (!(self->flags & NETIF_INITIALIZED)) return 0; enc28j60_reset(); #ifdef ENC_DEBUG dbglog(DBG_DEBUG, "DS_ENC28J60: Shutdown\n"); #endif self->flags &= ~(NETIF_DETECTED | NETIF_INITIALIZED | NETIF_RUNNING); return 0; } static int enc_if_start(netif_t * self) { if (!(self->flags & NETIF_INITIALIZED)) return -1; self->flags |= NETIF_RUNNING; /* start receiving packets */ //enc28j60_set_bits(ECON1, (1 << ECON1_RXEN)); //enc28j60_write_phy(PHIE, PHIE_PGEIE | PHIE_PLNKIE); //enc28j60_clear_bits(EIR, EIR_DMAIF | EIR_LINKIF | EIR_TXIF | EIR_TXERIF | EIR_RXERIF | EIR_PKTIF); //enc28j60_write(EIE, EIE_INTIE | EIE_PKTIE | EIE_LINKIE | EIE_TXIE | EIE_TXERIE | EIE_RXERIE); #ifdef ENC_DEBUG dbglog(DBG_DEBUG, "DS_ENC28J60: Start\n"); #endif return 0; } static int enc_if_stop(netif_t * self) { if (!(self->flags & NETIF_RUNNING)) return -1; self->flags &= ~NETIF_RUNNING; /* stop receiving packets */ //enc28j60_write(EIE, 0x00); enc28j60_clear_bits(ECON1, (1 << ECON1_RXEN)); #ifdef ENC_DEBUG dbglog(DBG_DEBUG, "DS_ENC28J60: Stop\n"); #endif return 0; } static int enc_if_tx(netif_t * self, const uint8 * data, int len, int blocking) { if (!(self->flags & NETIF_RUNNING)) return -1; #ifdef ENC_DEBUG dbglog(DBG_INFO, "DS_ENC28J60: Send packet "); #endif if(!enc28j60_send_packet(data, len)) { #ifdef ENC_DEBUG dbglog(DBG_DEBUG, "Error\n"); #endif return -1; } #ifdef ENC_DEBUG dbglog(DBG_DEBUG, "OK\n"); #endif return 0; } /* We'll auto-commit for now */ static int enc_if_tx_commit(netif_t * self) { return 0; } static int enc_if_rx_poll(netif_t * self) { uint len = 1514; uint8 pkt[1514]; #ifdef ENC_DEBUG dbglog(DBG_DEBUG, "DS_ENC28J60: Receive packet "); #endif len = enc28j60_receive_packet(pkt, len); if(!len) { #ifdef ENC_DEBUG dbglog(DBG_DEBUG, "Error\n"); #endif return -1; } #ifdef ENC_DEBUG dbglog(DBG_INFO, "OK\n"); #endif /* Submit it for processing */ net_input(&enc_if, pkt, len); return 0; } /* Don't need to hook anything here yet */ static int enc_if_set_flags(netif_t * self, uint32 flags_and, uint32 flags_or) { self->flags = (self->flags & flags_and) | flags_or; return 0; } static int enc_if_set_mc(netif_t *self, const uint8 *list, int count) { #ifdef ENC_DEBUG dbglog(DBG_DEBUG, "DS_ENC28J60: Set multicast: %d\n", count); #endif //return -1; if(count == 0) { enc28j60_write(ERXFCON, (1 << ERXFCON_UCEN) | /* accept unicast packets */ (1 << ERXFCON_CRCEN) | /* accept packets with valid CRC only */ (0 << ERXFCON_PMEN) | /* no pattern matching */ (0 << ERXFCON_MPEN) | /* ignore magic packets */ (0 << ERXFCON_HTEN) | /* disable hash table filter */ (0 << ERXFCON_MCEN) | /* ignore multicast packets */ (1 << ERXFCON_BCEN) | /* accept broadcast packets */ (0 << ERXFCON_ANDOR) /* packets must meet at least one criteria */ ); } else { enc28j60_write(ERXFCON, (1 << ERXFCON_UCEN) | /* accept unicast packets */ (1 << ERXFCON_CRCEN) | /* accept packets with valid CRC only */ (0 << ERXFCON_PMEN) | /* no pattern matching */ (0 << ERXFCON_MPEN) | /* ignore magic packets */ (0 << ERXFCON_HTEN) | /* disable hash table filter */ (1 << ERXFCON_MCEN) | /* accept multicast packets */ (1 << ERXFCON_BCEN) | /* accept broadcast packets */ (0 << ERXFCON_ANDOR) /* packets must meet at least one criteria */ ); } return 0; } /* Set ISP configuration from the flashrom, as long as we're configured staticly */ static void enc_set_ispcfg() { uint8 ip_addr[4] = {192, 168, 1, 110}; uint8 netmask[4] = {255, 255, 255, 0}; uint8 gateway[4] = {192, 168, 1, 1}; uint8 broadcast[4] = {0, 0, 0, 0}; memcpy(enc_if.ip_addr, &ip_addr, 4); memcpy(enc_if.netmask, &netmask, 4); memcpy(enc_if.gateway, &gateway, 4); memcpy(enc_if.broadcast, &broadcast, 4); #ifdef ENC_DEBUG dbglog(DBG_DEBUG, "DS_ENC28J60: Default IP=%d.%d.%d.%d\n", enc_if.ip_addr[0], enc_if.ip_addr[1], enc_if.ip_addr[2], enc_if.ip_addr[3]); #endif flashrom_ispcfg_t isp; uint32 fields = FLASHROM_ISP_IP | FLASHROM_ISP_NETMASK | FLASHROM_ISP_BROADCAST | FLASHROM_ISP_GATEWAY; if(flashrom_get_ispcfg(&isp) == -1) return; if((isp.valid_fields & fields) != fields) return; if(isp.method != FLASHROM_ISP_STATIC) return; memcpy(enc_if.ip_addr, isp.ip, 4); memcpy(enc_if.netmask, isp.nm, 4); memcpy(enc_if.gateway, isp.gw, 4); memcpy(enc_if.broadcast, isp.bc, 4); #ifdef ENC_DEBUG dbglog(DBG_DEBUG, "enc: Setting up IP=%d.%d.%d.%d\n", enc_if.ip_addr[0], enc_if.ip_addr[1], enc_if.ip_addr[2], enc_if.ip_addr[3]); #endif } /* Initialize */ int enc28j60_if_init(int cs, int rs) { if(cs > -1) { spi_cs = cs; } if(rs > -1) { spi_reset = rs; } /* Setup the netcore structure */ enc_if.name = "enc"; enc_if.descr = "ENC28J60"; enc_if.index = 0; enc_if.dev_id = 0; enc_if.flags = NETIF_NO_FLAGS; memset(enc_if.ip_addr, 0, sizeof(enc_if.ip_addr)); memset(enc_if.netmask, 0, sizeof(enc_if.netmask)); memset(enc_if.gateway, 0, sizeof(enc_if.gateway)); memset(enc_if.broadcast, 0, sizeof(enc_if.broadcast)); memset(enc_if.dns, 0, sizeof(enc_if.dns)); enc_if.mtu = 1500; /* The Ethernet v2 MTU */ memset(&enc_if.ip6_lladdr, 0, sizeof(enc_if.ip6_lladdr)); enc_if.ip6_addrs = NULL; enc_if.ip6_addr_count = 0; memset(&enc_if.ip6_gateway, 0, sizeof(enc_if.ip6_gateway)); enc_if.mtu6 = 0; enc_if.hop_limit = 0; enc_if.if_detect = enc_if_detect; enc_if.if_init = enc_if_init; enc_if.if_shutdown = enc_if_shutdown; enc_if.if_start = enc_if_start; enc_if.if_stop = enc_if_stop; enc_if.if_tx = enc_if_tx; enc_if.if_tx_commit = enc_if_tx_commit; enc_if.if_rx_poll = enc_if_rx_poll; enc_if.if_set_flags = enc_if_set_flags; enc_if.if_set_mc = enc_if_set_mc; /* Attempt to set up our IP address et al from the flashrom */ enc_set_ispcfg(); /* Append it to the chain */ return net_reg_device(&enc_if); } /* Shutdown */ int enc28j60_if_shutdown() { enc_if_shutdown(&enc_if); return 0; } <file_sep>/modules/luaSQL/Makefile # # luaSQL module for DreamShell # Copyright (C) 2011-2014 SWAT # http://www.dc-swat.ru # TARGET_NAME = luaSQL OBJS = module.o src/luasql.o src/ls_sqlite3.o DBG_LIBS = -lds -lsqlite3 EXPORTS_FILE = exports.txt VER_MAJOR = 2 VER_MINOR = 1 VER_MICRO = 1 all: rm-elf include ../../sdk/Makefile.loadable KOS_CFLAGS += -I$(DS_SDK)/include/lua rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/firmware/isoldr/syscalls/Makefile # # DreamShell ISO Loader (low-level version) # Copyright (C) 2009-2022 SWAT # Copyright (C) 2019 megavolt85 # TARGET = 0x8c000000 SYSCALLOBJS = syscalls.o flash_font_sys.o syscallsc.o SYSCALLBIN = syscalls TARGETPREFIX = sh-elf TARGETCC = $(TARGETPREFIX)-gcc TARGETOBJCOPY = $(TARGETPREFIX)-objcopy TARGETLD = $(TARGETPREFIX)-ld TARGETAS = $(TARGETPREFIX)-as TARGETSIZE = $(TARGETPREFIX)-size TARGETLDFLAGS = -Wl,--gc-sections -Tshlelf.xc -nostartfiles -nostdlib -nodefaultlibs TARGETCFLAGS = -ml -m4-single-only -ffunction-sections -fdata-sections -ffreestanding \ -fno-builtin -fno-strict-aliasing -fomit-frame-pointer \ -Wall -std=c11 -Wextra -Werror # TARGETCFLAGS += -DLOG # SYSCALLOBJS += log.o memcpy.o TARGETCFLAGS += -I./include LIBS = -lgcc INSTALL_PATH = ../../../build/firmware/isoldr %.bin: %.elf $(TARGETOBJCOPY) -O binary $< $@ %.o: %.c $(TARGETCC) $(TARGETCFLAGS) -Os $(INCLUDE) -c $< -o $@ %.o: %.s $(TARGETCC) $(TARGETCFLAGS) $(INCLUDE) -o $@ -c $< %.o: %.S $(TARGETCC) $(TARGETCFLAGS) $(INCLUDE) -o $@ -c $< all: clean $(SYSCALLBIN).bin clean: rm -f $(SYSCALLOBJS) $(SYSCALLBIN).elf $(SYSCALLBIN).bin $(SYSCALLBIN).elf: $(SYSCALLOBJS) $(TARGETCC) $(TARGETCFLAGS) $(TARGETLDFLAGS) -o $(SYSCALLBIN).elf $(SYSCALLOBJS) $(LIBS) install: $(SYSCALLBIN).bin -mkdir -p $(INSTALL_PATH) cp $(SYSCALLBIN).bin $(INSTALL_PATH) <file_sep>/modules/ppp/Makefile # # PPP module for DreamShell # Copyright (C) 2014-2019 SWAT # http://www.dc-swat.ru # TARGET_NAME = ppp MODEM_DIR = $(KOS_BASE)/kernel/arch/dreamcast/hardware/modem OBJS = module.o $(MODEM_DIR)/mdata.o $(MODEM_DIR)/mintr.o \ $(MODEM_DIR)/modem.o $(MODEM_DIR)/chainbuf.o LIBS = -lppp DBG_LIBS = -lds EXPORTS_FILE = exports.txt VER_MAJOR = 1 VER_MINOR = 0 VER_MICRO = 1 all: rm-elf include ../../sdk/Makefile.loadable KOS_CFLAGS += $(KOS_CSTD) rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/firmware/aica/dec.h int init_mp3(); int init_aac(); void shutdown_mp3(); void shutdown_aac(); int decode_mp3(aica_decoder_t *dat);<file_sep>/include/gui.h /** * \file gui.h * \brief DreamShell GUI * \date 2006-2023 * \author SWAT www.dc-swat.ru */ #ifndef _DS_GUI_H #define _DS_GUI_H #include "video.h" #include "list.h" #include "events.h" #include "SDL/SDL_gui.h" typedef struct MouseCursor { SDL_Surface *bg; SDL_Surface *cursor; SDL_Rect src, dst; int draw; } MouseCursor_t; /* Mouse cursor */ MouseCursor_t *CreateMouseCursor(const char *fn, /* or */ SDL_Surface *surface); void DestroyMouseCursor(MouseCursor_t *c); void DrawMouseCursor(MouseCursor_t *c); void DrawMouseCursorEvent(MouseCursor_t *c, SDL_Event *event); void SetActiveMouseCursor(MouseCursor_t *c); MouseCursor_t *GetActiveMouseCursor(); void UpdateActiveMouseCursor(); void DrawActiveMouseCursor(); /* Virtual keyboard from vkb module */ int VirtKeyboardInit(); void VirtKeyboardShutdown(); int VirtKeyboardIsVisible(); void VirtKeyboardReDraw(); void VirtKeyboardShow(); void VirtKeyboardHide(); void VirtKeyboardToggle(); /* Main GUI */ int InitGUI(); void ShutdownGUI(); int GUI_Object2Trash(GUI_Object *object); void GUI_ClearTrash(); /* GUI utils */ Uint32 colorHexToRGB(char *color, SDL_Color *clr); SDL_Color Uint32ToColor(Uint32 c); Uint32 ColorToUint32(SDL_Color c); Uint32 MapHexColor(char *color, SDL_PixelFormat *format); SDL_Surface *SDL_ImageLoad(const char *filename, SDL_Rect *selection); #endif <file_sep>/commands/bin2iso/Makefile # DreamShell ##version## # # Copyright (C) 2011-2013 SWAT # DreamShell command Makefile # http://www.dc-swat.ru # TARGET = bin2iso OBJS = main.o DBG_LIBS = -lds all: rm-elf include ../../sdk/Makefile.loadable rm-elf: -rm -f $(TARGET) install: $(TARGET) -rm $(DS_BUILD)/cmds/$(TARGET) cp $(TARGET) $(DS_BUILD)/cmds/$(TARGET) <file_sep>/modules/xvid/Makefile # # xvid module for DreamShell # Copyright (C) 2011-2022 SWAT # http://www.dc-swat.ru # TARGET_NAME = xvid OBJS = module.o DBG_LIBS = -lds LIBS = -lxvidcore EXPORTS_FILE = exports.txt VER_MAJOR = 1 VER_MINOR = 0 VER_MICRO = 0 VER_BUILD = 0 KOS_LIB_PATHS += -L./xvidcore/build/generic/=build all: rm-elf library install library: cd ./xvidcore/build/generic && make library_clean: cd ./xvidcore/build/generic && make clean include ../../sdk/Makefile.loadable rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) ln -nsf $(DS_SDK)/lib/$(TARGET_LIB) $(DS_SDK)/lib/libxvidcore.a <file_sep>/sdk/bin/src/gdiopt/Makefile ifeq ($(LBITS),64) INCS = -I/usr/include/x86_64-linux-gnu -I/usr/include/$(gcc -print-multiarch) LIBS = -L/usr/lib32 CC = gcc -m32 $(INCS) LD = gcc -m32 $(LIBS) else CC = gcc LD = gcc endif CFLAGS = -O2 INSTALL = install DESTDIR = ../.. all : gdiopt ciso : gdiopt.o $(LD) -o gdiopt gdiopt.o ciso.o : gdiopt.c $(CC) -o gdiopt.o -c gdiopt.c install : gdiopt $(INSTALL) -m 755 gdiopt $(DESTDIR)/gdiopt run : gdiopt @./gdiopt test.gdi disk.gdi clean: rm -rf *.o rm -rf gdiopt <file_sep>/modules/isofs/map2dev.c /** * Copyright (c) 2015-2020 by SWAT <<EMAIL>> www.dc-swat.ru * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <ds.h> #include <isofs/isofs.h> #include <isofs/ciso.h> #include <isofs/cdi.h> #include <isofs/gdi.h> //#define DEBUG 1 #define SECBUF_COUNT 32 int fs_iso_map2dev(const char *filename, kos_blockdev_t *dev) { file_t fd, fdi; uint8 *data; uint32 image_type = 0; uint32 image_hdr = 0; uint32 total_length = 0; uint32 lba = 150; uint32 sector = lba; const char mp[] = "/ifsm2d"; if(dev->init(dev) < 0) { ds_printf("DS_ERROR: Can't initialize device\n"); return -1; } if(fs_iso_mount(mp, filename) < 0) { return -1; } fd = fs_iso_first_file(mp); if(fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open first file\n"); fs_iso_unmount(mp); return -1; } fs_ioctl(fd, ISOFS_IOCTL_GET_IMAGE_TYPE, &image_type); fs_ioctl(fd, ISOFS_IOCTL_GET_IMAGE_HEADER_PTR, &image_hdr); fs_ioctl(fd, ISOFS_IOCTL_GET_IMAGE_FD, &fdi); fs_ioctl(fd, ISOFS_IOCTL_GET_DATA_TRACK_LBA, &lba); fs_ioctl(fd, ISOFS_IOCTL_GET_TRACK_SECTOR_COUNT, &total_length); fs_close(fd); total_length += lba; data = memalign(32, SECBUF_COUNT * 2048); if(data == NULL) { ds_printf("DS_ERROR: No free memory\n"); fs_iso_unmount(mp); return -1; } memset_sh4(data, 0, SECBUF_COUNT * 2048); for(sector = lba; sector < total_length; sector += SECBUF_COUNT) { #ifdef DEBUG dbglog(DBG_DEBUG, "%s: read from %ld\n", __func__, sector); #endif switch(image_type) { case ISOFS_IMAGE_TYPE_CSO: case ISOFS_IMAGE_TYPE_ZSO: ciso_read_sectors((CISO_header_t*)image_hdr, fdi, data, sector, SECBUF_COUNT); break; case ISOFS_IMAGE_TYPE_CDI: cdi_read_sectors((CDI_header_t*)image_hdr, fdi, data, sector, SECBUF_COUNT); break; case ISOFS_IMAGE_TYPE_GDI: gdi_read_sectors((GDI_header_t*)image_hdr, data, sector, SECBUF_COUNT); break; case ISOFS_IMAGE_TYPE_ISO: default: fs_seek(fdi, ((sector - lba) * 2048), SEEK_SET); fs_read(fdi, data, SECBUF_COUNT * 2048); break; } #ifdef DEBUG dbglog(DBG_DEBUG, "%s: write to %ld\n", __func__, (sector - lba) * 4); #endif if(dev->write_blocks(dev, (sector - lba) * 4, SECBUF_COUNT * 4, data) < 0) { ds_printf("DS_ERROR: Can't write to device\n"); break; } } dev->flush(dev); fs_iso_unmount(mp); return 0; } <file_sep>/modules/http/module.c /* DreamShell ##version## module.c - http module Copyright (C)2011-2014 SWAT */ #include "ds.h" #include "network/http.h" DEFAULT_MODULE_HEADER(http); int lib_open(klibrary_t *lib) { tcpfs_init(); httpfs_init(); return nmmgr_handler_add(&ds_http_hnd.nmmgr); } int lib_close(klibrary_t *lib) { httpfs_shutdown(); tcpfs_shutdown(); return nmmgr_handler_remove(&ds_http_hnd.nmmgr); } <file_sep>/modules/luaMXML/module.c /* DreamShell ##version## module.c - luaMXML module Copyright (C)2007-2013 SWAT */ #include <kos.h> #include <kos/exports.h> #include "ds.h" DEFAULT_MODULE_HEADER(luaMXML); int tolua_MXML_open(lua_State* tolua_S); int lib_open(klibrary_t * lib) { tolua_MXML_open(GetLuaState()); RegisterLuaLib(lib_get_name(), (LuaRegLibOpen *)tolua_MXML_open); return nmmgr_handler_add(&ds_luaMXML_hnd.nmmgr); } int lib_close(klibrary_t * lib) { UnregisterLuaLib(lib_get_name()); return nmmgr_handler_remove(&ds_luaMXML_hnd.nmmgr); } <file_sep>/modules/minilzo/Makefile # # minilzo module for DreamShell # Copyright (C) 2009-2022 SWAT # http://www.dc-swat.ru # TARGET_NAME = minilzo OBJS = module.o $(TARGET_NAME).o DBG_LIBS = -lds EXPORTS_FILE = exports.txt VER_MAJOR = 2 VER_MINOR = 0 VER_MICRO = 9 VER_BUILD = 0 KOS_CFLAGS += -I../../include/minilzo all: rm-elf install include ../../sdk/Makefile.loadable rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/modules/telnetd/telnetd.c /**************************** * DreamShell ##version## * * telnetd.c * * DreamShell telnet server * * Created by SWAT * ****************************/ #include <kos.h> #include <sys/socket.h> #include <sys/select.h> #include <stdio.h> #include <sys/queue.h> #include "ds.h" struct tel_state; typedef TAILQ_HEAD(tel_state_list, tel_state) tel_state_list_t; typedef struct tel_state { TAILQ_ENTRY(tel_state) list; int socket; struct sockaddr_in client; socklen_t client_size; kthread_t * thd; int ptyfd; } tel_state_t; static tel_state_list_t states; #define st_foreach(var) TAILQ_FOREACH(var, &states, list) static mutex_t list_mutex = MUTEX_INITIALIZER; static int st_init() { TAILQ_INIT(&states); return 0; } static tel_state_t * st_create() { tel_state_t * ns; ns = calloc(1, sizeof(tel_state_t)); mutex_lock(&list_mutex); TAILQ_INSERT_TAIL(&states, ns, list); mutex_unlock(&list_mutex); return ns; } static void st_destroy(tel_state_t *st) { mutex_lock(&list_mutex); TAILQ_REMOVE(&states, st, list); mutex_unlock(&list_mutex); free(st); } static int st_add_fds(fd_set * fds, int maxfd) { tel_state_t * st; mutex_lock(&list_mutex); st_foreach(st) { FD_SET(st->socket, fds); if (maxfd < (st->socket+1)) maxfd = st->socket + 1; } mutex_unlock(&list_mutex); return maxfd; } /**********************************************************************/ // This thread will grab input from the PTY and stuff it into the socket static void *client_thread(void *param) { int rc, o; char buf[256]; tel_state_t * ts = (tel_state_t *)param; ds_printf("telnetd: client thread started, sock %d\n", ts->socket); // Block until we have something to write out for ( ; ; ) { rc = fs_read(ts->ptyfd, buf, 256); if (rc <= 0) break; for (o=0; rc; ) { int i = write(ts->socket, buf, rc); rc -= i; o += i; } } ds_printf("telnetd: client thread exited, sock %d\n", ts->socket); return NULL; } // Grab any input from the socket and stuff it into the PTY static int handle_read(tel_state_t * ts) { char buffer[256]; int rc, o, d; for (d = 0; !d; ) { rc = read(ts->socket, buffer, 256); if (rc == 0) return -1; if (rc < 256) d = 1; for (o=0; rc; ) { int i = fs_write(ts->ptyfd, buffer + o, rc); rc -= i; o += i; } } return 0; } void *telnetd(void *p); typedef struct telnetd_params { int port; int state; } telnetd_params_t; static telnetd_params_t tdp; void telnetd_shutdown() { tdp.state = 0; /* if(wait) { while(tdp.state > -1) thd_sleep(100); }*/ } int telnetd_init(int port) { tdp.port = port ? port : 23; tdp.state = 1; thd_create(1, telnetd, NULL); return 0; } void *telnetd(void *p) { int listenfd; struct sockaddr_in saddr; fd_set readset; fd_set writeset; int i, maxfdp1; tel_state_t *ts; listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) { ds_printf("telnetd: socket create failed\n"); return NULL; } memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_ANY); saddr.sin_port = htons(23); if (bind(listenfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) { ds_printf("telnetd: bind failed\n"); close(listenfd); return NULL; } if (listen(listenfd, 10) < 0) { ds_printf("telnetd: listen failed\n"); close(listenfd); return NULL; } st_init(); ds_printf("telnetd: listening for connections on socket %d\n", listenfd); while(tdp.state > 0) { maxfdp1 = listenfd + 1; FD_ZERO(&readset); FD_ZERO(&writeset); FD_SET(listenfd, &readset); maxfdp1 = st_add_fds(&readset, maxfdp1); i = select(maxfdp1, &readset, &writeset, 0, 0); if (i == 0) continue; // Check for new incoming connections if (FD_ISSET(listenfd, &readset)) { ts = st_create(); ts->client_size = sizeof(ts->client); ts->socket = accept(listenfd, (struct sockaddr *)&ts->client, &ts->client_size); ds_printf("telnetd: connect from %08lx, port %d, socket %d\n", ts->client.sin_addr.s_addr, ts->client.sin_port, ts->socket); if (ts->socket < 0) { st_destroy(ts); } else { file_t master, slave; if (fs_pty_create(NULL, 0, &master, &slave) < 0) { ds_printf("telnetd: can't create pty for shell\n"); } else { ts->ptyfd = master; //assert( ts->ptyfd >= 0 ); fs_dup2(slave, 0); fs_dup2(slave, 1); fs_dup2(slave, 2); ts->thd = thd_create(1, client_thread, ts); } } } // Process data from connected clients st_foreach(ts) { if (FD_ISSET(ts->socket, &readset)) { if (handle_read(ts) < 0) { ds_printf("telnetd: disconnected socket %d\n", ts->socket); close(ts->socket); st_destroy(ts); break; } } } } close(listenfd); return NULL; } <file_sep>/modules/opkg/module.c /* DreamShell ##version## module.c - opkg module Copyright (C)2013-2014 SWAT */ #include "ds.h" #include "opk.h" DEFAULT_MODULE_EXPORTS_CMD(opkg, "OPKG Package Manager"); static int display_info(char *package_path) { struct OPK *opk; const char *key, *val; const char *metadata_name; size_t skey, sval; opk = opk_open(package_path); //EXPT_GUARD_ASSIGN(opk, opk_open(package_path), opk = NULL); if (!opk) { ds_printf("Failed to open %s\n", package_path); return CMD_ERROR; } ds_printf("=== %s\n", package_path); while (opk_open_metadata(opk, &metadata_name) > 0) { ds_printf("\nMetadata file: %s\n\n", metadata_name); while(opk_read_pair(opk, &key, &skey, &val, &sval) && key) ds_printf(" %.*s: %.*s\n", (int) skey, key, (int) sval, val); } opk_close(opk); ds_printf("\n"); return CMD_OK; } static int extract_file_to(char *package_path, char *extract_file, char *dest) { struct OPK *opk; file_t fd; void *data; size_t size; opk = opk_open(package_path); if(opk == NULL) { ds_printf("DS_ERROR: Failed to open %s\n", package_path); return CMD_ERROR; } ds_printf("DS_PROCESS: Extracting %s ...\n", extract_file); if(opk_extract_file(opk, extract_file, &data, &size) < 0) { opk_close(opk); return CMD_ERROR; } fd = fs_open(dest, O_WRONLY | O_CREAT); if(fd < 0) { ds_printf("DS_ERROR: Can't open %s for write extracted file\n", dest); free(data); opk_close(opk); return CMD_ERROR; } fs_write(fd, data, size); fs_close(fd); free(data); opk_close(opk); return CMD_OK; } static int install_package(char *package_path) { struct OPK *opk; file_t fd; void *data; size_t size; const char *key, *val; const char *metadata_name; char dest[NAME_MAX], lua_file[128]; char *file_list, *file, *filepath, *tmpval; size_t skey, sval; opk = opk_open(package_path); if(opk == NULL) { ds_printf("DS_ERROR: Failed to open %s\n", package_path); return CMD_ERROR; } while (opk_open_metadata(opk, &metadata_name) > 0) { file_list = NULL; memset(lua_file, 0, sizeof(lua_file)); while(opk_read_pair(opk, &key, &skey, &val, &sval) && key) { if(!strncasecmp(key, "DS-Files", 8) || !strncasecmp(key, "DS-Data", 7)) { file_list = strndup((char *)val, sval); } else if(!strncasecmp(key, "Name", 4)) { ds_printf("DS_PROCESS: Installing %.*s package...\n", (int)sval, val); } else if(!strncasecmp(key, "DS-InstallScript", 16) && sval) { strncpy(lua_file, val, sval); } } if(file_list != NULL) { tmpval = file_list; while((filepath = strsep(&tmpval, " ;\t\n")) != NULL) { file = strrchr(filepath, '/'); if(!file) file = filepath; else file++; ds_printf("DS_PROCESS: Extracting '%s' to '%s' ...\n", file, filepath); sprintf(dest, "%s/%.*s", getenv("PATH"), strlen(filepath) - strlen(file) - 1, filepath); if(!DirExists(dest) && mkpath(dest)) { ds_printf("DS_ERROR: Can't create directory '%s'\n", dest); free(file_list); opk_close(opk); return CMD_ERROR; } if(opk_extract_file(opk, file, &data, &size) < 0) { if(opk_extract_file(opk, filepath, &data, &size) < 0) { opk_close(opk); return CMD_ERROR; } } sprintf(dest, "%s/%s", getenv("PATH"), filepath); fd = fs_open(dest, O_CREAT | O_TRUNC | O_WRONLY); if(fd < 0) { ds_printf("DS_ERROR: Can't open %s for write: %d\n", dest, errno); free(file_list); free(data); opk_close(opk); return CMD_ERROR; } fs_write(fd, data, size); fs_close(fd); free(data); } free(file_list); } else { ds_printf("DS_WARNING: Can't find 'DS-Files' or 'DS-Data' in metadata file\n"); } } if(lua_file[0] != 0 && !opk_extract_file(opk, lua_file, &data, &size)) { tmpval = (char*)data; tmpval[size-1] = '\0'; ds_printf("DS_PROCESS: Executing '%s'...\n", lua_file); LuaDo(LUA_DO_STRING, tmpval, GetLuaState()); free(data); } opk_close(opk); ds_printf("DS_OK: Installation completed!\n"); return CMD_OK; } static int uninstall_package(char *package_path) { struct OPK *opk; void *data; size_t size; const char *key, *val; const char *metadata_name; char dest[NAME_MAX], lua_file[128]; char *file_list, *filepath, *tmpval; size_t skey, sval; opk = opk_open(package_path); if(opk == NULL) { ds_printf("DS_ERROR: Failed to open %s\n", package_path); return CMD_ERROR; } while (opk_open_metadata(opk, &metadata_name) > 0) { file_list = NULL; memset(lua_file, 0, sizeof(lua_file)); while(opk_read_pair(opk, &key, &skey, &val, &sval) && key) { if(!strncasecmp(key, "DS-Files", 8) || !strncasecmp(key, "DS-Data", 7)) { file_list = strndup((char *)val, sval); } else if(!strncasecmp(key, "Name", 4)) { ds_printf("DS_PROCESS: Uninstalling %.*s package...\n", (int)sval, val); } else if(!strncasecmp(key, "DS-UninstallScript", 18) && sval) { strncpy(lua_file, val, sval); } } if(file_list != NULL) { tmpval = file_list; while((filepath = strsep(&tmpval, " ;\t\n")) != NULL) { sprintf(dest, "%s/%s", getenv("PATH"), filepath); ds_printf("DS_PROCESS: Deleting '%s' ...\n", dest); if(fs_unlink(dest) != 0) { ds_printf("DS_ERROR: Error when deleting a file: %d\n", errno); free(file_list); return CMD_ERROR; } } free(file_list); } else { ds_printf("DS_WARNING: Can't find 'DS-Files' or 'DS-Data' in metadata file\n"); } } if(lua_file[0] != 0 && !opk_extract_file(opk, lua_file, &data, &size)) { tmpval = (char*)data; tmpval[size-1] = '\0'; ds_printf("DS_PROCESS: Executing '%s'...\n", lua_file); LuaDo(LUA_DO_STRING, tmpval, GetLuaState()); free(data); } opk_close(opk); ds_printf("DS_OK: Uninstallation completed!\n"); return CMD_OK; } int builtin_opkg_cmd(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s options args\n" "Options: \n" " -i, --install -Installing package\n" " -u, --uninstall -Uninstalling package\n" " -m, --metadata -Display package metadata\n" " -v, --version -Display opkg module version\n\n" "Arguments: \n" " -f, --file -File .opk\n" " -e, --extract -Extract one file\n" " -d, --dest -Destination file/path\n\n" "Example: %s -m -f package.opk\n\n", argv[0], argv[0]); return CMD_NO_ARG; } int install = 0, uninstall = 0, metadata = 0, version = 0; char *file = NULL, *dest = NULL, *extractf = NULL; struct cfg_option options[] = { {"install", 'i', NULL, CFG_BOOL, (void *) &install, 0}, {"uninstall", 'u', NULL, CFG_BOOL, (void *) &uninstall, 0}, {"metadata", 'm', NULL, CFG_BOOL, (void *) &metadata, 0}, {"version", 'v', NULL, CFG_BOOL, (void *) &version, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, {"dest", 'd', NULL, CFG_STR, (void *) &dest, 0}, {"extract", 'e', NULL, CFG_STR, (void *) &extractf, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(version) { ds_printf("OPKG module version: %d.%d.%d build %d\n", VER_MAJOR, VER_MINOR, VER_MICRO, VER_BUILD); return CMD_OK; } if(file == NULL) { ds_printf("DS_ERROR: You did not specify a required argument (file .opk).\n"); return CMD_ERROR; } if(metadata) { return display_info(file); } if(extractf) { if(dest == NULL) { ds_printf("DS_ERROR: You did not specify a required argument (destination file).\n"); return CMD_ERROR; } return extract_file_to(file, extractf, dest); } if(install) { return install_package(file); } if(uninstall) { return uninstall_package(file); } return CMD_OK; } <file_sep>/firmware/isoldr/loader/fs/cd/cdfs.c /** * DreamShell ISO Loader * ISO9660 file system * (c)2011-2022 SWAT <http://www.dc-swat.ru> */ #include <main.h> #include <asic.h> #include <mmu.h> #include <arch/cache.h> /* Sector buffer */ static void *cd_sector_buffer; static int dma_mode = 0; void fs_enable_dma(int state) { dma_mode = state; } int fs_dma_enabled() { return dma_mode; } static int read_sectors(char *buf, int sec, int num, int async) { return cdrom_read_sectors_ex(buf, sec, num, async, dma_mode, 0); } static char *strchr0(const char *s, int c) { while(*s!=c) if(!*s++) return NULL; return (char *)s; } /* * ISO9660 support functions */ static int ntohlp(unsigned char *ptr) { /* Convert the long word pointed to by ptr from big endian */ return (ptr[0]<<24)|(ptr[1]<<16)|(ptr[2]<<8)|ptr[3]; } static int tolower(int c) { if(('A' <= c) && (c <= 'Z')) { return c + ('a' - 'A'); } return c; } static int fncompare(const char *fn1, int fn1len, const char *fn2, int fn2len) { /* Compare two filenames, disregarding verion number on fn2 if neccessary */ while(fn2len--) if(!fn1len--) return *fn2 == ';'; else if(tolower(*fn1++) != tolower(*fn2++)) return 0; return fn1len == 0; } /* * Low file I/O */ static int find_root(unsigned int *psec, unsigned int *plen) { /* Find location and length of root directory. Plain ISO9660 only. */ CDROM_TOC *toc; int r; unsigned int sec; if((r=cdrom_reinit(2048, 0))!=0) { LOGFF("can't reinit cdrom (%d)\n", r); return r; } if(!(toc = cdrom_get_toc(0, 0))) { LOGFF("can't get toc (%d)\n", r); return r; } if((sec = cdrom_locate_data_track(toc)) == (u32)-1) { LOGFF("can't locate data track (%d)\n", FS_ERR_DIRERR); return FS_ERR_DIRERR; } if((r=read_sectors((char *)cd_sector_buffer, sec+16, 1, 0))!=0) { LOGFF("can't read root (%d)\n", r); return r; } if(memcmp((char *)cd_sector_buffer, "\001CD001", 6)) { LOGFF("bad root (%d)\n", FS_ERR_DIRERR); return FS_ERR_DIRERR; } /* Need to add 150 to LBA to get physical sector number */ *psec = ntohlp(((unsigned char *)cd_sector_buffer)+156+6); if (cdrom_get_dev_type(0) == 2) *psec += 150; *plen = ntohlp(((unsigned char *)cd_sector_buffer)+156+14); return 0; } static int low_find(unsigned int sec, unsigned int dirlen, int isdir, unsigned int *psec, unsigned int *plen, const char *fname, int fnlen) { /* Find a named entry in a directory */ /* sec and dirlen points out the extent of the directory */ /* psec and plen points to variables that will receive the extent of the file if found */ isdir = (isdir? 2 : 0); while(dirlen>0) { unsigned int r, i; unsigned char *rec = (unsigned char *)cd_sector_buffer; if((r=read_sectors((char *)cd_sector_buffer, sec, 1, 0))!=0) return r; for(i=0; i<2048 && i<dirlen && rec[0] != 0; i += rec[0], rec += rec[0]) { //WriteLog("low_find: %s = %s\n", fname, rec+33); if((rec[25]&2) == isdir && fncompare(fname, fnlen, (char*)rec+33, rec[32])) { /* Entry found. Copy start sector and length. Add 150 to LBA. */ *psec = ntohlp(rec+6); if (cdrom_get_dev_type(0) == 2) *psec += 150; *plen = ntohlp(rec+14); return 0; } } /* Not found, proceed to next sector */ sec++; dirlen -= (dirlen>2048? 2048 : dirlen); } /* End of directory. Entry not found. */ return FS_ERR_NOFILE; } /* File I/O */ /* A file handle. */ static struct { unsigned int sec0; /* First sector */ unsigned int loc; /* Current read position (in bytes) */ unsigned int len; /* Length of file (in bytes) */ unsigned int rcnt; void *rbuf; int async; fs_callback_f *poll_cb; int dma_mode; } fh[MAX_OPEN_FILES]; static unsigned int root_sector = 0; static unsigned int root_len = 0; int open(const char *path, int oflag) { int fd, r; unsigned int sec, len; char *p; /* Find a free file handle */ for(fd=0; fd<MAX_OPEN_FILES; fd++) if(fh[fd].sec0 == 0) break; if(fd>=MAX_OPEN_FILES) return FS_ERR_NUMFILES; /* Find the root directory */ if (!root_sector) { if((r=find_root(&sec, &len))) { LOGFF("can't find root (%d)\n", r); return r; } root_sector = sec; root_len = len; } else { sec = root_sector; len = root_len; } int old_dma_mode = dma_mode; dma_mode = 0; /* If the file we want is in a subdirectory, first locate this subdirectory */ while((p = strchr0(path, '/'))) { if(p != path) if((r = low_find(sec, len, 1, &sec, &len, path, p-path))) { LOGFF("can't find file %s in a subdirectory (%d)\n", path, r); return r; } path = p+1; } /* Locate the file in the resulting directory */ if(*path) { if((r = low_find(sec, len, oflag&O_DIR, &sec, &len, path, strchr0(path, '\0')-path))) { dma_mode = old_dma_mode; LOGFF("can't find file %s in resulting directory (%d)\n", path, r); return r; } } else { /* If the path ends with a slash, check that it's really the dir that is wanted */ if(!(oflag & O_DIR)) { dma_mode = old_dma_mode; LOGFF("can't find file %s (%d)\n", path, FS_ERR_NOFILE); return FS_ERR_NOFILE; } } /* Fill in the file handle and return the fd */ LOGF("Opened file: %s fd=%d sec=%d len=%d\n", path, fd, sec, len); fh[fd].sec0 = sec; fh[fd].loc = 0; fh[fd].len = len; fh[fd].async = 0; fh[fd].poll_cb = NULL; fh[fd].dma_mode = -1; dma_mode = old_dma_mode; if(oflag & O_PIO) { fh[fd].dma_mode = FS_DMA_DISABLED; } return fd; } int close(int fd) { /* Check that the fd is valid */ if(fd < 0 || fd >= MAX_OPEN_FILES) return FS_ERR_PARAM; LOGF("Closed file: fd=%d sec=%d len=%d\n", fd, fh[fd].sec0, fh[fd].len); /* Zeroing the sector number marks the handle as unused */ fh[fd].sec0 = 0; if(fh[fd].async > 0) { abort_async(fd); } return 0; } int pread(int fd, void *buf, unsigned int nbyte, unsigned int offset) { int r, t; /* Check that the fd is valid */ if(fd<0 || fd>=MAX_OPEN_FILES || fh[fd].sec0==0) return FS_ERR_PARAM; /* If the read position is beyond the end of the file, return an empty read */ if(offset>=fh[fd].len) return 0; /* If the full read would span beyond the EOF, shorten the read */ if(offset+nbyte > fh[fd].len) nbyte = fh[fd].len - offset; /* Read whole sectors directly into buf if possible */ if(nbyte>=2048 && !(offset & 2047)) if((r = read_sectors(buf, fh[fd].sec0 + (offset>>11), nbyte>>11, 0))) return r; else { t = nbyte & ~2047; buf = ((char *)buf) + t; offset += t; nbyte &= 2047; } else t = 0; /* If all data has now been read, return */ if(!nbyte) return t; /* Need to read parts of sectors */ if((offset & 2047)+nbyte > 2048) { /* If more than one sector is involved, split the read up and recurse */ DBGFF("0x%08lx %ld %ld (part)\n", (uint32)buf, 2048-(offset & 2047)); if((r = pread(fd, buf, 2048-(offset & 2047), offset))<0) return r; else { t += r; buf = ((char *)buf) + r; offset += r; nbyte -= r; } DBGFF("0x%08lx %ld (other)\n", (uint32)buf, nbyte); if((r = pread(fd, buf, nbyte, offset))<0) return r; else t += r; } else { if (!((uint32)buf & PHYS_ADDR(RAM_START_ADDR)) && mmu_enabled()) { if((r = cdrom_read_sectors_part(buf, fh[fd].sec0+(offset>>11), offset, nbyte, 0))) { return r; } } else { /* Just one sector. Read it and copy the relevant part. */ if((r = read_sectors((char *)cd_sector_buffer, fh[fd].sec0+(offset>>11), 1, 0))) { return r; } memcpy(buf, ((char *)cd_sector_buffer)+(offset&2047), nbyte); } t += nbyte; } return t; } int read(int fd, void *buf, unsigned int nbyte) { /* Check that the fd is valid */ if(fd < 0 || fd >= MAX_OPEN_FILES || fh[fd].sec0 == 0) { return FS_ERR_PARAM; } int old_dma_mode = dma_mode; if (fh[fd].dma_mode > -1) { dma_mode = fh[fd].dma_mode; } /* Use pread to read at the current position */ int r = pread(fd, buf, nbyte, fh[fd].loc); dma_mode = old_dma_mode; /* Update current position */ if(r > 0) fh[fd].loc += r; return r; } #if _FS_READONLY == 0 int write(int fd, void *buf, unsigned int nbyte) { if(fd < 0 || fd >= MAX_OPEN_FILES || fh[fd].sec0 == 0) { return FS_ERR_PARAM; } (void)buf; (void)nbyte; return FS_ERR_SYSERR; } #endif int poll(int fd) { if(fd < 0) { return FS_ERR_NOFILE; } if(!fh[fd].poll_cb || fh[fd].async < 1) { LOGFF("error, not async fd\n"); return 0; } int transfered = g1_dma_transfered(); if (g1_dma_in_progress()) { return transfered; } else { fh[fd].loc += transfered; if (fh[fd].rcnt) { if (cdrom_read_sectors_part(fh[fd].rbuf, fh[fd].sec0 + (fh[fd].loc >> 11), fh[fd].loc % 2048, fh[fd].rcnt, 0) < 0) { fh[fd].async = 0; fs_callback_f *cb = fh[fd].poll_cb; fh[fd].poll_cb = NULL; cb(-1); return FS_ERR_SYSERR; } return transfered + fh[fd].rcnt - 32; } fs_callback_f *cb = fh[fd].poll_cb; fh[fd].poll_cb = NULL; cb(transfered); return 0; } } void poll_all(int err) { for(int i = 0; i < MAX_OPEN_FILES; i++) { if(fh[i].sec0 > 0 && fh[i].async > 0) { if (err) { fs_callback_f *cb = fh[i].poll_cb; fh[i].poll_cb = NULL; cb(err); } else { poll(i); } } } } int abort_async(int fd) { if(fd < 0 || fd >= MAX_OPEN_FILES) return FS_ERR_PARAM; if(fh[fd].async > 0) { fh[fd].async = 0; fh[fd].poll_cb = NULL; g1_dma_abort(); } return 0; } int read_async(int fd, void *buf, unsigned int nbyte, fs_callback_f *cb) { unsigned int sector, count; /* Check that the fd is valid */ if(fd < 0 || fd >= MAX_OPEN_FILES || fh[fd].sec0 == 0) { return FS_ERR_PARAM; } if(fh[fd].loc + nbyte > fh[fd].len) { nbyte = fh[fd].len - fh[fd].loc; } sector = fh[fd].sec0 + (fh[fd].loc >> 11); /* If DMA is not possible, just use sync pio read */ if((uint32)buf & 0x1F) { cb(read(fd, buf, nbyte)); return 0; } else if((fh[fd].loc & 2047) || (nbyte & 2047)) { if((fh[fd].loc & 2047) + nbyte > 2048) { count = (2048-(fh[fd].loc & 2047)) >> 11; fh[fd].rcnt = nbyte - (count << 11); fh[fd].rbuf = buf + (count << 11); } else { if (cdrom_read_sectors_part(buf, fh[fd].sec0 + (fh[fd].loc >> 11), fh[fd].loc % 2048, nbyte, 0) < 0) { fh[fd].async = 0; fh[fd].poll_cb = NULL; return FS_ERR_SYSERR; } fh[fd].async = 1; fh[fd].poll_cb = cb; DBGFF("offset=%d size=%d count=%d\n", fh[fd].loc, nbyte, nbyte >> 11); return 0; } } else { count = nbyte >> 11; } if (read_sectors(buf, sector, count, 1) < 0) { fh[fd].async = 0; fh[fd].poll_cb = NULL; return FS_ERR_SYSERR; } fh[fd].async = 1; fh[fd].poll_cb = cb; DBGFF("offset=%d size=%d count=%d\n", fh[fd].loc, nbyte, nbyte >> 11); return 0; } int pre_read(int fd, unsigned int size) { if (cdrom_pre_read_sectors(fh[fd].sec0 + (fh[fd].loc >> 11), size >> 11, 0) < 0) { return FS_ERR_SYSERR; } fh[fd].async = 1; return 0; } long int lseek(int fd, long int offset, int whence) { /* Check that the fd is valid */ if(fd < 0 || fd >= MAX_OPEN_FILES || fh[fd].sec0 == 0) { return FS_ERR_PARAM; } /* Update current position according to arguments */ switch(whence) { case SEEK_SET: return fh[fd].loc = offset; case SEEK_CUR: return fh[fd].loc += offset; case SEEK_END: return fh[fd].loc = fh[fd].len + offset; default: return FS_ERR_PARAM; } } long int tell(int fd) { /* Check that the fd is valid */ if(fd < 0 || fd >= MAX_OPEN_FILES || fh[fd].sec0 == 0) return FS_ERR_PARAM; return fh[fd].loc; } unsigned long total(int fd) { return fh[fd].len; } int ioctl(int fd, int cmd, void *data) { /* Check that the fd is valid */ if(fd < 0 || fd >= MAX_OPEN_FILES || fh[fd].sec0 == 0) { return FS_ERR_PARAM; } switch(cmd) { case FS_IOCTL_GET_LBA: { memcpy(data, &fh[fd].sec0, sizeof(fh[fd].sec0)); return 0; } default: return FS_ERR_PARAM; } } /* Init function */ int fs_init() { memset(&fh, 0, sizeof(fh)); cd_sector_buffer = malloc(2048 + 32); if (!cd_sector_buffer) { LOGFF("Memory failed"); return -1; } cd_sector_buffer = (void *)ALIGN32_ADDR((uint32)cd_sector_buffer); memset(cd_sector_buffer, 0, 2048); LOGFF("Sector buffer at 0x%08lx\n", (uint32)cd_sector_buffer); return g1_bus_init(); } <file_sep>/firmware/isoldr/loader/kos/src/scif.c /* KallistiOS ##version## hardware/scif.c Copyright (C)2000,2001,2004 <NAME> */ #include <dc/scif.h> /* This module handles very basic serial I/O using the SH4's SCIF port. FIFO mode is used by default; you can turn this off to avoid forcing a wait when there is no serial device attached. Unlike in KOS 1.x, this is not designed to be used as the normal I/O, but simply as an early debugging device in case something goes wrong in the kernel or for debugging it. */ /* SCIF registers */ #define SCIFREG08(x) *((volatile uint8 *)(x)) #define SCIFREG16(x) *((volatile uint16 *)(x)) #define SCSMR2 SCIFREG16(0xffeb0000) #define SCBRR2 SCIFREG08(0xffe80004) #define SCSCR2 SCIFREG16(0xffe80008) #define SCFTDR2 SCIFREG08(0xffe8000C) #define SCFSR2 SCIFREG16(0xffe80010) #define SCFRDR2 SCIFREG08(0xffe80014) #define SCFCR2 SCIFREG16(0xffe80018) #define SCFDR2 SCIFREG16(0xffe8001C) #define SCSPTR2 SCIFREG16(0xffe80020) #define SCLSR2 SCIFREG16(0xffe80024) //#define PTR2_RTSIO (1 << 7) //#define PTR2_RTSDT (1 << 6) /* Default serial parameters */ //static int serial_baud = 57600; //static int serial_fifo = 1; /* Set serial parameters; this is not platform independent like I want it to be, but it should be generic enough to be useful. */ //void scif_set_parameters(int baud, int fifo) { // serial_baud = baud; // serial_fifo = fifo; //} /* Initialize the SCIF port; baud_rate must be at least 9600 and no more than 57600. 115200 does NOT work for most PCs. */ // recv trigger to 1 byte int scif_init() { int i; /* int fifo = 1; */ /* Disable interrupts, transmit/receive, and use internal clock */ SCSCR2 = 0; /* Enter reset mode */ SCFCR2 = 0x06; /* 8N1, use P0 clock */ SCSMR2 = 0; /* If baudrate unset, set baudrate, N = P0/(32*B)-1 */ // if (SCBRR2 == 0xff) SCBRR2 = (uint8)(50000000 / (32 * 115200)) - 1; /* Wait a bit for it to stabilize */ for (i=0; i<10000; i++) __asm__("nop"); /* Unreset, enable hardware flow control, triggers on 8 bytes */ SCFCR2 = 0x48; /* Disable manual pin control */ SCSPTR2 = 0; /* Disable SD */ // SCSPTR2 = PTR2_RTSIO | PTR2_RTSDT; /* Clear status */ (void)SCFSR2; SCFSR2 = 0x60; (void)SCLSR2; SCLSR2 = 0; /* Enable transmit/receive */ SCSCR2 = 0x30; /* Wait a bit for it to stabilize */ for (i=0; i<10000; i++) __asm__("nop"); return 0; } /* Read one char from the serial port (-1 if nothing to read) */ int scif_read() { int c; if (!(SCFDR2 & 0x1f)) return -1; // Get the input char c = SCFRDR2; // Ack SCFSR2 &= ~0x92; return c; } /* Write one char to the serial port (call serial_flush()!) */ int scif_write(int c) { int timeout = 100000; /* Wait until the transmit buffer has space. Too long of a failure is indicative of no serial cable. */ while (!(SCFSR2 & 0x20) && timeout > 0) timeout--; if (timeout <= 0) return -1; /* Send the char */ SCFTDR2 = c; /* Clear status */ SCFSR2 &= 0xff9f; return 1; } /* Flush all FIFO'd bytes out of the serial port buffer */ int scif_flush() { int timeout = 100000; SCFSR2 &= 0xbf; while (!(SCFSR2 & 0x40) && timeout > 0) timeout--; if (timeout <= 0) return -1; SCFSR2 &= 0xbf; return 0; } /* Send an entire buffer */ int scif_write_buffer(const uint8 *data, int len, int xlat) { int rv, i = 0, c; while (len-- > 0) { c = *data++; if (xlat) { if (c == '\n') { if (scif_write('\r') < 0) return -1; i++; } } rv = scif_write(c); if (rv < 0) return -1; i += rv; } if (scif_flush() < 0) return -1; return i; } /* Read an entire buffer (block) */ int scif_read_buffer(uint8 *data, int len) { int c, i = 0; while (len-- > 0) { while ( (c = scif_read()) == -1) ; *data++ = c; i++; } return i; } <file_sep>/firmware/aica/codec/systime.c /******************************************************************************/ /* */ /* TIME.C: Time Functions for 1000Hz Clock Tick */ /* */ /******************************************************************************/ /* ported to arm-elf-gcc / WinARM by <NAME>, KL, .de */ /* <<EMAIL>> */ /* */ /* Based on a file that has been a part of the uVision/ARM development */ /* tools, Copyright KEIL ELEKTRONIK GmbH 2002-2004 */ /******************************************************************************/ /* - mt: modified interrupt ISR handling, updated labels */ #include "AT91SAM7S64.h" #include "Board.h" #include "interrupt_utils.h" #include "systime.h" #include "keys.h" #include "diskio.h" #include "ir.h" #ifdef ERAM /* Fast IRQ functions Run in RAM - see board.h */ #define ATTR RAMFUNC #else #define ATTR #endif volatile unsigned long systime_value; /* Current Time Tick */ /* Current Time Tick */ void NACKEDFUNC ATTR systime_isr(void) { /* System Interrupt Handler */ volatile AT91S_PITC * pPIT; ISR_ENTRY(); pPIT = AT91C_BASE_PITC; if (pPIT->PITC_PISR & AT91C_PITC_PITS) { /* Check PIT Interrupt */ systime_value++; /* Increment Time Tick */ //if ((systime_value % 500) == 0) { /* 500ms Elapsed ? */ // *AT91C_PIOA_ODSR ^= LED4; /* Toggle LED4 */ //} if (systime_value % 128 == 0) { process_keys(); } if (systime_value % 256 == 0) { disk_timerproc(); } if (systime_value % 1 == 0) { ir_receive(); } *AT91C_AIC_EOICR = pPIT->PITC_PIVR; /* Ack & End of Interrupt */ } else { *AT91C_AIC_EOICR = 0; /* End of Interrupt */ } ISR_EXIT(); } void systime_init(void) { /* Setup PIT with Interrupt */ volatile AT91S_AIC * pAIC = AT91C_BASE_AIC; //*AT91C_PIOA_OWER = LED4; // LED4 ODSR Write Enable *AT91C_PITC_PIMR = AT91C_PITC_PITIEN | /* PIT Interrupt Enable */ AT91C_PITC_PITEN | /* PIT Enable */ PIV; /* Periodic Interval Value */ /* Setup System Interrupt Mode and Vector with Priority 7 and Enable it */ pAIC->AIC_SMR[AT91C_ID_SYS] = AT91C_AIC_SRCTYPE_INT_POSITIVE_EDGE | 7; pAIC->AIC_SVR[AT91C_ID_SYS] = (unsigned long) systime_isr; pAIC->AIC_IECR = (1 << AT91C_ID_SYS); } unsigned long systime_get(void) { unsigned state; unsigned long ret; state = disableIRQ(); ret = systime_value; restoreIRQ(state); return ret; } unsigned long systime_get_ms(void) { return systime_get() / 10; }<file_sep>/modules/SDL_net/module.c /* DreamShell ##version## module.c - SDL_net module Copyright (C)2012-2014 SWAT */ #include "ds.h" DEFAULT_MODULE_EXPORTS(SDL_net); <file_sep>/include/memory.h // dummy file for platforms that don't use memory.h <file_sep>/modules/ftpd/lftpd/lftpd.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdarg.h> #include <stdbool.h> #include <unistd.h> #include <ctype.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <dirent.h> #include <errno.h> #include <sys/stat.h> #include <kos/net.h> #include "lftpd.h" #include "private/lftpd_status.h" #include "private/lftpd_inet.h" #include "private/lftpd_log.h" #include "private/lftpd_string.h" #include "private/lftpd_io.h" // https://tools.ietf.org/html/rfc959 // https://tools.ietf.org/html/rfc2389#section-2.2 // https://tools.ietf.org/html/rfc3659 // https://tools.ietf.org/html/rfc5797 // https://tools.ietf.org/html/rfc2428#section-3 EPSV // https://en.wikipedia.org/wiki/List_of_FTP_commands #define FILE_BUFFER_SIZE 8 * 1024 typedef struct { char *command; int (*handler) (lftpd_client_t* client, const char* arg); } command_t; static int cmd_cwd(); static int cmd_dele(); static int cmd_epsv(); static int cmd_feat(); static int cmd_list(); static int cmd_nlst(); static int cmd_noop(); static int cmd_pass(); static int cmd_pasv(); static int cmd_pwd(); static int cmd_quit(); static int cmd_retr(); static int cmd_size(); static int cmd_stor(); static int cmd_syst(); static int cmd_type(); static int cmd_user(); static command_t commands[] = { { "CWD", cmd_cwd }, { "DELE", cmd_dele }, { "EPSV", cmd_epsv }, { "FEAT", cmd_feat }, { "LIST", cmd_list }, { "NLST", cmd_nlst }, { "NOOP", cmd_noop }, { "PASS", cmd_pass }, { "PASV", cmd_pasv }, { "PWD", cmd_pwd }, { "QUIT", cmd_quit }, { "RETR", cmd_retr }, { "SIZE", cmd_size }, { "STOR", cmd_stor }, { "SYST", cmd_syst }, { "TYPE", cmd_type }, { "USER", cmd_user }, { NULL, NULL }, }; static int send_response(int socket, int code, bool include_code, bool multiline_start, const char* format, ...) { va_list args; va_start(args, format); char* message = NULL; int err = vasprintf(&message, format, args); va_end(args); if (err < 0) { return -1; } char* response = NULL; if (include_code) { if (multiline_start) { err = asprintf(&response, "%d-%s%s", code, message, CRLF); } else { err = asprintf(&response, "%d %s%s", code, message, CRLF); } } else { err = asprintf(&response, "%s%s", message, CRLF); } free(message); if (err < 0) { return -1; } err = lftpd_inet_write_string(socket, response); free(response); return err; } #define send_simple_response(socket, code, format, ...) send_response(socket, code, true, false, format, ##__VA_ARGS__) #define send_multiline_response_begin(socket, code, format, ...) send_response(socket, code, true, true, format, ##__VA_ARGS__) #define send_multiline_response_line(socket, format, ...) send_response(socket, 0, false, false, format, ##__VA_ARGS__) #define send_multiline_response_end(socket, code, format, ...) send_response(socket, code, true, false, format, ##__VA_ARGS__) static int send_list(int socket, const char* path) { // https://files.stairways.com/other/ftp-list-specs-info.txt // http://cr.yp.to/ftp/list/binls.html static const char* directory_format = "drw-rw-rw- 1 dream shell %lu Nov 27 1998 %s"; static const char* file_format = "-rw-rw-rw- 1 dream shell %lu Nov 27 1998 %s"; file_t fd = fs_open(path, O_RDONLY | O_DIR); if (fd < 0) { return -1; } dirent_t *entry; while ((entry = fs_readdir(fd))) { if (entry->attr == O_DIR) { send_multiline_response_line(socket, directory_format, 0, entry->name); } else { send_multiline_response_line(socket, file_format, entry->size, entry->name); } } fs_close(fd); return 0; } static int send_nlst(int socket, const char* path) { file_t fd = fs_open(path, O_RDONLY | O_DIR); if (fd < 0) { return -1; } dirent_t *entry; while ((entry = fs_readdir(fd))) { send_multiline_response_line(socket, entry->name); } fs_close(fd); return 0; } static int send_file(int socket, const char* path) { file_t fd = fs_open(path, O_RDONLY); if (fd < 0) { lftpd_log_error("failed to open file for read"); return -1; } uint8_t *buffer = (uint8_t *)malloc(FILE_BUFFER_SIZE); int read_len; while ((read_len = fs_read(fd, buffer, FILE_BUFFER_SIZE)) > 0) { uint8_t *p = buffer; while (read_len > 0) { int write_len = write(socket, p, read_len); if (write_len < 0) { lftpd_log_error("write error"); fs_close(fd); free(buffer); return -1; } p += write_len; read_len -= write_len; } } fs_close(fd); free(buffer); return 0; } static int receive_file(int socket, const char* path) { file_t fd = fs_open(path, O_WRONLY | O_TRUNC); if (fd < 0) { lftpd_log_error("failed to open file for read"); return -1; } uint8_t *buffer = (uint8_t *)malloc(FILE_BUFFER_SIZE); int read_len; while ((read_len = read(socket, buffer, FILE_BUFFER_SIZE)) > 0) { if (fs_write(fd, buffer, read_len) < 0) { fs_close(fd); free(buffer); return -1; } } fs_close(fd); free(buffer); return 0; } static int cmd_cwd(lftpd_client_t* client, const char* arg) { if (arg == NULL || strlen(arg) == 0) { send_simple_response(client->socket, 550, STATUS_550); } char* path = lftpd_io_canonicalize_path(client->directory, arg); file_t fd = fs_open(path, O_RDONLY | O_DIR); if (fd < 0) { send_simple_response(client->socket, 550, STATUS_550); free(path); return -1; } fs_close(fd); free(client->directory); client->directory = path; send_simple_response(client->socket, 250, STATUS_250); return 0; } static int cmd_dele(lftpd_client_t* client, const char* arg) { if (arg == NULL || strlen(arg) == 0) { send_simple_response(client->socket, 550, STATUS_550); } char* path = lftpd_io_canonicalize_path(client->directory, arg); if (fs_unlink(path) < 0) { send_simple_response(client->socket, 550, STATUS_550); free(path); return -1; } free(path); send_simple_response(client->socket, 250, STATUS_250); return 0; } static int cmd_epsv(lftpd_client_t* client, const char* arg) { // open a data port int listener_socket = lftpd_inet_listen(0); if (listener_socket < 0) { send_simple_response(client->socket, 425, STATUS_425); return -1; } // get the port from the new socket, which is random int port = lftpd_inet_get_socket_port(listener_socket); // format the response send_simple_response(client->socket, 229, STATUS_229, port); // wait for the connection to the data port lftpd_log_debug("waiting for data port connection on port %d...", port); int client_socket = accept(listener_socket, NULL, NULL); if (client_socket < 0) { lftpd_log_error("error accepting client socket"); close(listener_socket); return -1; } lftpd_log_debug("data port connection received..."); // close the listener close(listener_socket); client->data_socket = client_socket; return 0; } static int cmd_feat(lftpd_client_t* client, const char* arg) { send_multiline_response_begin(client->socket, 211, STATUS_211); send_multiline_response_line(client->socket, "EPSV"); send_multiline_response_line(client->socket, "PASV"); send_multiline_response_line(client->socket, "SIZE"); send_multiline_response_line(client->socket, "NLST"); send_multiline_response_end(client->socket, 211, STATUS_211); return 0; } static int cmd_list(lftpd_client_t* client, const char* arg) { if (client->data_socket == -1) { send_simple_response(client->socket, 425, STATUS_425); return -1; } send_simple_response(client->socket, 150, STATUS_150); int err = send_list(client->data_socket, client->directory); close(client->data_socket); client->data_socket = -1; if (err == 0) { send_simple_response(client->socket, 226, STATUS_226); } else { send_simple_response(client->socket, 550, STATUS_550); } return 0; } static int cmd_nlst(lftpd_client_t* client, const char* arg) { if (client->data_socket == -1) { send_simple_response(client->socket, 425, STATUS_425); return -1; } send_simple_response(client->socket, 150, STATUS_150); int err = send_nlst(client->data_socket, client->directory); close(client->data_socket); client->data_socket = -1; if (err == 0) { send_simple_response(client->socket, 226, STATUS_226); } else { send_simple_response(client->socket, 550, STATUS_550); } return 0; } static int cmd_noop(lftpd_client_t* client, const char* arg) { send_simple_response(client->socket, 200, STATUS_200); return 0; } static int cmd_pass(lftpd_client_t* client, const char* arg) { send_simple_response(client->socket, 230, STATUS_230); return 0; } static int cmd_pasv(lftpd_client_t* client, const char* arg) { // open a data port int listener_socket = lftpd_inet_listen(0); if (listener_socket < 0) { send_simple_response(client->socket, 425, STATUS_425); return -1; } // get the port from the new socket, which is random int port = lftpd_inet_get_socket_port(listener_socket); send_simple_response(client->socket, 227, STATUS_227, net_default_dev->ip_addr[0], net_default_dev->ip_addr[1], net_default_dev->ip_addr[2], net_default_dev->ip_addr[3], (port >> 8) & 0xff, (port & 0xff)); // wait for the connection to the data port lftpd_log_debug("waiting for data port connection on port %d...", port); int client_socket = accept(listener_socket, NULL, NULL); if (client_socket < 0) { lftpd_log_error("error accepting client socket"); close(listener_socket); return -1; } lftpd_log_debug("data port connection received..."); // close the listener close(listener_socket); client->data_socket = client_socket; return 0; } static int cmd_pwd(lftpd_client_t* client, const char* arg) { send_simple_response(client->socket, 257, "\"%s\"", client->directory); return 0; } static int cmd_quit(lftpd_client_t* client, const char* arg) { send_simple_response(client->socket, 221, STATUS_221); return -1; } static int cmd_retr(lftpd_client_t* client, const char* arg) { if (client->data_socket == -1) { send_simple_response(client->socket, 425, STATUS_425); return -1; } send_simple_response(client->socket, 150, STATUS_150); char* path = lftpd_io_canonicalize_path(client->directory, arg); lftpd_log_debug("send '%s'", path); int err = send_file(client->data_socket, path); free(path); close(client->data_socket); client->data_socket = -1; if (err == 0) { send_simple_response(client->socket, 226, STATUS_226); } else { send_simple_response(client->socket, 450, STATUS_450); } return 0; } static int cmd_size(lftpd_client_t* client, const char* arg) { if (!arg) { send_simple_response(client->socket, 550, STATUS_550); return 0; } char* path = lftpd_io_canonicalize_path(client->directory, arg); lftpd_log_debug("size %s", path); int fd = fs_open(path, O_RDONLY); if (fd < 0) { send_simple_response(client->socket, 550, STATUS_550); } else { send_simple_response(client->socket, 213, "%lu", fs_total(fd)); fs_close(fd); } free(path); return 0; } static int cmd_stor(lftpd_client_t* client, const char* arg) { if (client->data_socket == -1) { send_simple_response(client->socket, 425, STATUS_425); return -1; } send_simple_response(client->socket, 150, STATUS_150); char* path = lftpd_io_canonicalize_path(client->directory, arg); lftpd_log_debug("receive '%s'", path); int err = receive_file(client->data_socket, path); free(path); close(client->data_socket); client->data_socket = -1; if (err == 0) { send_simple_response(client->socket, 226, STATUS_226); } else { send_simple_response(client->socket, 450, STATUS_450); } return 0; } static int cmd_syst(lftpd_client_t* client, const char* arg) { send_simple_response(client->socket, 215, "UNIX Type: L8"); return 0; } static int cmd_type(lftpd_client_t* client, const char* arg) { send_simple_response(client->socket, 200, STATUS_200); return 0; } static int cmd_user(lftpd_client_t* client, const char* arg) { send_simple_response(client->socket, 230, STATUS_230); return 0; } static int handle_control_channel(lftpd_client_t* client) { int err = send_simple_response(client->socket, 220, STATUS_220); if (err != 0) { lftpd_log_error("error sending welcome message"); goto cleanup; } size_t read_buffer_len = 512; char* read_buffer = malloc(read_buffer_len); while (err == 0) { int line_len = lftpd_inet_read_line(client->socket, read_buffer, read_buffer_len); if (line_len != 0) { lftpd_log_error("error reading next command"); goto cleanup; } // find the index of the first space int index; char* p = strchr(read_buffer, ' '); if (p != NULL) { index = p - read_buffer; } // if no space, use the whole string else { index = strlen(read_buffer); } // if the index is 5 or greater the command is too long if (index >= 5) { err = send_simple_response(client->socket, 500, STATUS_500); continue; } // copy the command into a temporary buffer char command_tmp[4 + 1]; memset(command_tmp, 0, sizeof(command_tmp)); memcpy(command_tmp, read_buffer, index); // upper case the command for (int i = 0; command_tmp[i]; i++) { command_tmp[i] = (char) toupper((int) command_tmp[i]); } // see if we have a matching function for the command, and if // so, dispatch it bool matched = false; for (int i = 0; commands[i].command; i++) { if (strcmp(commands[i].command, command_tmp) == 0) { char* arg = NULL; if (index < strlen(read_buffer)) { arg = strdup(read_buffer + index + 1); arg = lftpd_string_trim(arg); } err = commands[i].handler(client, arg); free(arg); matched = true; break; } } if (!matched) { send_simple_response(client->socket, 502, STATUS_502); } } cleanup: close(client->socket); return 0; } int lftpd_start(const char* directory, int port, lftpd_t* lftpd) { memset(lftpd, 0, sizeof(lftpd_t)); lftpd->directory = directory; lftpd->port = port; lftpd->server_socket = lftpd_inet_listen(port); if (lftpd->server_socket < 0) { lftpd_log_error("error creating listener"); return -1; } lftpd_log_info("listening on %d.%d.%d.%d:%d...", net_default_dev->ip_addr[0], net_default_dev->ip_addr[1], net_default_dev->ip_addr[2], net_default_dev->ip_addr[3], port ); while (true) { lftpd_log_info("waiting for connection..."); int client_socket = accept(lftpd->server_socket, NULL, NULL); if (client_socket < 0) { lftpd_log_error("error accepting client socket"); break; } lftpd_log_info("connection received."); lftpd_client_t client = { .directory = strdup(directory), .socket = client_socket, .data_socket = -1, }; lftpd->client = &client; handle_control_channel(&client); free(client.directory); lftpd->client = NULL; } close(lftpd->server_socket); return 0; } int lftpd_stop(lftpd_t* lftpd) { close(lftpd->server_socket); if (lftpd->client) { close(lftpd->client->socket); } return 0; } <file_sep>/modules/mp3/libmp3/xingmp3/csbt.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** csbt.c *************************************************** MPEG audio decoder, dct and window portable C 1/7/96 mod for Layer III ******************************************************************/ #include <float.h> #include <math.h> #include "L3.h" #include "mhead.h" void fdct32(MPEG *m, float *, float *); void fdct32_dual(MPEG *m, float *, float *); void fdct32_dual_mono(MPEG *m, float *, float *); void fdct16(MPEG *m, float *, float *); void fdct16_dual(MPEG *m, float *, float *); void fdct16_dual_mono(MPEG *m, float *, float *); void fdct8(MPEG *m, float *, float *); void fdct8_dual(MPEG *m, float *, float *); void fdct8_dual_mono(MPEG *m, float *, float *); void window(MPEG *m, float *, int , short *pcm); void window_dual(MPEG *m, float *, int , short *pcm); void window16(MPEG *m, float *, int , short *pcm); void window16_dual(MPEG *m, float *, int , short *pcm); void window8(MPEG *m, float *, int , short *pcm); void window8_dual(MPEG *m, float *, int , short *pcm); float *dct_coef_addr(MPEG *m); /*-------------------------------------------------------------------------*/ /* circular window buffers */ /*======================================================================*/ static void gencoef(MPEG *m) /* gen coef for N=32 (31 coefs) */ { int p, n, i, k; double t, pi; float *coef32; coef32 = dct_coef_addr(m); pi = 4.0 * atan(1.0); n = 16; k = 0; for (i = 0; i < 5; i++, n = n / 2) { for (p = 0; p < n; p++, k++) { t = (pi / (4 * n)) * (2 * p + 1); coef32[k] = (float) (0.50 / cos(t)); } } } /*------------------------------------------------------------*/ void sbt_init(MPEG *m) { int i; if (m->csbt.first_pass) { gencoef(m); m->csbt.first_pass = 0; } /* clear window m->csbt.vbuf */ for (i = 0; i < 512; i++) { m->csbt.vbuf[i] = 0.0F; m->csbt.vbuf2[i] = 0.0F; } m->csbt.vb2_ptr = m->csbt.vb_ptr = 0; } /*============================================================*/ /*============================================================*/ /*============================================================*/ void sbt_mono(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct32(m, sample, m->csbt.vbuf + m->csbt.vb_ptr); window(m, m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ void sbt_dual(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct32_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); fdct32_dual(m,sample + 1, m->csbt.vbuf2 + m->csbt.vb_ptr); window_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); window_dual(m,m->csbt.vbuf2, m->csbt.vb_ptr, pcm + 1); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 64; } } /*------------------------------------------------------------*/ /* convert dual to mono */ void sbt_dual_mono(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct32_dual_mono(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /* convert dual to left */ void sbt_dual_left(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct32_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /* convert dual to right */ void sbt_dual_right(MPEG *m, float *sample, short *pcm, int n) { int i; sample++; /* point to right chan */ for (i = 0; i < n; i++) { fdct32_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /*---------------- 16 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ void sbt16_mono(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct16(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void sbt16_dual(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct16_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); fdct16_dual(m,sample + 1, m->csbt.vbuf2 + m->csbt.vb_ptr); window16_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); window16_dual(m,m->csbt.vbuf2, m->csbt.vb_ptr, pcm + 1); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 32; } } /*------------------------------------------------------------*/ void sbt16_dual_mono(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct16_dual_mono(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void sbt16_dual_left(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct16_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void sbt16_dual_right(MPEG *m, float *sample, short *pcm, int n) { int i; sample++; for (i = 0; i < n; i++) { fdct16_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ /*---------------- 8 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ void sbt8_mono(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct8(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void sbt8_dual(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct8_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); fdct8_dual(m,sample + 1, m->csbt.vbuf2 + m->csbt.vb_ptr); window8_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); window8_dual(m,m->csbt.vbuf2, m->csbt.vb_ptr, pcm + 1); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 16; } } /*------------------------------------------------------------*/ void sbt8_dual_mono(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct8_dual_mono(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void sbt8_dual_left(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct8_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void sbt8_dual_right(MPEG *m, float *sample, short *pcm, int n) { int i; sample++; for (i = 0; i < n; i++) { fdct8_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ /*------------------------------------------------------------*/ #include "csbtb.c" /* 8 bit output */ #include "csbtL3.c" /* Layer III */ /*------------------------------------------------------------*/ <file_sep>/firmware/isoldr/loader/kos/src/video.c /* KallistiOS ##version## video.c (c)2001 <NAME> (scav) Parts (c)2000-2001 <NAME> */ #include <dc/video.h> #include "string.h" //#define FORCE_VMODE_FROM_DS 1 #ifndef FORCE_VMODE_FROM_DS //#define FBPOS(n) (n * 0x200000) /*-----------------------------------------------------------------------------*/ /* This table is indexed w/ DM_* */ vid_mode_t vid_builtin[DM_MODE_COUNT] = { /* NULL mode.. */ /* DM_INVALID = 0 */ // { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, { 0, 0, 0, 0 } }, // // /* 320x240 VGA 60Hz */ // /* DM_320x240_VGA */ // { // DM_320x240, // 320, 240, // VID_PIXELDOUBLE | VID_LINEDOUBLE, // CT_VGA, // 0, // 262, 857, // 0xAC, 0x28, // 0x15, 0x104, // 141, 843, // 24, 263, // 0, 1, // { 0, 0, 0, 0 } // }, // // /* 320x240 NTSC 60Hz */ // /* DM_320x240_NTSC */ // { // DM_320x240, // 320, 240, // VID_PIXELDOUBLE | VID_LINEDOUBLE, // CT_ANY, // 0, // 262, 857, // 0xA4, 0x18, // 0x15, 0x104, // 141, 843, // 24, 263, // 0, 1, // { 0, 0, 0, 0 } // }, /* 640x480 VGA 60Hz */ /* DM_640x480_VGA */ { DM_640x480, 640, 480, VID_INTERLACE, CT_VGA, 0, 0x20C, 0x359, 0xAC, 0x28, 0x15, 0x104, 0x7E, 0x345, 0x24, 0x204, 0, 1, { 0, 0, 0, 0 } }, /* 640x480 NTSC 60Hz IL */ /* DM_640x480_NTSC_IL */ { DM_640x480, 640, 480, VID_INTERLACE, CT_ANY, 0, 0x20C, 0x359, 0xA4, 0x12, 0x15, 0x104, 0x7E, 0x345, 0x24, 0x204, 0, 1, { 0, 0, 0, 0 } }, /* 800x608 NTSC 60Hz (VGA) [BROKEN!] */ /* DM_800x608_VGA */ { DM_800x608, 320, 240, VID_INTERLACE, 1/*CT_ANY*/, /* This will block the mode from being set. */ 0, 262, 857, 164, 24, 21, 82, 141, 843, 24, 264, 0, 1, { 0, 0, 0, 0 } }, /* 640x480 PAL 50Hz IL */ /* DM_640x480_PAL_IL */ { DM_640x480, 640, 480, VID_INTERLACE | VID_PAL, CT_ANY, 0, 0x270, 0x35F, 0xAE, 0x2D, 0x15, 0x104, 0x8D, 0x34B, 0x2C, 0x26C, 0, 1, { 0, 0, 0, 0 } }, // // /* 256x256 PAL 50Hz IL (seems to output the same w/o VID_PAL, ie. in NTSC IL mode) */ // /* DM_256x256_PAL_IL */ // { // DM_256x256, // 256, 256, // VID_PIXELDOUBLE | VID_LINEDOUBLE | VID_INTERLACE | VID_PAL, // CT_ANY, // 0, // 624, 863, // 226, 37, // 0x15, 0x104, // 0x8D, 0x34B, // 0x2C, 0x26C, // 0, 1, // { 0, 0, 0, 0 } // }, // // /* 768x480 NTSC 60Hz IL (thanks DCGrendel) */ // /* DM_768x480_NTSC_IL */ // { // DM_768x480, // 768, 480, // VID_INTERLACE, // CT_ANY, // 0, // 524, 857, // 96, 18, // 0x15, 0x104, // 0x2e, 0x345, // 0x24, 0x204, // 0, 1, // { 0, 0, 0, 0 } // }, // // /* 768x576 PAL 50Hz IL (DCG) */ // /* DM_768x576_PAL_IL */ // { // DM_768x576, // 768, 576, // VID_INTERLACE | VID_PAL, // CT_ANY, // 0, // 624, 863, // 88, 16, // 0x18, 0x104, // 0x36, 0x34b, // 0x2c, 0x26c, // 0, 1, // { 0, 0, 0, 0 } // }, // // /* 768x480 PAL 50Hz IL */ // /* DM_768x480_PAL_IL */ // { // DM_768x480, // 768, 480, // VID_INTERLACE | VID_PAL, // CT_ANY, // 0, // 624, 863, // 88, 16, // 0x18, 0x104, // 0x36, 0x34b, // 0x2c, 0x26c, // 0, 1, // { 0, 0, 0, 0 } // }, // // /* 320x240 PAL 50Hz (thanks <NAME> aka Mekanaizer) */ // /* DM_320x240_PAL */ // { // DM_320x240, // 320, 240, // VID_PIXELDOUBLE | VID_LINEDOUBLE | VID_PAL, // CT_ANY, // 0, // 312, 863, // 174, 45, // 21, 260, // 141, 843, // 44, 620, // 0, 1, // { 0, 0, 0, 0 } // }, // // /* All of the modes below this comment are exactly the same as the ones // above, other than that they support multiple framebuffers (in the current // case, 4). They're only particularly useful if you're doing a drawing by // directly writing to the framebuffer, and are not useful at all if you're // using the PVR to do your drawing. */ // /* 320x240 VGA 60Hz */ // /* DM_320x240_VGA_MB */ // { // DM_320x240 | DM_MULTIBUFFER, // 320, 240, // VID_PIXELDOUBLE | VID_LINEDOUBLE, // CT_VGA, // 0, // 262, 857, // 0xAC, 0x28, // 0x15, 0x104, // 141, 843, // 24, 263, // 0, VID_MAX_FB, // { FBPOS(0), FBPOS(1), FBPOS(2), FBPOS(3) } // }, // // /* 320x240 NTSC 60Hz */ // /* DM_320x240_NTSC_MB */ // { // DM_320x240 | DM_MULTIBUFFER, // 320, 240, // VID_PIXELDOUBLE | VID_LINEDOUBLE, // CT_ANY, // 0, // 262, 857, // 0xA4, 0x18, // 0x15, 0x104, // 141, 843, // 24, 263, // 0, VID_MAX_FB, // { FBPOS(0), FBPOS(1), FBPOS(2), FBPOS(3) } // }, // // /* 640x480 VGA 60Hz */ // /* DM_640x480_VGA_MB */ // { // DM_640x480 | DM_MULTIBUFFER, // 640, 480, // VID_INTERLACE, // CT_VGA, // 0, // 0x20C, 0x359, // 0xAC, 0x28, // 0x15, 0x104, // 0x7E, 0x345, // 0x24, 0x204, // 0, VID_MAX_FB, // { FBPOS(0), FBPOS(1), FBPOS(2), FBPOS(3) } // }, // // /* 640x480 NTSC 60Hz IL */ // /* DM_640x480_NTSC_IL_MB */ // { // DM_640x480 | DM_MULTIBUFFER, // 640, 480, // VID_INTERLACE, // CT_ANY, // 0, // 0x20C, 0x359, // 0xA4, 0x12, // 0x15, 0x104, // 0x7E, 0x345, // 0x24, 0x204, // 0, VID_MAX_FB, // { FBPOS(0), FBPOS(1), FBPOS(2), FBPOS(3) } // }, // // /* 800x608 NTSC 60Hz (VGA) [BROKEN!] */ // /* DM_800x608_VGA_MB */ // { // DM_800x608 | DM_MULTIBUFFER, // 320, 240, // VID_INTERLACE, // 1/*CT_ANY*/, /* This will block the mode from being set. */ // 0, // 262, 857, // 164, 24, // 21, 82, // 141, 843, // 24, 264, // 0, VID_MAX_FB, // { FBPOS(0), FBPOS(1), FBPOS(2), FBPOS(3) } // }, // // /* 640x480 PAL 50Hz IL */ // /* DM_640x480_PAL_IL_MB */ // { // DM_640x480 | DM_MULTIBUFFER, // 640, 480, // VID_INTERLACE | VID_PAL, // CT_ANY, // 0, // 0x270, 0x35F, // 0xAE, 0x2D, // 0x15, 0x104, // 0x8D, 0x34B, // 0x2C, 0x26C, // 0, VID_MAX_FB, // { FBPOS(0), FBPOS(1), FBPOS(2), FBPOS(3) } // }, // // /* 256x256 PAL 50Hz IL (seems to output the same w/o VID_PAL, ie. in NTSC IL mode) */ // /* DM_256x256_PAL_IL_MB */ // { // DM_256x256 | DM_MULTIBUFFER, // 256, 256, // VID_PIXELDOUBLE | VID_LINEDOUBLE | VID_INTERLACE | VID_PAL, // CT_ANY, // 0, // 624, 863, // 226, 37, // 0x15, 0x104, // 0x8D, 0x34B, // 0x2C, 0x26C, // 0, VID_MAX_FB, // { FBPOS(0), FBPOS(1), FBPOS(2), FBPOS(3) } // }, // // /* 768x480 NTSC 60Hz IL (thanks DCGrendel) */ // /* DM_768x480_NTSC_IL_MB */ // { // DM_768x480 | DM_MULTIBUFFER, // 768, 480, // VID_INTERLACE, // CT_ANY, // 0, // 524, 857, // 96, 18, // 0x15, 0x104, // 0x2e, 0x345, // 0x24, 0x204, // 0, VID_MAX_FB, // { FBPOS(0), FBPOS(1), FBPOS(2), FBPOS(3) } // }, // // /* 768x576 PAL 50Hz IL (DCG) */ // /* DM_768x576_PAL_IL_MB */ // { // DM_768x576 | DM_MULTIBUFFER, // 768, 576, // VID_INTERLACE | VID_PAL, // CT_ANY, // 0, // 624, 863, // 88, 16, // 0x18, 0x104, // 0x36, 0x34b, // 0x2c, 0x26c, // 0, VID_MAX_FB, // { FBPOS(0), FBPOS(1), FBPOS(2), FBPOS(3) } // }, // // /* 768x480 PAL 50Hz IL */ // /* DM_768x480_PAL_IL_MB */ // { // DM_768x480 | DM_MULTIBUFFER, // 768, 480, // VID_INTERLACE | VID_PAL, // CT_ANY, // 0, // 624, 863, // 88, 16, // 0x18, 0x104, // 0x36, 0x34b, // 0x2c, 0x26c, // 0, VID_MAX_FB, // { FBPOS(0), FBPOS(1), FBPOS(2), FBPOS(3) } // }, // // /* 320x240 PAL 50Hz (thanks <NAME> aka Mekanaizer) */ // /* DM_320x240_PAL_MB */ // { // DM_320x240 | DM_MULTIBUFFER, // 320, 240, // VID_PIXELDOUBLE | VID_LINEDOUBLE | VID_PAL, // CT_ANY, // 0, // 312, 863, // 174, 45, // 21, 260, // 141, 843, // 44, 620, // 0, VID_MAX_FB, // { FBPOS(0), FBPOS(1), FBPOS(2), FBPOS(3) } // }, /* END */ /* DM_SENTINEL */ // { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, { 0, 0, 0, 0 } } /* DM_MODE_COUNT */ }; /*-----------------------------------------------------------------------------*/ static vuint32 *regs = (uint32*)0xA05F8000; static vid_mode_t currmode = { 0 }; vid_mode_t *vid_mode = 0; #endif uint16 *vram_s; uint32 *vram_l; #ifndef FORCE_VMODE_FROM_DS /*-----------------------------------------------------------------------------*/ /* Checks the attached cable type (to the A/V port). Returns one of the following: 0 == VGA 1 == (nothing) 2 == RGB 3 == Composite This is a direct port of Marcus' assembly function of the same name. [This is the old KOS function by Dan.] */ int vid_check_cable() { vuint32 * porta = (uint32 *)0xff80002c; *porta = (*porta & 0xfff0ffff) | 0x000a0000; /* Read port8 and port9 */ return (*((vuint16*)(porta + 1)) >> 8) & 3; } /*-----------------------------------------------------------------------------*/ void vid_set_mode(int dm, int pm) { vid_mode_t mode; int i, ct, found, dm2; ct = vid_check_cable(); /* Remove the multi-buffering flag from the mode, if its present, and save the state of that flag. */ dm2 = dm & DM_MULTIBUFFER; dm &= ~DM_MULTIBUFFER; /* Check to see if we should use a direct mode index, a generic mode check, or if it's just invalid. */ if(dm > DM_INVALID && dm < DM_SENTINEL) { memcpy(&mode, &vid_builtin[dm], sizeof(vid_mode_t)); } else if(dm >= DM_GENERIC_FIRST && dm <= DM_GENERIC_LAST) { found = 0; for(i = 1; i < DM_SENTINEL; i++) { /* Is it the right generic mode? */ if(vid_builtin[i].generic != (dm | dm2)) continue; /* Do we have the right cable type? */ if(vid_builtin[i].cable_type != CT_ANY && vid_builtin[i].cable_type != ct) continue; /* Ok, nothing else to check right now -- we've got our mode */ memcpy(&mode, &vid_builtin[i], sizeof(vid_mode_t)); found = 1; break; } if(!found) { return; } } else { return; } /* We set this here so actual mode is bit-depth independent.. */ mode.pm = pm; /* This is also to be generic */ mode.cable_type = ct; /* This will make a private copy of our "mode" */ vid_set_mode_ex(&mode); } /*-----------------------------------------------------------------------------*/ void vid_set_mode_ex(vid_mode_t *mode) { static uint8 bpp[4] = { 2, 2, 0, 4 }; uint16 ct; uint32 data; /* Verify cable type for video mode. */ ct = vid_check_cable(); if(mode->cable_type != CT_ANY) { if(mode->cable_type != ct) { /* Maybe this should have the ability to be forced (thru param) so you can set a mode with VGA params with RGB cable type? */ /*ct=mode->cable_type; */ return; } } /* Blank screen and reset display enable (looks nicer) */ regs[0x3A] |= 8; /* Blank */ regs[0x11] &= ~1; /* Display disable */ /* Clear interlace flag if VGA (this maybe should be in here?) */ if(ct == CT_VGA) { mode->flags &= ~VID_INTERLACE; if(mode->flags & VID_LINEDOUBLE) mode->scanlines *= 2; } vid_border_color(0, 0, 0); /* Pixelformat */ data = (mode->pm << 2); if(ct == CT_VGA) { data |= 1 << 23; if(mode->flags & VID_LINEDOUBLE) data |= 2; } regs[0x11] = data; /* Linestride */ regs[0x13] = (mode->width * bpp[mode->pm]) / 8; /* Display size */ data = ((mode->width * bpp[mode->pm]) / 4) - 1; if(ct == CT_VGA || (!(mode->flags & VID_INTERLACE))) { data |= (1 << 20) | ((mode->height - 1) << 10); } else { data |= (((mode->width * bpp[mode->pm] >> 2) + 1) << 20) | (((mode->height / 2) - 1) << 10); } regs[0x17] = data; /* vblank irq */ if(ct == CT_VGA) { regs[0x33] = (mode->scanint1 << 16) | (mode->scanint2 << 1); } else { regs[0x33] = (mode->scanint1 << 16) | mode->scanint2; } /* Interlace stuff */ data = 0x100; if(mode->flags & VID_INTERLACE) { data |= 0x10; if(mode->flags & VID_PAL) { data |= 0x80; } else { data |= 0x40; } } regs[0x34] = data; /* Border window */ regs[0x35] = (mode->borderx1 << 16) | mode->borderx2; regs[0x37] = (mode->bordery1 << 16) | mode->bordery2; /* Scanlines and clocks. */ regs[0x36] = (mode->scanlines << 16) | mode->clocks; /* Horizontal pixel doubling */ if(mode->flags & VID_PIXELDOUBLE) { regs[0x3A] |= 0x100; } else { regs[0x3A] &= ~0x100; } /* Bitmap window */ regs[0x3B] = mode->bitmapx; data = mode->bitmapy; if(mode->flags & VID_PAL) { data++; } data = (data << 16) | mode->bitmapy; regs[0x3C] = data; /* Everything is ok */ memcpy(&currmode, mode, sizeof(vid_mode_t)); vid_mode = &currmode; /* Set up the framebuffer */ vid_mode->fb_curr = -1; vid_flip(0); /* Set cable type */ *((vuint32*)0xa0702c00) = (*((vuint32*)0xa0702c00) & 0xfffffcff) | ((ct & 3) << 8); /* Re-enable the display */ regs[0x3A] &= ~8; regs[0x11] |= 1; } /*-----------------------------------------------------------------------------*/ void vid_set_start(uint32 base) { static uint8 bpp[4] = { 2, 2, 0, 4 }; /* Set vram base of current framebuffer */ base &= 0x007FFFFF; regs[0x14] = base; /* These are nice to have. */ vram_s = (uint16*)(0xA5000000 | base); vram_l = (uint32*)(0xA5000000 | base); /* Set odd-field if interlaced. */ if(vid_mode->flags & VID_INTERLACE) { regs[0x15] = base + (currmode.width * bpp[currmode.pm]); } } /*-----------------------------------------------------------------------------*/ void vid_flip(int fb) { uint16 oldfb; uint32 base; oldfb = vid_mode->fb_curr; if(fb < 0) { vid_mode->fb_curr++; } else { vid_mode->fb_curr = fb; } vid_mode->fb_curr &= (vid_mode->fb_count - 1); if(vid_mode->fb_curr == oldfb) { return; } vid_set_start(vid_mode->fb_base[vid_mode->fb_curr]); /* Set the vram_* pointers as expected */ base = vid_mode->fb_base[(vid_mode->fb_curr + 1) & (vid_mode->fb_count - 1)]; vram_s = (uint16*)(0xA5000000 | base); vram_l = (uint32*)(0xA5000000 | base); } /*-----------------------------------------------------------------------------*/ uint32 vid_border_color(int r, int g, int b) { uint32 obc = regs[0x0040 / 4]; regs[0x0040 / 4] = ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF); return obc; } /*-----------------------------------------------------------------------------*/ /* Clears the screen with a given color [This is the old KOS function by Dan.] */ void vid_clear(int r, int g, int b) { uint16 pixel16; uint32 pixel32; switch(vid_mode->pm) { case PM_RGB555: pixel16 = ((r >> 3) << 10) | ((g >> 3) << 5) | ((b >> 3) << 0); memset2(vram_s, pixel16, (vid_mode->width * vid_mode->height)); break; case PM_RGB565: pixel16 = ((r >> 3) << 11) | ((g >> 2) << 5) | ((b >> 3) << 0); memset2(vram_s, pixel16, (vid_mode->width * vid_mode->height)); break; case PM_RGB888: pixel32 = (r << 16) | (g << 8) | (b << 0); memset4(vram_l, pixel32, (vid_mode->width * vid_mode->height)); break; default: break; } } /*-----------------------------------------------------------------------------*/ /* Clears all of video memory as quickly as possible [This is the old KOS function by Dan.] */ void vid_empty() { /* We'll use the actual base address here since the vram_* pointers can now move around */ memset4((uint32 *)0xa5000000, 0, 2 * 1024 * 1024); } /*-----------------------------------------------------------------------------*/ /* Waits for a vertical refresh to start. This is the period between when the scan beam reaches the bottom of the picture, and when it starts again at the top. Thanks to HeroZero for this info. [This is the old KOS function by Dan.] */ void vid_waitvbl() { vuint32 *vbl = regs + 0x010c / 4; while(!(*vbl & 0x01ff)) ; while(*vbl & 0x01ff) ; } #endif /*-----------------------------------------------------------------------------*/ void vid_init(int disp_mode, int pixel_mode) { /* Set mode and clear vram */ #ifndef FORCE_VMODE_FROM_DS vid_set_mode(disp_mode, pixel_mode); vid_clear(0, 0, 0); vid_flip(0); #else (void)disp_mode; (void)pixel_mode; vram_s = (uint16*)(VIDEO_VRAM_START); vram_l = (uint32*)(VIDEO_VRAM_START); for(int i = 0; i < 0x4B000; i++) vram_s[i] = 0; #endif } /*-----------------------------------------------------------------------------*/ //void vid_shutdown() { // /* Play nice with loaders, like KOS used to do. */ // vid_init(DM_640x480, PM_RGB565); //} // // //uint16 vid_pixel(int r, int g, int b) { // return (((r >> 3) & 0x1f) << 11) | // (((g >> 2) & 0x3f) << 5) | // (((b >> 3) & 0x1f)); //} <file_sep>/firmware/isoldr/loader/malloc.c /** * DreamShell ISO Loader * Memory allocation * (c)2022-2023 SWAT <http://www.dc-swat.ru> */ #include <main.h> #include <maple.h> enum malloc_types { MALLOC_TYPE_INTERNAL = 0, MALLOC_TYPE_KATANA = 1 }; static int malloc_type = MALLOC_TYPE_INTERNAL; /** * @brief KATANA ingame memory allocation */ // FIXME: Can be different #define KATANA_MALLOC_INDEX 0x84 #define KATANA_FREE_INDEX 0x152 #define KATANA_REALLOC_INDEX 0x20a static uint8 *katana_malloc_root = NULL; static const uint8 katana_malloc_key[] = {<KEY>}; static int katana_malloc_init(void) { if (!katana_malloc_root || memcmp(katana_malloc_root, katana_malloc_key, sizeof(katana_malloc_key))) { katana_malloc_root = search_memory(katana_malloc_key, sizeof(katana_malloc_key)); } if (katana_malloc_root) { malloc_type = MALLOC_TYPE_KATANA; LOGF("KATANA malloc initialized\n"); return 0; } LOGF("KATANA malloc init failed\n"); return -1; } static void katana_malloc_stat(uint32 *free_size, uint32 *max_free_size) { if (katana_malloc_root) { return (*(void(*)())katana_malloc_root)(free_size, max_free_size); } else { *free_size = 0; *max_free_size = 0; } } static void *katana_malloc(uint32 size) { void *mem = NULL; if (katana_malloc_root) { mem = (*(void*(*)())(katana_malloc_root + KATANA_MALLOC_INDEX))(size); } return mem; } static void katana_free(void *data) { if (data && katana_malloc_root) { return (*(void(*)())(katana_malloc_root + KATANA_FREE_INDEX))(data); } } static void *katana_realloc(void *data, uint32 size) { void *mem = NULL; if (data && katana_malloc_root) { mem = (*(void*(*)())(katana_malloc_root + KATANA_REALLOC_INDEX))(data, size); } return mem; } /** * @brief Simple memory allocation */ static inline size_t word_align(size_t size) { return size + ((sizeof(size_t) - 1) & ~(sizeof(size_t) - 1)); } struct chunk { struct chunk *next, *prev; size_t size; int free; void *data; }; typedef struct chunk *Chunk; static void *internal_malloc_base = NULL; static void *internal_malloc_pos = NULL; static void internal_malloc_init_auto() { if (loader_addr < APP_ADDR && IsoInfo->exec.type != BIN_TYPE_WINCE) { if ((loader_addr >= ISOLDR_DEFAULT_ADDR_LOW && IsoInfo->emu_cdda) || (IsoInfo->emu_cdda && IsoInfo->use_irq == 0) || IsoInfo->boot_mode != BOOT_MODE_DIRECT || (loader_end > (IPBIN_ADDR + 0x2000) && (IsoInfo->emu_cdda || IsoInfo->image_type == ISOFS_IMAGE_TYPE_ZSO)) ) { internal_malloc_base = (void *)ISOLDR_DEFAULT_ADDR_HIGH - 0x8000; } else if (loader_end < IPBIN_ADDR && (IsoInfo->emu_cdda == 0 || IsoInfo->use_irq) ) { internal_malloc_base = (void *)IPBIN_ADDR + 0x800; } } else if (loader_addr > APP_ADDR) { internal_malloc_base = (void *)ISOLDR_DEFAULT_ADDR_MIN + 0x1000; } else if (IsoInfo->exec.type == BIN_TYPE_WINCE) { if (loader_end < IPBIN_ADDR) { internal_malloc_base = (void *)IPBIN_ADDR + 0x800; } } } static void internal_malloc_init_maple(int first) { if (first == 0) { uint32 addr = MAPLE_REG(MAPLE_DMA_ADDR); internal_malloc_base = (void *)CACHED_ADDR(addr); if (IsoInfo->image_type == ISOFS_IMAGE_TYPE_ZSO || IsoInfo->emu_cdda ) { internal_malloc_base += 0x1000; } else { if (IsoInfo->exec.type == BIN_TYPE_KOS) { internal_malloc_base += 0x3000; } else { internal_malloc_base += 0x5000; } } } else { // Temporary place before executing internal_malloc_init_auto(); } } static int internal_malloc_init(int first) { internal_malloc_base = (void *)ALIGN32_ADDR(loader_end); internal_malloc_pos = NULL; if (IsoInfo->heap >= HEAP_MODE_SPECIFY) { internal_malloc_base = (void *)IsoInfo->heap; } else if (IsoInfo->heap == HEAP_MODE_AUTO) { internal_malloc_init_auto(); } else if (IsoInfo->heap == HEAP_MODE_INGAME) { /** * Temporary place before executing * or if KATANA malloc init failed. */ internal_malloc_init_auto(); } else if(IsoInfo->heap == HEAP_MODE_MAPLE) { internal_malloc_init_maple(first); } internal_malloc_pos = internal_malloc_base + word_align(sizeof(struct chunk)); Chunk b = internal_malloc_base; b->next = NULL; b->prev = NULL; b->size = 0; b->free = 0; b->data = NULL; LOGF("Internal malloc initialized\n"); malloc_type = MALLOC_TYPE_INTERNAL; return 0; } static void internal_malloc_stat(uint32 *free_size, uint32 *max_free_size) { uint32 exec_addr = CACHED_ADDR(IsoInfo->exec.addr); if ((uint32)internal_malloc_base < exec_addr) { *free_size = exec_addr - (uint32)internal_malloc_pos; *max_free_size = exec_addr - (uint32)internal_malloc_base; } else { *free_size = RAM_END_ADDR - (uint32)internal_malloc_pos; *max_free_size = RAM_END_ADDR - (uint32)internal_malloc_base; } } Chunk internal_malloc_chunk_find(size_t s, Chunk *heap) { Chunk c = internal_malloc_base; for (; c && (!c->free || c->size < s); *heap = c, c = c->next); return c; } void internal_malloc_merge_next(Chunk c) { c->size = c->size + c->next->size + sizeof(struct chunk); c->next = c->next->next; if (c->next) { c->next->prev = c; } } void internal_malloc_split_next(Chunk c, size_t size) { Chunk newc = (Chunk)((char*) c + size); newc->prev = c; newc->next = c->next; newc->size = c->size - size; newc->free = 1; newc->data = newc + 1; if (c->next) { c->next->prev = newc; } c->next = newc; c->size = size - sizeof(struct chunk); } void *internal_malloc(size_t size) { if (!size) { return NULL; } size_t length = word_align(size + sizeof(struct chunk)); Chunk prev = NULL; Chunk c = internal_malloc_chunk_find(size, &prev); if (!c) { Chunk newc = internal_malloc_pos; internal_malloc_pos += length; newc->next = NULL; newc->prev = prev; newc->size = length - sizeof(struct chunk); newc->data = newc + 1; prev->next = newc; c = newc; } else if (length + sizeof(size_t) < c->size) { internal_malloc_split_next(c, length); } c->free = 0; return c->data; } void internal_free(void *ptr) { if (!ptr || ptr < internal_malloc_base) { return; } Chunk c = (Chunk) ptr - 1; if (c->data != ptr) { return; } c->free = 1; if (c->next && c->next->free) { internal_malloc_merge_next(c); } if (c->prev->free) { internal_malloc_merge_next(c = c->prev); } if (!c->next) { c->prev->next = NULL; internal_malloc_pos -= (c->size + sizeof(struct chunk)); } } void *internal_realloc(void *ptr, size_t size) { void *newptr = internal_malloc(size); if (newptr && ptr && ptr >= internal_malloc_base) { Chunk c = (Chunk) ptr - 1; if (c->data == ptr) { size_t length = c->size > size ? size : c->size; memcpy(newptr, ptr, length); free(ptr); } } return newptr; } int malloc_init(int first) { if (IsoInfo->heap == HEAP_MODE_INGAME && IsoInfo->exec.type == BIN_TYPE_KATANA && first == 0 ) { if (malloc_type == MALLOC_TYPE_KATANA) { return 1; } if (katana_malloc_init() < 0) { return internal_malloc_init(first); } return 0; } return internal_malloc_init(first); } void malloc_stat(uint32 *free_size, uint32 *max_free_size) { if (malloc_type == MALLOC_TYPE_KATANA) { katana_malloc_stat(free_size, max_free_size); } else { internal_malloc_stat(free_size, max_free_size); } } uint32 malloc_heap_pos() { if (malloc_type == MALLOC_TYPE_KATANA) { return 0; // Not used } else { return (uint32)internal_malloc_pos; } } void *malloc(uint32 size) { if (malloc_type == MALLOC_TYPE_KATANA) { void *ptr = katana_malloc(size); if (ptr == NULL) { LOGFF("KATANA failed, trying internal\n"); if (internal_malloc_pos == NULL) { internal_malloc_init(0); } return internal_malloc(size); } return ptr; } else { return internal_malloc(size); } } void free(void *data) { if (malloc_type == MALLOC_TYPE_KATANA) { katana_free(data); } else { internal_free(data); } } void *realloc(void *data, uint32 size) { if (malloc_type == MALLOC_TYPE_KATANA) { return katana_realloc(data, size); } else { return internal_realloc(data, size); } } <file_sep>/modules/ffmpeg/module.c /* DreamShell ##version## module.c - ffmpeg module Copyright (C)2011-2014 SWAT */ #include "ds.h" #include "libavcodec/avcodec.h" #include "libavformat/avformat.h" #include "libavformat/avio.h" DEFAULT_MODULE_HEADER(ffmpeg); static int file_open(URLContext *h, const char *filename, int flags) { file_t fd; int _flags = 0; char fn[NAME_MAX]; char proto[32]; sscanf(filename, "%[a-zA-Z0-9_]:%s", proto, fn); switch(flags) { case URL_RDONLY: _flags = O_RDONLY; break; case URL_WRONLY: _flags = O_WRONLY; break; case URL_RDWR: _flags = O_RDWR; break; default: ds_printf("DS_ERROR_FFMPEG: Uknown file open flag: %08x\n", flags); return -1; } if ((fd = fs_open(fn, _flags)) < 0) { return -1; } h->priv_data = (void*)fd; return 0; } static int file_read(URLContext *h, unsigned char *buf, int size) { return fs_read((file_t)h->priv_data, buf, size); } static int file_write(URLContext *h, unsigned char *buf, int size) { return fs_write((file_t)h->priv_data, buf, size); } static int64_t file_seek(URLContext *h, int64_t pos, int whence) { if(whence == AVSEEK_SIZE) { return fs_total((file_t)h->priv_data); } return fs_seek((file_t)h->priv_data, pos, whence); } static int file_close(URLContext *h) { fs_close((file_t)h->priv_data); return 0; } /* static int file_read_pause(URLContext *h, int pause) { return 0; } static int64_t file_read_seek(URLContext *h, int stream_index, int64_t timestamp, int flags) { return 0; } */ static int file_get_file_handle(URLContext *h) { return (file_t)h->priv_data; } static URLProtocol fs_protocol = { "ds", file_open, file_read, file_write, file_seek, file_close, NULL, NULL, NULL, file_get_file_handle }; int ffplay(const char *filename, const char *force_format); //int sdl_ffplay(const char *filename); int builtin_ffplay_cmd(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: %s option args...\n\n" "Options: \n" " -v, --version -Show ffmpeg version\n" //" -s, --sdl -Use SDL_ffmpeg (slow)\n" " -p, --play -Start playing\n\n" "Arguments: \n" " -i --format -Force format detection\n" " -f, --file -File for playing\n\n" "Examples: %s -p -f /cd/file.avi\n", argv[0], argv[0]); return CMD_NO_ARG; } int play = 0, /*use_sdl = 0, */ver = 0; char *file = NULL, *format = NULL; struct cfg_option options[] = { {"play", 'p', NULL, CFG_BOOL, (void *) &play, 0}, //{"sdl", 's', NULL, CFG_BOOL, (void *) &use_sdl, 0}, {"version", 'v', NULL, CFG_BOOL, (void *) &ver, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, {"format", 'i', NULL, CFG_STR, (void *) &format, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(ver) { ds_printf("DS: ffmpeg v%d.%d.%d build %02x\n", VER_MAJOR, VER_MINOR, VER_MICRO, VER_BUILD); } if(play) { //if(use_sdl) { // sdl_ffplay(file); //} else { ffplay(file, format); //} } return CMD_OK; } int lib_open(klibrary_t *lib) { av_register_all(); av_register_protocol(&fs_protocol); AddCmd("ffplay", "Video/Audio player via ffmpeg", (CmdHandler *) builtin_ffplay_cmd); return nmmgr_handler_add(&ds_ffmpeg_hnd.nmmgr); } int lib_close(klibrary_t *lib) { RemoveCmd(GetCmdByName("ffplay")); return nmmgr_handler_remove(&ds_ffmpeg_hnd.nmmgr); } <file_sep>/sdk/toolchain/fedora_build.sh #!/bin/bash # number of cpu cores cores="$(grep -c ^processor /proc/cpuinfo )" # exports export SH_PREFIX=/opt/toolchains/dc/sh-elf export ARM_PREFIX=/opt/toolchains/dc/arm-eabi export KOS_ROOT=/usr/local/dc/kos export KOS_BASE=$KOS_ROOT/kos export KOS_PORTS=$KOS_ROOT/kos-ports # install deps and setup directories sudo dnf install subversion gcc gcc-c++ make automake autoconf m4 \ bison elfutils-libelf-devel flex libtool texinfo gawk \ latex2html git sed wget libpng-devel lyx libjpeg-turbo-devel \ mpfr-devel gmp-devel isl-devel intltool zlib-devel diffutils patch sudo mkdir -p $KOS_ROOT sudo mkdir -p $SH_PREFIX/sh-elf/include sudo mkdir -p $ARM_PREFIX/share sudo chown -R $USER:$USER $ARM_PREFIX sudo chown -R $USER:$USER $SH_PREFIX sudo chown -R $USER:$USER $KOS_ROOT # clone kos git clone git://git.code.sf.net/p/cadcdev/kallistios kos git clone --recursive git://git.code.sf.net/p/cadcdev/kos-ports kos-ports cp -r kos $KOS_ROOT rm -rf kos cp -r kos-ports $KOS_ROOT rm -rf kos-ports # prepare ./download.sh ./unpack.sh cd gcc-9.3.0 ./contrib/download_prerequisites cd .. && make patch # build make -j${cores} build-sh4-binutils make -j${cores} build-sh4-gcc-pass1 make -j${cores} build-sh4-newlib-only make -j${coreS} fixup-sh4-newlib make -j${cores} build-sh4-gcc-pass2 make -j${coreS} build-arm-binutils make -j${cores} build-arm-gcc # env script cp $KOS_BASE/doc/environ.sh.sample $KOS_BASE/environ.sh sed -i 's/\/opt\/toolchains\/dc\/kos/\/usr\/local\/dc\/kos\/kos/g' $KOS_BASE/environ.sh source $KOS_BASE/environ.sh # build kos and kos-ports pushd `pwd` cd $KOS_BASE make -j${cores} cd $KOS_PORTS ./utils/build-all.sh popd <file_sep>/modules/ffmpeg/Makefile # # ffmpeg module for DreamShell # Copyright (C)2011-2022 SWAT # http://www.dc-swat.ru # TARGET_NAME = ffmpeg OBJS = module.o player.o block8x8.o aica.o mpg123.o oggvorbis.o #xvid.o #OBJS += sdl_player.o SDL_ffmpeg/src/SDL_ffmpeg.o DBG_LIBS = -lds -lbzip2 -loggvorbis -lmpg123 #-lxvidcore LIBS = -lavcodec -lavformat -lavutil #-lswscale EXPORTS_FILE = exports.txt VER_MAJOR = 0 VER_MINOR = 6 VER_MICRO = 3 KOS_CFLAGS += -I./include KOS_LIB_PATHS += -L./lib all: rm-elf ffmpeg-0.6.3/config.h include/libavcodec/avcodec.h include ../../sdk/Makefile.loadable ffmpeg-0.6.3/config.h: ln -nsf $(DS_SDK)/lib/liboggvorbis.a $(DS_SDK)/lib/libvorbisenc.a ln -nsf $(DS_SDK)/lib/liboggvorbis.a $(DS_SDK)/lib/libogg.a ln -nsf $(DS_SDK)/lib/libxvid.a $(DS_SDK)/lib/libxvidcore.a ./config.sh include/libavcodec/avcodec.h: cd ./ffmpeg-0.6.3 && make install rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/firmware/isoldr/loader/fs/fat/include/fstime.h /* $$$ : fstime.h -- */ #ifndef __FSTIME_H__ #define __FSTIME_H__ struct _time_block { int year; int mon; int day; int hour; int min; int sec; }; unsigned long rtc_secs(void); struct _time_block *conv_gmtime(unsigned long t); #endif // end of : fstime.h <file_sep>/modules/http/tcpfs.c /* * HTTP protocol for file system * Copyright (c) 2000-2001 <NAME> * Copyright (c) 2011-2019 SWAT * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ds.h" #include "network/http.h" #include <netdb.h> #include <sys/socket.h> typedef struct { int socket; int pos; int stream; } TCPContext; //#define DEBUG 1 /* return zero if error */ static uint32 t_open(const char *uri, int flags, int udp) { char hostname[128]; char options[128]; int port; TCPContext *s; int sock = -1; struct sockaddr_in sa; int res; //h->is_streamed = 1; if (flags & O_DIR) { #ifdef DEBUG dbglog(DBG_DEBUG, "TCPFS: Error, dir not supported\n"); #endif return 0; } s = malloc(sizeof(TCPContext)); if (!s) { #ifdef DEBUG dbglog(DBG_DEBUG, "TCPFS: Malloc error\n"); #endif return 0; } /* fill the dest addr */ /* needed in any case to build the host string */ _url_split(NULL, 0, hostname, sizeof(hostname), &port, options, sizeof(options), uri); if (port < 0) port = 80; #ifdef DEBUG dbglog(DBG_DEBUG, "TCP: %s:%d\n", hostname, port); #endif in_addr_t addr; if ((addr = inet_addr(hostname)) == -1) { struct hostent *he = gethostbyname(hostname); if(he == NULL) { #ifdef DEBUG dbglog(DBG_DEBUG, "TCPFS: can't resolve host %s\n", hostname); #endif goto fail; } memcpy(&sa.sin_addr, he->h_addr_list[0], he->h_length); } else { sa.sin_addr.s_addr = addr; } sa.sin_family = AF_INET; sa.sin_port = htons(port); sock = socket(PF_INET, udp ? SOCK_DGRAM : SOCK_STREAM, 0); if (sock < 0) { #ifdef DEBUG dbglog(DBG_DEBUG, "TCPFS: socket error\n"); #endif goto fail; } res = connect(sock, (struct sockaddr*)&sa, sizeof(sa)); #ifdef DEBUG dbglog(DBG_DEBUG, "TCPFS: connect --> %d\n", res); #endif if(res) { #ifdef DEBUG dbglog(DBG_DEBUG, "TCPFS: connect error\n"); #endif goto fail; } s->socket = sock; s->pos = 0; s->stream = (int)strstr(options, "<stream>"); return (uint32) s; fail: if (sock >= 0) { close(sock); } free(s); return 0; } static void *tcpfs_open(vfs_handler_t * vfs, const char *fn, int flags) { return (void*)t_open(fn, flags, 0); } static void *udpfs_open(vfs_handler_t * vfs, const char *fn, int flags) { return (void*)t_open(fn, flags, 1); } static ssize_t tcpfs_read(void *h, void *buffer, size_t size) { int len = 0; TCPContext *s = (TCPContext *)h; uint8 *buf = (uint8 *)buffer; do { int l; #ifdef DEBUG dbglog(DBG_DEBUG, "TCPFS: reading size %d -->", size); #endif l = read(s->socket, buf, size); #ifdef DEBUG dbglog(DBG_DEBUG, " %d\n", l); #endif if (l >= 0) { len += l; s->pos += l; buf += l; size -= l; } else if (len == 0) return l; else return len; } while(s->stream && 0 < size); return len; } static off_t tcpfs_seek(void *hnd, off_t size, int whence) { TCPContext *s = (TCPContext *)hnd; int len = 0; if (whence != SEEK_CUR) return s->pos; if (size <= 0) return s->pos; uint8 buf[1024]; while (size > 0) { int l = size > 1024 ? 1024 : size; l = read(s->socket, buf, l); if (l <= 0) break; len += l; size -= l; } return s->pos + len; } static ssize_t tcpfs_write(void *h, const void *buffer, size_t size) { TCPContext *s = (TCPContext *)h; #ifdef DEBUG dbglog(DBG_DEBUG, "TCPFS: write %d\n", size); #endif return write(s->socket, (uint8*)buffer, size); } static int tcpfs_close(void *h) { TCPContext *s = (TCPContext *)h; #ifdef DEBUG dbglog(DBG_DEBUG, "TCPFS: close socket %d\n", s->socket); #endif close(s->socket); free(s); return 0; } static off_t tcpfs_tell(void *h) { TCPContext *s = (TCPContext *)h; return s->pos; } /* Pull all that together */ static vfs_handler_t vh = { /* Name handler */ { "/tcp", /* name */ 0, /* tbfi */ 0x00010000, /* Version 1.0 */ 0, /* flags */ NMMGR_TYPE_VFS, /* VFS handler */ NMMGR_LIST_INIT }, 0, NULL, /* no cacheing, privdata */ tcpfs_open, tcpfs_close, tcpfs_read, tcpfs_write, tcpfs_seek, tcpfs_tell, NULL, NULL, NULL, /* ioctl */ NULL, NULL, NULL, /* mmap */ NULL, /* complete */ NULL, /* stat XXX */ NULL, /* mkdir XXX */ NULL /* rmdir XXX */ }; /* Pull all that together */ static vfs_handler_t vh_udpfs = { /* Name handler */ { "/udp", /* name */ 0, /* tbfi */ 0x00010000, /* Version 1.0 */ 0, /* flags */ NMMGR_TYPE_VFS, /* VFS handler */ NMMGR_LIST_INIT }, 0, NULL, /* no cacheing, privdata */ udpfs_open, tcpfs_close, tcpfs_read, tcpfs_write, tcpfs_seek, tcpfs_tell, NULL, NULL, NULL, /* ioctl */ NULL, NULL, NULL, /* mmap */ NULL, /* complete */ NULL, /* stat XXX */ NULL, /* mkdir XXX */ NULL /* rmdir XXX */ }; static int inited = 0; int tcpfs_init() { if (inited) return 0; inited = 1; /* Register with VFS */ return nmmgr_handler_add(&vh.nmmgr) || nmmgr_handler_add(&vh_udpfs.nmmgr); } void tcpfs_shutdown() { if (!inited) return; inited = 0; nmmgr_handler_remove(&vh.nmmgr); nmmgr_handler_remove(&vh_udpfs.nmmgr); } <file_sep>/firmware/isoldr/loader/kos/kos.h /* KallistiOS ##version## kos.h */ <file_sep>/modules/mongoose/module.c /* DreamShell ##version## module.c - mongoose module Copyright (C)2012-2014 SWAT */ #include "ds.h" #include "network/mongoose.h" DEFAULT_MODULE_EXPORTS_CMD(mongoose, "Mongoose http server"); /* static void *callback(enum mg_event event, struct mg_connection *conn, const struct mg_request_info *request_info) { if (event == MG_NEW_REQUEST) { // Echo requested URI back to the client mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n\r\n" "%s", request_info->uri); return ""; // Mark as processed } else { return NULL; } } */ static struct mg_context *ctx; int builtin_mongoose_cmd(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s options args\n" "Options: \n" " -s, --start -Start server\n" " -t, --stop -Stop server\n\n" "Arguments: \n" " -p, --port -Server listen port (default 80)\n" " -r, --root -Document root (default /)\n" " -n, --threads -Num of threads (default 3)\n\n" "Example: %s --start\n\n", argv[0], argv[0]); return CMD_NO_ARG; } int start_srv = 0, stop_srv = 0; char *port = NULL, *docroot = NULL, *thds = NULL; const char *mg_options[] = { "listening_ports", "80", "document_root", "/", "num_threads", "3", NULL }; struct cfg_option options[] = { {"start", 's', NULL, CFG_BOOL, (void *) &start_srv, 0}, {"stop", 't', NULL, CFG_BOOL, (void *) &stop_srv, 0}, {"port", 'p', NULL, CFG_STR, (void *) &port, 0}, {"root", 'r', NULL, CFG_STR, (void *) &docroot, 0}, {"threads", 'n', NULL, CFG_STR, (void *) &thds, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(start_srv) { ctx = mg_start(/*&callback*/NULL, NULL, mg_options); ds_printf("Mongoose web server v. %s started on port(s) %s with web root [%s]\n", mg_version(), mg_get_option(ctx, "listening_ports"), mg_get_option(ctx, "document_root")); return CMD_OK; } if(stop_srv) { ds_printf("mongoose: Waiting for all threads to finish..."); mg_stop(ctx); return CMD_OK; } return CMD_OK; } <file_sep>/modules/mp3/libmp3/xingmp3/l3dq.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** quant.c *************************************************** Layer III dequant does reordering of short blocks mod 8/19/98 decode 22 sf bands ******************************************************************/ #include <float.h> #include <math.h> #include <string.h> #include "L3.h" #include "mhead.h" #include "protos.h" /*---------- static struct { int l[23]; int s[14];} sfBandTable[3] = {{{0,4,8,12,16,20,24,30,36,44,52,62,74,90,110,134,162,196,238,288,342,418,576}, {0,4,8,12,16,22,30,40,52,66,84,106,136,192}}, {{0,4,8,12,16,20,24,30,36,42,50,60,72,88,106,128,156,190,230,276,330,384,576}, {0,4,8,12,16,22,28,38,50,64,80,100,126,192}}, {{0,4,8,12,16,20,24,30,36,44,54,66,82,102,126,156,194,240,296,364,448,550,576}, {0,4,8,12,16,22,30,42,58,78,104,138,180,192}}}; ----------*/ /*--------------------------------*/ static int pretab[2][22] = { {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, 2, 2, 3, 3, 3, 2, 0}, }; /* 8 bit plus 2 lookup x = pow(2.0, 0.25*(global_gain-210)) */ /* two extra slots to do 1/sqrt(2) scaling for ms */ /* 4 extra slots to do 1/2 scaling for cvt to mono */ /*-------- scaling lookup x = pow(2.0, -0.5*(1+scalefact_scale)*scalefac + preemp) look_scale[scalefact_scale][preemp][scalefac] -----------------------*/ #if 0 typedef float LS[4][32]; #endif /*--- iSample**(4/3) lookup, -32<=i<=31 ---*/ /*-- pow(2.0, -0.25*8.0*subblock_gain) --*/ /*-- reorder buffer ---*/ typedef float ARRAY3[3]; /*=============================================================*/ float *quant_init_global_addr(MPEG *m) { return m->cupl.look_global; } /*-------------------------------------------------------------*/ LS *quant_init_scale_addr(MPEG *m) { return m->cupl.look_scale; } /*-------------------------------------------------------------*/ float *quant_init_pow_addr(MPEG *m) { return m->cupl.look_pow; } /*-------------------------------------------------------------*/ float *quant_init_subblock_addr(MPEG *m) { return m->cupl.look_subblock; } /*=============================================================*/ #ifdef _MSC_VER #pragma warning(disable: 4056) #endif void dequant(MPEG *m, SAMPLE Sample[], int *nsamp, SCALEFACT * sf, GR * gr, CB_INFO * cb_info, int ncbl_mixed) { int i, j; int cb, n, w; float x0, xs; float xsb[3]; double tmp; int ncbl; int cbs0; ARRAY3 *buf; /* short block reorder */ int nbands; int i0; int non_zero; int cbmax[3]; nbands = *nsamp; ncbl = 22; /* long block cb end */ cbs0 = 12; /* short block cb start */ /* ncbl_mixed = 8 or 6 mpeg1 or 2 */ if (gr->block_type == 2) { ncbl = 0; cbs0 = 0; if (gr->mixed_block_flag) { ncbl = ncbl_mixed; cbs0 = 3; } } /* fill in cb_info -- */ /* This doesn't seem used anywhere... cb_info->lb_type = gr->block_type; if (gr->block_type == 2) cb_info->lb_type; */ cb_info->cbs0 = cbs0; cb_info->ncbl = ncbl; cbmax[2] = cbmax[1] = cbmax[0] = 0; /* global gain pre-adjusted by 2 if ms_mode, 0 otherwise */ x0 = m->cupl.look_global[(2 + 4) + gr->global_gain]; i = 0; /*----- long blocks ---*/ for (cb = 0; cb < ncbl; cb++) { non_zero = 0; xs = x0 * m->cupl.look_scale[gr->scalefac_scale][pretab[gr->preflag][cb]][sf->l[cb]]; n = m->cupl.nBand[0][cb]; for (j = 0; j < n; j++, i++) { if (Sample[i].s == 0) Sample[i].x = 0.0F; else { non_zero = 1; if ((Sample[i].s >= (-ISMAX)) && (Sample[i].s < ISMAX)) Sample[i].x = xs * m->cupl.look_pow[ISMAX + Sample[i].s]; else { float tmpConst = (float)(1.0/3.0); tmp = (double) Sample[i].s; Sample[i].x = (float) (xs * tmp * pow(fabs(tmp), tmpConst)); } } } if (non_zero) cbmax[0] = cb; if (i >= nbands) break; } cb_info->cbmax = cbmax[0]; cb_info->cbtype = 0; // type = long if (cbs0 >= 12) return; /*--------------------------- block type = 2 short blocks ----------------------------*/ cbmax[2] = cbmax[1] = cbmax[0] = cbs0; i0 = i; /* save for reorder */ buf = m->cupl.re_buf; for (w = 0; w < 3; w++) xsb[w] = x0 * m->cupl.look_subblock[gr->subblock_gain[w]]; for (cb = cbs0; cb < 13; cb++) { n = m->cupl.nBand[1][cb]; for (w = 0; w < 3; w++) { non_zero = 0; xs = xsb[w] * m->cupl.look_scale[gr->scalefac_scale][0][sf->s[w][cb]]; for (j = 0; j < n; j++, i++) { if (Sample[i].s == 0) buf[j][w] = 0.0F; else { non_zero = 1; if ((Sample[i].s >= (-ISMAX)) && (Sample[i].s < ISMAX)) buf[j][w] = xs * m->cupl.look_pow[ISMAX + Sample[i].s]; else { float tmpConst = (float)(1.0/3.0); tmp = (double) Sample[i].s; buf[j][w] = (float) (xs * tmp * pow(fabs(tmp), tmpConst)); } } } if (non_zero) cbmax[w] = cb; } if (i >= nbands) break; buf += n; } memmove(&Sample[i0].x, &m->cupl.re_buf[0][0], sizeof(float) * (i - i0)); *nsamp = i; /* update nsamp */ cb_info->cbmax_s[0] = cbmax[0]; cb_info->cbmax_s[1] = cbmax[1]; cb_info->cbmax_s[2] = cbmax[2]; if (cbmax[1] > cbmax[0]) cbmax[0] = cbmax[1]; if (cbmax[2] > cbmax[0]) cbmax[0] = cbmax[2]; cb_info->cbmax = cbmax[0]; cb_info->cbtype = 1; /* type = short */ return; } #ifdef _MSC_VER #pragma warning(default: 4056) #endif /*-------------------------------------------------------------*/ <file_sep>/modules/adx/LibADX/Makefile #LibADX (C) <NAME> 2011 TARGET = libADX.a OBJS = libadx.o include $(KOS_BASE)/addons/Makefile.prefab <file_sep>/src/lua/packlib.c /* * packlib.c -- a Lua library for packing and unpacking binary data */ /* * Added some new codes and modified some of the existing codes to * match perl templates. * * A lua string packed as (len, string) * c Signed char value * C Unsigned char value * s Signed short value * S Unsigned short value * i Signed integer value * I Unsigned integer value * l Signed long value * L Unsigned long value * f Single-precision float in the native format * d Double-precision float in the native format * n lua_Number * _ Separator * * feel free to add the mising modes. * <NAME> */ #include "ds.h" #include "lua.h" #ifndef LUA_REGISTRYINDEX #define lua_Number double #endif static void badmode(lua_State *L, int c) { char s[]="bad mode `?'"; s[sizeof(s)-3]=c; luaL_argerror(L,1,s); } static int copy(lua_State *L, void *a, size_t n, const char *s, int i, size_t len) { if (i+n>len) luaL_argerror(L,1,"input string too short"); memcpy(a,s+i,n); return i+n; } static int l_unpack(lua_State *L) /* unpack(s,f,[init]) */ { const char *s=luaL_checkstring(L,1); const char *f=luaL_checkstring(L,2); int i=luaL_optnumber(L,3,1)-1; size_t len=lua_strlen(L,1); int n; for (n=0; f[n]; n++) { int c=f[n]; switch (c) { case 'A': { size_t l; i=copy(L,&l,sizeof(l),s,i,len); if (i+l>len) luaL_argerror(L,1,"input string too short"); lua_pushlstring(L,s+i,l); i+=l; break; } case 'n': { lua_Number a; i=copy(L,&a,sizeof(a),s,i,len); lua_pushnumber(L,a); break; } case 'd': { double a; i=copy(L,&a,sizeof(a),s,i,len); lua_pushnumber(L,a); break; } case 'f': { float a; i=copy(L,&a,sizeof(a),s,i,len); lua_pushnumber(L,a); break; } case 'c': { char a; i=copy(L,&a,sizeof(a),s,i,len); lua_pushnumber(L,a); break; } case 'C': { unsigned char a; i=copy(L,&a,sizeof(a),s,i,len); lua_pushnumber(L,a); break; } case 's': { short a; i=copy(L,&a,sizeof(a),s,i,len); lua_pushnumber(L,a); break; } case 'S': { unsigned short a; i=copy(L,&a,sizeof(a),s,i,len); lua_pushnumber(L,a); break; } case 'i': { int a; i=copy(L,&a,sizeof(a),s,i,len); lua_pushnumber(L,a); break; } case 'I': { unsigned int a; i=copy(L,&a,sizeof(a),s,i,len); lua_pushnumber(L,a); break; } case 'l': { long a; i=copy(L,&a,sizeof(a),s,i,len); lua_pushnumber(L,a); break; } case 'L': { unsigned long a; i=copy(L,&a,sizeof(a),s,i,len); lua_pushnumber(L,a); break; } case '_': i+=1; break; default: badmode(L,c); break; } } lua_pushnumber(L,i+1); return n+1; } /* s string, d double, f float, i int, w short, b byte, c char */ static int l_pack(lua_State *L) /* pack(s,...) */ { int i,j; const char *s=luaL_checkstring(L,1); luaL_Buffer b; luaL_buffinit(L,&b); for (i=0, j=2; s[i]; i++, j++) { int c=s[i]; switch (c) { case 'A': { size_t l; const char *a=luaL_checklstring(L,j,&l); luaL_addlstring(&b,(void*)&l,sizeof(l)); luaL_addlstring(&b,a,l); break; } case 'n': { lua_Number a=luaL_checknumber(L,j); luaL_addlstring(&b,(void*)&a,sizeof(a)); break; } case 'd': { double a=luaL_checknumber(L,j); luaL_addlstring(&b,(void*)&a,sizeof(a)); break; } case 'f': { float a=luaL_checknumber(L,j); luaL_addlstring(&b,(void*)&a,sizeof(a)); break; } case 'c': { char a=luaL_checknumber(L,j); luaL_addlstring(&b,(void*)&a,sizeof(a)); break; } case 'C': { unsigned char a=luaL_checknumber(L,j); luaL_addlstring(&b,(void*)&a,sizeof(a)); break; } case 's': { short a=luaL_checknumber(L,j); luaL_addlstring(&b,(void*)&a,sizeof(a)); break; } case 'S': { unsigned short a=luaL_checknumber(L,j); luaL_addlstring(&b,(void*)&a,sizeof(a)); break; } case 'i': { int a=luaL_checknumber(L,j); luaL_addlstring(&b,(void*)&a,sizeof(a)); break; } case 'I': { unsigned int a=luaL_checknumber(L,j); luaL_addlstring(&b,(void*)&a,sizeof(a)); break; } case 'l': { long a=luaL_checknumber(L,j); luaL_addlstring(&b,(void*)&a,sizeof(a)); break; } case 'L': { unsigned long a=luaL_checknumber(L,j); luaL_addlstring(&b,(void*)&a,sizeof(a)); break; } case '_': { break; } default: badmode(L,c); break; } } luaL_pushresult(&b); return 1; } int lua_packlibopen(lua_State *L) { lua_register(L,"bpack",l_pack); lua_register(L,"bunpack",l_unpack); return 0; } <file_sep>/modules/luaTask/module.c /* DreamShell ##version## module.c - luaTask module Copyright (C)2011-2014 SWAT */ #include "ds.h" #include <kos/exports.h> DEFAULT_MODULE_HEADER(luaTask); int luaopen_task(lua_State *L); int lib_open(klibrary_t * lib) { luaopen_task(GetLuaState()); RegisterLuaLib(lib_get_name(), (LuaRegLibOpen *)luaopen_task); return nmmgr_handler_add(&ds_luaTask_hnd.nmmgr); } int lib_close(klibrary_t * lib) { UnregisterLuaLib(lib_get_name()); return nmmgr_handler_remove(&ds_luaTask_hnd.nmmgr); } <file_sep>/sdk/bin/src/mkbios/mkbios.c /** * mkbios.c * Copyright (c) 2022 SWAT */ #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <unistd.h> #define BIOS_OFFSET 65536 int main(int argc, char *argv[]) { if (argc < 3) { printf("BIOS maker v0.1 by SWAT\n"); printf("Usage: %s file.bios program.bin", argv[0]); return 0; } FILE *fr, *fw; fw = fopen(argv[1], "r+b"); if (!fw) { printf("Can't open for read: %s\n", argv[1]); return -1; } fr = fopen(argv[2], "r"); if (!fr) { printf("Can't open for read: %s\n", argv[2]); fclose(fw); return -1; } fseek(fr, 0L, SEEK_END); size_t size = ftell(fr); fseek(fr, 0L, SEEK_SET); uint8_t *buff = (uint8_t *) malloc(size); if (!buff) { printf("Malloc failed for %zu bytes\n", size); fclose(fr); fclose(fw); return -1; } printf("Writing to %s by offset %d size %zu\n", argv[1], BIOS_OFFSET, size); fread(buff, sizeof(char), size, fr); fclose(fr); fseek(fw, BIOS_OFFSET, SEEK_SET); fwrite(buff, sizeof(char), size, fw); fclose(fw); free(buff); return 0; } <file_sep>/firmware/isoldr/loader/dev/ide/ide.h /** * Copyright (c) 2014-2022 SWAT <http://www.dc-swat.ru> * Copyright (c) 2017 Megavolt85 * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef __IDE_H #define __IDE_H #include <sys/cdefs.h> __BEGIN_DECLS #include <arch/types.h> #include <dc/cdrom.h> typedef unsigned char u8; typedef unsigned short u16; typedef unsigned int u32; typedef unsigned long long u64; typedef char s8; typedef short s16; typedef int s32; typedef long long s64; // Directions: #define G1_READ_PIO 0 #define G1_WRITE_PIO 1 #define G1_READ_DMA 2 #define G1_WRITE_DMA 3 typedef struct pt_struct { u8 bootable; u8 start_part[3]; u8 type_part; u8 end_part[3]; u32 sect_before; u32 sect_total; } pt_t; typedef struct cdrom_info { CDROM_TOC tocs[2]; u8 disc_type; u8 sec_type; u8 inited; } cdri_t; typedef struct cd_sense { u8 sk; u8 asc; u8 ascq; } cd_sense_t; typedef struct ide_device { u8 reserved; // 0 (Empty) or 1 (This Drive really exists). u8 drive; // 0 (Master Drive) or 1 (Slave Drive). u8 type; // 0: ATA, 1: ATAPI, 2: SPI (Sega Packet Interface) u8 lba48; // 0: LBA28, 1: LBA48 u16 sign; // Drive Signature u16 capabilities; // Features. u32 command_sets; // Command Sets Supported. // s8 model[41]; // Model in string. u64 max_lba; u16 wdma_modes; #if defined(DEV_TYPE_IDE) && defined(DEBUG) pt_t pt[4]; u8 pt_num; #endif #ifdef DEV_TYPE_GD cdri_t cd_info; #endif } ide_device_t; s32 g1_bus_init(void); void g1_dma_set_irq_mask(s32 last_transfer); u32 g1_dma_has_irq_mask(); s32 g1_dma_init_irq(void); void g1_dma_irq_hide(s32 all); void g1_dma_irq_restore(void); void g1_dma_start(u32 addr, size_t bytes); void g1_dma_abort(void); u32 g1_dma_in_progress(void); u32 g1_dma_transfered(void); void g1_pio_reset(size_t total_bytes); void g1_pio_xfer(u32 addr, size_t bytes); void g1_pio_abort(void); u32 g1_pio_in_progress(void); u32 g1_pio_transfered(void); void g1_ata_xfer(u32 addr, size_t bytes); void g1_ata_abort(void); u32 g1_ata_in_progress(void); u32 g1_ata_transfered(void); void g1_ata_raise_interrupt(u64 sector); void cdrom_spin_down(u8 drive); s32 cdrom_get_status(s32 *status, u8 *disc_type, u8 drive); s32 cdrom_read_toc(CDROM_TOC *toc_buffer, u8 session, u8 drive); CDROM_TOC *cdrom_get_toc(u8 session, u8 drive); u32 cdrom_locate_data_track(CDROM_TOC *toc); void cdrom_set_sector_size(s32 sec_size, u8 drive); s32 cdrom_reinit(s32 sec_size, u8 drive); s32 cdrom_cdda_play(u32 start, u32 end, u32 loops, s32 mode); s32 cdrom_cdda_pause(); s32 cdrom_cdda_resume(); s32 cdrom_read_sectors(void *buffer, u32 sector, u32 cnt, u8 drive); s32 cdrom_read_sectors_ex(void *buffer, u32 sector, u32 cnt, u8 async, u8 dma, u8 drive); s32 cdrom_read_sectors_part(void *buffer, u32 sector, size_t offset, size_t bytes, u8 drive); s32 cdrom_pre_read_sectors(u32 sector, size_t bytes, u8 drive); s32 cdrom_chk_disc_change(u8 drive); u8 cdrom_get_dev_type(u8 drive); /** \brief DMA read disk sector part with Linear Block Addressing (LBA). This function reads partial disk block from the slave device on the G1 ATA bus using LBA mode (either 28 or 48 bits, as appropriate). \param sector The sector reading. \param bytes The number of bytes to read. \param buf Storage for the read-in disk sectors. This should be at least 32-byte aligned. \return 0 on success. < 0 on failure, setting errno as appropriate. */ s32 g1_ata_read_lba_dma_part(u64 sector, size_t bytes, u8 *buf); /** \brief Pre-read disk sector part with Linear Block Addressing (LBA). * * This function for pre-reading sectors from the slave device. **/ s32 g1_ata_pre_read_lba(u64 sector, size_t count); /** \brief Read one or more blocks from the ATA device. This function reads the specified number of blocks from the ATA device from the beginning block specified into the buffer passed in. It is your responsibility to allocate the buffer properly for the number of bytes that is to be read (512 * the number of blocks requested). \param block The starting block number to read from. \param count The number of 512 byte blocks of data to read. \param buf The buffer to read into. \param wait_dma Wait DMA complete \retval 0 On success. \retval -1 On error, errno will be set as appropriate. */ s32 g1_ata_read_blocks(u64 block, size_t count, u8 *buf, u8 wait_dma); /** \brief Write one or more blocks to the ATA device. This function writes the specified number of blocks to the ATA device at the beginning block specified from the buffer passed in. Each block is 512 bytes in length, and you must write at least one block at a time. You cannot write partial blocks. If this function returns an error, you have quite possibly corrupted something on the ATA device or have a damaged device in general (unless errno is ENXIO). \param block The starting block number to write to. \param count The number of 512 byte blocks of data to write. \param buf The buffer to write from. \param wait_dma Wait DMA complete \retval 0 On success. \retval -1 On error, errno will be set as appropriate. */ s32 g1_ata_write_blocks(u64 block, size_t count, const u8 *buf, u8 wait_dma); /** \brief Polling the ATA device. This function used for async reading. \return On succes, the transfered size. On error, -1. */ s32 g1_ata_poll(void); /** \brief Retrieve the size of the ATA device. \return On succes, max LBA error, (uint64)-1. */ u64 g1_ata_max_lba(void); /** \brief Flush the write cache on the attached disk. This function flushes the write cache on the disk attached as the slave device on the G1 ATA bus. This ensures that all writes that have previously completed are fully persisted to the disk. You should do this before unmounting any disks or exiting your program if you have called any of the write functions in here. \return 0 on success. <0 on error, setting errno as appropriate. */ s32 g1_ata_flush(void); /** \brief Ack IRQ of the ATA device. * */ s32 g1_ata_ack_irq(void); /** \brief Check for IRQ of the ATA device. * */ s32 g1_ata_has_irq(void); __END_DECLS #endif /* __IDE_H */ <file_sep>/include/audio/adx.h #ifndef ADX_H #define ADX_H #define ADX_CRI_SIZE 0x06 #define ADX_PAD_SIZE 0x0e #define ADX_HDR_SIZE 0x2c #define ADX_HDR_SIG 0x80 #define ADX_EXIT_SIG 0x8001 #define ADX_ADDR_START 0x02 #define ADX_ADDR_CHUNK 0x05 #define ADX_ADDR_CHAN 0x07 #define ADX_ADDR_RATE 0x08 #define ADX_ADDR_SAMP 0x0c #define ADX_ADDR_TYPE 0x12 #define ADX_ADDR_LOOP 0x18 #define ADX_ADDR_SAMP_START 0x1c #define ADX_ADDR_BYTE_START 0x20 #define ADX_ADDR_SAMP_END 0x24 #define ADX_ADDR_BYTE_END 0x28 typedef struct { int sample_offset; int chunk_size; int channels; int rate; int samples; int loop_type; int loop; int loop_start; int loop_end; int loop_samp_start; int loop_samp_end; int loop_samples; }ADX_INFO; typedef struct { int s1,s2; } PREV; /* LibADX Public Function Definitions */ /* Return 1 on success, 0 on failure */ /* Start Straming the ADX in a seperate thread */ int adx_dec( char * adx_file, int loop_enable ); /* Stop Streaming the ADX */ int adx_stop(); /* Restart Streaming the ADX */ int adx_restart(); /* Pause Streaming the ADX (if streaming) */ int adx_pause(); /* Resume Streaming the ADX (if paused) */ int adx_resume(); #endif <file_sep>/modules/ffmpeg/config.sh # # ffmpeg library config for DreamShell # Copyright (C)2011-2020 SWAT # http://www.dc-swat.ru # cd ./ffmpeg-0.6.3 ./configure \ --disable-debug --disable-network --disable-swscale \ --disable-ffmpeg --disable-ffplay --disable-ffprobe --disable-ffserver --disable-encoders --disable-avdevice \ --disable-protocols --disable-devices --disable-filters --disable-muxers --disable-bsfs --disable-hwaccels \ --disable-amd3dnow --disable-amd3dnowext --disable-mmx --disable-mmx2 --disable-sse --disable-ssse3 \ --disable-armv5te --disable-armv6 --disable-armv6t2 --disable-armvfp --disable-iwmmxt --disable-mmi \ --disable-neon --disable-vis --disable-yasm --disable-altivec --disable-golomb --disable-lpc \ --disable-vaapi --disable-vdpau --disable-dxva2 --disable-decoders --disable-demuxers \ \ --enable-gpl --prefix=../ --enable-cross-compile --cross-prefix=sh-elf- --arch=sh4 --target-os=gnu \ --extra-cflags="${KOS_CFLAGS} -I${KOS_BASE}/ds/include -I${KOS_BASE}/ds/include/zlib -I${KOS_BASE}/ds/sdk/include/freetype -I${KOS_BASE}/ds/modules/ogg/liboggvorbis/liboggvorbis/libvorbis/include -I${KOS_BASE}/ds/modules/ogg/liboggvorbis/liboggvorbis/libogg/include" \ --extra-ldflags="${KOS_LDFLAGS} -L${KOS_BASE}/ds/sdk/lib ${KOS_LIBS}" --enable-zlib --enable-bzlib --enable-libvorbis --enable-libxvid \ \ --enable-decoder=h264 --enable-decoder=mpeg2video --enable-decoder=mpeg4 --enable-decoder=msmpeg4v1 --enable-decoder=ape \ --enable-decoder=mpeg1video --enable-decoder=ac3 --enable-decoder=eac3 --enable-decoder=vp6 --enable-decoder=vp5 --enable-decoder=vp3 \ --enable-decoder=aac --enable-decoder=eac3 --enable-decoder=flac --enable-decoder=flic --enable-decoder=mjpeg --enable-decoder=mjpegb \ --enable-decoder=adpcm_4xm --enable-decoder=adpcm_adx --enable-decoder=mpegvideo --enable-decoder=theora --enable-decoder=dca \ --enable-decoder=flac --enable-decoder=h261 --enable-decoder=flv --enable-decoder=cinepak --enable-decoder=bink --enable-decoder=truehd \ --enable-decoder=msmpeg4v2 --enable-decoder=msmpeg4v3 --enable-decoder=h263 --enable-decoder=wmv1 --enable-decoder=wmv2 --enable-decoder=wmv3 \ --enable-decoder=pcm_s16be --enable-decoder=pcm_s16le --enable-decoder=pcm_u16be --enable-decoder=pcm_u16le \ \ --enable-demuxer=avi --enable-demuxer=ac3 --enable-demuxer=mp3 --enable-demuxer=mpegts --enable-demuxer=mpegvideo --enable-demuxer=matroska \ --enable-demuxer=h264 --enable-demuxer=asf --enable-demuxer=m4v --enable-demuxer=aac --enable-demuxer=mjpeg \ --enable-demuxer=h261 --enable-demuxer=pcm_u16le --enable-demuxer=pcm_s16be --enable-demuxer=pcm_s16le --enable-demuxer=pcm_u16be \ --enable-demuxer=eac3 --enable-demuxer=ape --enable-demuxer=aiff --enable-demuxer=asf --enable-demuxer=ogg \ --enable-demuxer=voc --enable-demuxer=eac3 --enable-demuxer=rm --enable-demuxer=avisynth \ --enable-demuxer=flac --enable-demuxer=flic --enable-decoder=dts --enable-demuxer=h263 --enable-demuxer=flv \ --enable-demuxer=dv --enable-demuxer=truehd --enable-demuxer=vc1 --enable-demuxer=bink --enable-demuxer=nc # --enable-small --ar=kos-ar --as=kos-as --cc=kos-cc --ld=kos-ld \ # --enable-decoder=adpcm_ms --enable-demuxer=pcm_u32le --enable-demuxer=pcm_f32le --enable-demuxer=pcm_s24be --enable-demuxer=pcm_s24le # --enable-decoder=pcm_f32be --enable-decoder=pcm_f32le --enable-decoder=pcm_s24le --enable-decoder=pcm_s32be --enable-decoder=pcm_s32le # --enable-decoder=pcm_s24be --enable-decoder=pcm_u24be --enable-decoder=pcm_u24le --enable-decoder=pcm_u32be --enable-decoder=pcm_u32le # --enable-demuxer=pcm_u24be --enable-demuxer=pcm_u24le --enable-demuxer=pcm_u32be --enable-demuxer=pcm_s32be --enable-demuxer=pcm_s32le # --enable-demuxer=pcm_f32be # --disable-mdct --disable-rdft --disable-fft --enable-decoder=mp3 --enable-decoder=mp2 --enable-decoder=mp1 --enable-decoder=vorbis # <file_sep>/firmware/aica/codec/keys.h #ifndef _KEYS_H_ #define _KEYS_H_ void process_keys(void); long get_key_press( long key_mask ); long get_key_rpt( long key_mask ); long get_key_short( long key_mask ); long get_key_long( long key_mask ); void key_init( void ); #define KEY0 19 #define KEY1 20 #endif /* _KEYS_H_ */ <file_sep>/modules/bflash/devices.c /* DreamShell ##version## devices.c (c)2009-2014 SWAT http://www.dc-swat.ru */ #include <assert.h> #include <stdio.h> #include "ds.h" #include "drivers/bflash.h" #include "flash_if.h" const bflash_manufacturer_t bflash_manufacturers[] = { { "AMD", 0x0001 }, { "STMicroelectronics", 0x0020 }, { "Macronix", 0x00C2 }, { "AMIC", 0x0037 }, { "ESMT", 0x008C }, { "Sega", 0x00FF }, { "Unknown", 0x0000 } }; static uint32 sectors_29_800_t[] = { 0x00000, 0x10000, 0x20000, 0x30000, 0x40000, 0x50000, 0x60000, 0x70000, 0x80000, 0x90000, 0xA0000, 0xB0000, 0xC0000, 0xD0000, 0xE0000, 0xF0000, 0xF8000, 0xFA000, 0xFC000 }; static uint32 sectors_29_800_b[] = { 0x00000, 0x04000, 0x06000, 0x08000, 0x10000, 0x20000, 0x30000, 0x40000, 0x50000, 0x60000, 0x70000, 0x80000, 0x90000, 0xA0000, 0xB0000, 0xC0000, 0xD0000, 0xE0000, 0xF0000 }; static uint32 sectors_29_160_t[] = { 0x000000, 0x010000, 0x020000, 0x030000, 0x040000, 0x050000, 0x060000, 0x070000, 0x080000, 0x090000, 0x0A0000, 0x0B0000, 0x0C0000, 0x0D0000, 0x0E0000, 0x0F0000, 0x100000, 0x110000, 0x120000, 0x130000, 0x140000, 0x150000, 0x160000, 0x170000, 0x180000, 0x190000, 0x1A0000, 0x1B0000, 0x1C0000, 0x1D0000, 0x1E0000, 0x1F0000, 0x1F8000, 0x1FA000, 0x1FC000 }; static uint32 sectors_29_160_b[] = { 0x000000, 0x004000, 0x006000, 0x008000, 0x010000, 0x020000, 0x030000, 0x040000, 0x050000, 0x060000, 0x070000, 0x080000, 0x090000, 0x0A0000, 0x0B0000, 0x0C0000, 0x0D0000, 0x0E0000, 0x0F0000, 0x100000, 0x110000, 0x120000, 0x130000, 0x140000, 0x150000, 0x160000, 0x170000, 0x180000, 0x190000, 0x1A0000, 0x1B0000, 0x1C0000, 0x1D0000, 0x1E0000, 0x1F0000 }; /* Command unlock addrs */ #define CMD_UNLOCK_BM {ADDR_UNLOCK_1_BM, ADDR_UNLOCK_2_BM} #define CMD_UNLOCK_WM {ADDR_UNLOCK_1_WM, ADDR_UNLOCK_2_WM} #define CMD_UNLOCK_JEDEC {ADDR_UNLOCK_1_JEDEC, ADDR_UNLOCK_2_JEDEC} /* Short flags */ #define FB_RD F_FLASH_READ #define FB_PR F_FLASH_PROGRAM #define FB_ER F_FLASH_ERASE_SECTOR | F_FLASH_ERASE_ALL | F_FLASH_ERASE_SUSPEND #define FB_3V F_FLASH_LOGIC_3V #define FB_5V F_FLASH_LOGIC_5V const bflash_dev_t bflash_devs[] = { /* STMicroelectronics */ { "M29W800T", 0x20D7, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 1024, 1, 20, sectors_29_800_t,F_FLASH_DATAPOLLING_PM}, { "M29W800B", 0x205B, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 1024, 1, 20, sectors_29_800_b,F_FLASH_DATAPOLLING_PM}, { "M29W160BT", 0x20C4, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 2048, 1, 35, sectors_29_160_t,F_FLASH_DATAPOLLING_PM}, { "M29W160BB", 0x2049, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 2048, 1, 35, sectors_29_160_b,F_FLASH_DATAPOLLING_PM}, /* AMD */ { "Am29LV800T", 0x01DA, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 1024, 1, 20, sectors_29_800_t,F_FLASH_DATAPOLLING_PM}, { "Am29LV800B", 0x015B, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 1024, 1, 20, sectors_29_800_b,F_FLASH_DATAPOLLING_PM}, { "Am29LV160DT", 0x01C4, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 2048, 1, 35, sectors_29_160_t,F_FLASH_DATAPOLLING_PM}, { "Am29LV160DB", 0x0149, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 2048, 1, 35, sectors_29_160_b,F_FLASH_DATAPOLLING_PM}, { "Am29F160DT", 0x01D2, (FB_RD | FB_PR | FB_ER | FB_5V), CMD_UNLOCK_BM, 2048, 1, 35, sectors_29_160_t,F_FLASH_DATAPOLLING_PM}, { "Am29F160DB", 0x01D8, (FB_RD | FB_PR | FB_ER | FB_5V), CMD_UNLOCK_BM, 2048, 1, 35, sectors_29_160_b,F_FLASH_DATAPOLLING_PM}, /* Macronix */ { "MX29LV160T", 0xC2C4, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 2048, 1, 35, sectors_29_160_t,F_FLASH_DATAPOLLING_PM}, { "MX29LV160B", 0xC249, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 2048, 1, 35, sectors_29_160_b,F_FLASH_DATAPOLLING_PM}, { "MX29F1610", 0xC2F1, (FB_RD | FB_PR | FB_ER | FB_5V), CMD_UNLOCK_JEDEC, 2048, 128, 16, (uint32 []) { 0x000000, 0x020000, 0x040000, 0x060000, 0x080000, 0x0A0000, 0x0C0000, 0x0E0000, 0x100000, 0x120000, 0x140000, 0x160000, 0x180000, 0x1A0000, 0x1C0000, 0x1E0000 },F_FLASH_REGPOLLING_PM}, { "MX29F1610A", 0xC2FA, (FB_RD | FB_PR | FB_ER | FB_5V), CMD_UNLOCK_JEDEC, 2048, 128, 16, (uint32 []) { 0x000000, 0x020000, 0x040000, 0x060000, 0x080000, 0x0A0000, 0x0C0000, 0x0E0000, 0x100000, 0x120000, 0x140000, 0x160000, 0x180000, 0x1A0000, 0x1C0000, 0x1E0000 },F_FLASH_REGPOLLING_PM}, { "MX29F016", 0xC2AD, (FB_RD | FB_PR | FB_ER | FB_5V), CMD_UNLOCK_WM, 2048, 1, 32, (uint32 []) { 0x000000, 0x010000, 0x020000, 0x030000, 0x040000, 0x050000, 0x060000, 0x070000, 0x080000, 0x090000, 0x0A0000, 0x0B0000, 0x0C0000, 0x0D0000, 0x0E0000, 0x0F0000, 0x100000, 0x110000, 0x120000, 0x130000, 0x140000, 0x150000, 0x160000, 0x170000, 0x180000, 0x190000, 0x1A0000, 0x1B0000, 0x1C0000, 0x1D0000, 0x1E0000, 0x1F0000 },F_FLASH_DATAPOLLING_PM}, { "MX29F400", 0xC299, (FB_RD | FB_PR | FB_ER | FB_5V), CMD_UNLOCK_BM, 512, 1, 8, (uint32 []) { 0x000000, 0x010000, 0x020000, 0x030000, 0x040000, 0x050000, 0x060000, 0x070000 },F_FLASH_DATAPOLLING_PM}, { "MX29LV320T", 0xC2A7, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 4096, 1, 24, (uint32 []) { 0x000000, 0x010000, 0x020000, 0x030000, 0x040000, 0x050000, 0x060000, 0x070000, 0x080000, 0x090000, 0x0A0000, 0x0B0000, 0x0C0000, 0x0D0000, 0x0E0000, 0x0F0000, 0x100000, 0x110000, 0x120000, 0x130000, 0x140000, 0x150000, 0x160000, 0x170000, 0x180000, 0x190000, 0x1A0000, 0x1B0000, 0x1C0000, 0x1D0000, 0x1E0000, 0x1F0000, 0x200000, 0x210000, 0x220000, 0x230000, 0x240000, 0x250000, 0x260000, 0x270000, 0x280000, 0x290000, 0x2A0000, 0x2B0000, 0x2C0000, 0x2D0000, 0x2E0000, 0x2F0000, 0x300000, 0x310000, 0x320000, 0x330000, 0x340000, 0x350000, 0x360000, 0x370000, 0x380000, 0x390000, 0x3A0000, 0x3B0000, 0x3C0000, 0x3D0000, 0x3E0000, 0x3F0000, 0x3F2000, 0x3F4000, 0x3F6000, 0x3F8000, 0x3FA000, 0x3FC000, 0x3FE000 },F_FLASH_DATAPOLLING_PM}, { "MX29LV320B", 0xC2A8, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 4096, 1, 24, (uint32 []) { 0x000000, 0x002000, 0x004000, 0x006000, 0x008000, 0x00A000, 0x00C000, 0x00E000, 0x010000, 0x020000, 0x030000, 0x040000, 0x050000, 0x060000, 0x070000, 0x080000, 0x090000, 0x0A0000, 0x0B0000, 0x0C0000, 0x0D0000, 0x0E0000, 0x0F0000, 0x100000, 0x110000, 0x120000, 0x130000, 0x140000, 0x150000, 0x160000, 0x170000, 0x180000, 0x190000, 0x1A0000, 0x1B0000, 0x1C0000, 0x1D0000, 0x1E0000, 0x1F0000, 0x200000, 0x210000, 0x220000, 0x230000, 0x240000, 0x250000, 0x260000, 0x270000, 0x280000, 0x290000, 0x2A0000, 0x2B0000, 0x2C0000, 0x2D0000, 0x2E0000, 0x2F0000, 0x300000, 0x310000, 0x320000, 0x330000, 0x340000, 0x350000, 0x360000, 0x370000, 0x380000, 0x390000, 0x3A0000, 0x3B0000, 0x3C0000, 0x3D0000, 0x3E0000, 0x3F0000 },F_FLASH_DATAPOLLING_PM}, { "MX29L3211", 0xC2F9, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_JEDEC, 4096, 256, 32, (uint32 []) { 0x000000, 0x020000, 0x040000, 0x060000, 0x080000, 0x0A0000, 0x0C0000, 0x0E0000, 0x100000, 0x120000, 0x140000, 0x160000, 0x180000, 0x1A0000, 0x1C0000, 0x1E0000, 0x200000, 0x220000, 0x240000, 0x260000, 0x280000, 0x2A0000, 0x2C0000, 0x2E0000, 0x300000, 0x320000, 0x340000, 0x360000, 0x380000, 0x3A0000, 0x3C0000, 0x3E0000 },F_FLASH_REGPOLLING_PM}, /* AMIC */ { "A29L160AT", 0x37C4, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 2048, 1, 35, sectors_29_160_t,F_FLASH_DATAPOLLING_PM}, { "A29L160AB", 0x3749, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 2048, 1, 35, sectors_29_160_b,F_FLASH_DATAPOLLING_PM}, /* ESMT */ { "F49L160UA", 0x8CC4, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 2048, 1, 35, sectors_29_160_t,F_FLASH_DATAPOLLING_PM}, { "F49L160BA", 0x8C49, (FB_RD | FB_PR | FB_ER | FB_3V), CMD_UNLOCK_BM, 2048, 1, 35, sectors_29_160_b,F_FLASH_DATAPOLLING_PM}, /* Sega */ { "MPR-XXXXX", SEGA_FLASH_DEVICE_ID, (FB_RD | FB_3V | FB_5V), CMD_UNLOCK_BM, 2048, 1, 1, (uint32 []) { 0 },F_FLASH_UNKNOWN_PM}, /* Default entry */ { "Unknown", 0x0000, 0, {0, 0}, 0, 0, 0, (uint32 []) { 0 },F_FLASH_UNKNOWN_PM} }; <file_sep>/modules/mp3/libmp3/xingmp3/isbt.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** isbt.c *************************************************** MPEG audio decoder, dct and window portable C integer version of csbt.c mods 11/15/95 for Layer I mods 1/7/97 warnings ******************************************************************/ #include <float.h> #include <math.h> #include "itype.h" #ifdef _MSC_VER #pragma warning(disable: 4244) #pragma warning(disable: 4056) #endif /* asm is quick only, c code does not need separate window for right */ /* full is opposite of quick */ #ifdef FULL_INTEGER #define i_window_dual_right i_window_dual #define i_window16_dual_right i_window16_dual #define i_window8_dual_right i_window8_dual #endif void i_dct32(SAMPLEINT * sample, WININT * vbuf); void i_dct32_dual(SAMPLEINT * sample, WININT * vbuf); void i_dct32_dual_mono(SAMPLEINT * sample, WININT * vbuf); void i_dct16(SAMPLEINT * sample, WININT * vbuf); void i_dct16_dual(SAMPLEINT * sample, WININT * vbuf); void i_dct16_dual_mono(SAMPLEINT * sample, WININT * vbuf); void i_dct8(SAMPLEINT * sample, WININT * vbuf); void i_dct8_dual(SAMPLEINT * sample, WININT * vbuf); void i_dct8_dual_mono(SAMPLEINT * sample, WININT * vbuf); void i_window(WININT * vbuf, int vb_ptr, short *pcm); void i_window_dual(WININT * vbuf, int vb_ptr, short *pcm); void i_window_dual_right(WININT * vbuf, int vb_ptr, short *pcm); void i_window16(WININT * vbuf, int vb_ptr, short *pcm); void i_window16_dual(WININT * vbuf, int vb_ptr, short *pcm); void i_window16_dual_right(WININT * vbuf, int vb_ptr, short *pcm); void i_window8(WININT * vbuf, int vb_ptr, short *pcm); void i_window8_dual(WININT * vbuf, int vb_ptr, short *pcm); void i_window8_dual_right(WININT * vbuf, int vb_ptr, short *pcm); /*--------------------------------------------------------------------*/ /*-- floating point window coefs ---*/ /*-- for integer-quick window, table used to generate integer coefs --*/ static float wincoef[264] = { #include "tableawd.h" }; /* circular window buffers */ /* extern windows because of asm */ static signed int vb_ptr; // static WININT vbuf[512]; //static WININT vbuf2[512]; extern WININT vbuf[512]; extern WININT vbuf2[512]; DCTCOEF *i_dct_coef_addr(); /*======================================================================*/ static void gencoef() /* gen coef for N=32 */ { int p, n, i, k; double t, pi; DCTCOEF *coef32; coef32 = i_dct_coef_addr(); pi = 4.0 * atan(1.0); n = 16; k = 0; for (i = 0; i < 5; i++, n = n / 2) { for (p = 0; p < n; p++, k++) { t = (pi / (4 * n)) * (2 * p + 1); coef32[k] = (1 << DCTBITS) * (0.50 / cos(t)) + 0.5; } } } /*------------------------------------------------------------*/ WINCOEF *i_wincoef_addr(); static void genwincoef_q() /* gen int window coefs from floating table */ { int i, j, k, m; float x; WINCOEF *iwincoef; iwincoef = i_wincoef_addr(); /*--- coefs generated inline for quick window ---*/ /*-- quick uses only 116 coefs --*/ k = 0; m = 0; for (i = 0; i < 16; i++) { k += 5; for (j = 0; j < 7; j++) { x = (1 << WINBITS) * wincoef[k++]; if (x > 0.0) x += 0.5; else x -= 0.5; iwincoef[m++] = x; } k += 4; } k++; for (j = 0; j < 4; j++) { x = (1 << WINBITS) * wincoef[k++]; if (x > 0.0) x += 0.5; else x -= 0.5; iwincoef[m++] = x; } } /*------------------------------------------------------------*/ static void genwincoef() /* gen int window coefs from floating table */ { int i; float x; WINCOEF *iwincoef; WINCOEF *i_wincoef_addr(); iwincoef = i_wincoef_addr(); for (i = 0; i < 264; i++) { x = (1 << WINBITS) * wincoef[i]; if (x > 0.0) x += 0.5; else x -= 0.5; iwincoef[i] = x; } } /*------------------------------------------------------------*/ void i_sbt_init() { int i; static int first_pass = 1; #ifdef FULL_INTEGER static int full_integer = 1; #else static int full_integer = 0; #endif if (first_pass) { gencoef(); if (full_integer) genwincoef(); else genwincoef_q(); first_pass = 0; } /* clear window vbuf */ for (i = 0; i < 512; i++) vbuf[i] = vbuf2[i] = 0; vb_ptr = 0; } /*==============================================================*/ /*==============================================================*/ /*==============================================================*/ void i_sbt_mono(SAMPLEINT * sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct32(sample, vbuf + vb_ptr); i_window(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ void i_sbt_dual(SAMPLEINT * sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct32_dual(sample, vbuf + vb_ptr); i_dct32_dual(sample + 1, vbuf2 + vb_ptr); i_window_dual(vbuf, vb_ptr, pcm); i_window_dual_right(vbuf2, vb_ptr, pcm + 1); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 64; } } /*------------------------------------------------------------*/ /* convert dual to mono */ void i_sbt_dual_mono(SAMPLEINT * sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct32_dual_mono(sample, vbuf + vb_ptr); i_window(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /* convert dual to left */ void i_sbt_dual_left(SAMPLEINT * sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct32_dual(sample, vbuf + vb_ptr); i_window(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /* convert dual to right */ void i_sbt_dual_right(SAMPLEINT * sample, short *pcm, int n) { int i; sample++; /* point to right chan */ for (i = 0; i < n; i++) { i_dct32_dual(sample, vbuf + vb_ptr); i_window(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /*---------------- 16 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ void i_sbt16_mono(SAMPLEINT * sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct16(sample, vbuf + vb_ptr); i_window16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void i_sbt16_dual(SAMPLEINT * sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct16_dual(sample, vbuf + vb_ptr); i_dct16_dual(sample + 1, vbuf2 + vb_ptr); i_window16_dual(vbuf, vb_ptr, pcm); i_window16_dual_right(vbuf2, vb_ptr, pcm + 1); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 32; } } /*------------------------------------------------------------*/ void i_sbt16_dual_mono(SAMPLEINT * sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct16_dual_mono(sample, vbuf + vb_ptr); i_window16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void i_sbt16_dual_left(SAMPLEINT * sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct16_dual(sample, vbuf + vb_ptr); i_window16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void i_sbt16_dual_right(SAMPLEINT * sample, short *pcm, int n) { int i; sample++; for (i = 0; i < n; i++) { i_dct16_dual(sample, vbuf + vb_ptr); i_window16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ /*---------------- 8 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ void i_sbt8_mono(SAMPLEINT * sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct8(sample, vbuf + vb_ptr); i_window8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void i_sbt8_dual(SAMPLEINT * sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct8_dual(sample, vbuf + vb_ptr); i_dct8_dual(sample + 1, vbuf2 + vb_ptr); i_window8_dual(vbuf, vb_ptr, pcm); i_window8_dual_right(vbuf2, vb_ptr, pcm + 1); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 16; } } /*------------------------------------------------------------*/ void i_sbt8_dual_mono(SAMPLEINT * sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct8_dual_mono(sample, vbuf + vb_ptr); i_window8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void i_sbt8_dual_left(SAMPLEINT * sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct8_dual(sample, vbuf + vb_ptr); i_window8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void i_sbt8_dual_right(SAMPLEINT * sample, short *pcm, int n) { int i; sample++; for (i = 0; i < n; i++) { i_dct8_dual(sample, vbuf + vb_ptr); i_window8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ /*--- 8 bit output ----------------*/ #include "isbtb.c" /*----------------------------------*/ #ifdef _MSC_VER #pragma warning(default: 4244) #pragma warning(default: 4056) #endif <file_sep>/firmware/isoldr/loader/gdb.c /* sh-stub.c -- debugging stub for the Hitachi-SH. NOTE!! This code has to be compiled with optimization, otherwise the function inlining which generates the exception handlers won't work. */ /* This is originally based on an m68k software stub written by <NAME> at HP, but has changed quite a bit. Modifications for the SH by <NAME> and <NAME> Modifications for KOS by <NAME> (earlier) and <NAME> (more recently). Modifications for ISO Loader by SWAT (2014-2016) */ /**************************************************************************** THIS SOFTWARE IS NOT COPYRIGHTED HP offers the following for use in the public domain. HP makes no warranty with regard to the software or it's performance and the user accepts the software "AS IS" with all faults. HP DISCLAIMS ANY WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD TO THIS SOFTWARE INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ****************************************************************************/ /* Remote communication protocol. A debug packet whose contents are <data> is encapsulated for transmission in the form: $ <data> # CSUM1 CSUM2 <data> must be ASCII alphanumeric and cannot include characters '$' or '#'. If <data> starts with two characters followed by ':', then the existing stubs interpret this as a sequence number. CSUM1 and CSUM2 are ascii hex representation of an 8-bit checksum of <data>, the most significant nibble is sent first. the hex digits 0-9,a-f are used. Receiver responds with: + - if CSUM is correct and ready for next packet - - if CSUM is incorrect <data> is as follows: All values are encoded in ascii hex digits. Request Packet read registers g reply XX....X Each byte of register data is described by two hex digits. Registers are in the internal order for GDB, and the bytes in a register are in the same order the machine uses. or ENN for an error. write regs GXX..XX Each byte of register data is described by two hex digits. reply OK for success ENN for an error write reg Pn...=r... Write register n... with value r..., which contains two hex digits for each byte in the register (target byte order). reply OK for success ENN for an error (not supported by all stubs). read mem mAA..AA,LLLL AA..AA is address, LLLL is length. reply XX..XX XX..XX is mem contents Can be fewer bytes than requested if able to read only part of the data. or ENN NN is errno write mem MAA..AA,LLLL:XX..XX AA..AA is address, LLLL is number of bytes, XX..XX is data reply OK for success ENN for an error (this includes the case where only part of the data was written). cont cAA..AA AA..AA is address to resume If AA..AA is omitted, resume at same address. step sAA..AA AA..AA is address to resume If AA..AA is omitted, resume at same address. last signal ? Reply the current reason for stopping. This is the same reply as is generated for step or cont : SAA where AA is the signal number. There is no immediate reply to step or cont. The reply comes when the machine stops. It is SAA AA is the "signal number" or... TAAn...:r...;n:r...;n...:r...; AA = signal number n... = register number r... = register contents or... WAA The process exited, and AA is the exit status. This is only applicable for certains sorts of targets. kill request k toggle debug d toggle debug flag (see 386 & 68k stubs) reset r reset -- see sparc stub. reserved <other> On other requests, the stub should ignore the request and send an empty response ($#<checksum>). This way we can extend the protocol and GDB can tell whether the stub it is talking to uses the old or the new. search tAA:PP,MM Search backwards starting at address AA for a match with pattern PP and mask MM. PP and MM are 4 bytes. Not supported by all stubs. general query qXXXX Request info about XXXX. general set QXXXX=yyyy Set value of XXXX to yyyy. query sect offs qOffsets Get section offsets. Reply is Text=xxx;Data=yyy;Bss=zzz console output Otext Send text to stdout. Only comes from remote target. Responses can be run-length encoded to save space. A '*' means that the next character is an ASCII encoding giving a repeat count which stands for that many repititions of the character preceding the '*'. The encoding is n+29, yielding a printable character where n >=3 (which is where rle starts to win). Don't use an n > 126. So "0* " means the same as "0000". */ #include <arch/types.h> #include <dc/scif.h> #include <arch/gdb.h> #include <arch/irq.h> #include <arch/cache.h> #include <exception.h> #include <string.h> /* Hitachi SH architecture instruction encoding masks */ #define COND_BR_MASK 0xff00 #define UCOND_DBR_MASK 0xe000 #define UCOND_RBR_MASK 0xf0df #define TRAPA_MASK 0xff00 #define COND_DISP 0x00ff #define UCOND_DISP 0x0fff #define UCOND_REG 0x0f00 /* Hitachi SH instruction opcodes */ #define BF_INSTR 0x8b00 #define BFS_INSTR 0x8f00 #define BT_INSTR 0x8900 #define BTS_INSTR 0x8d00 #define BRA_INSTR 0xa000 #define BSR_INSTR 0xb000 #define JMP_INSTR 0x402b #define JSR_INSTR 0x400b #define RTS_INSTR 0x000b #define RTE_INSTR 0x002b #define TRAPA_INSTR 0xc300 #define SSTEP_INSTR 0xc320 /* Hitachi SH processor register masks */ #define T_BIT_MASK 0x0001 /* * BUFMAX defines the maximum number of characters in inbound/outbound * buffers. At least NUMREGBYTES*2 are needed for register packets. */ //#define BUFMAX 1024 #define BUFMAX 512 /* * Number of bytes for registers */ //#define NUMREGBYTES 41*4 #define NUMREGBYTES 33*4 /* * Modes for packet dcload packet transmission */ #define DCL_SEND 0x1 #define DCL_RECV 0x2 #define DCL_SENDRECV 0x3 /* * typedef */ typedef void (*Function)(); /* * Forward declarations */ static int hex(char); static char *mem2hex(char *, char *, uint32); static char *hex2mem(char *, char *, uint32); static int hexToInt(char **, uint32 *); static unsigned char *getpacket(void); static void putpacket(char *); static int computeSignal(int exceptionVector); static void hardBreakpoint(int, int, uint32, int, char*); static void putDebugChar(char); static char getDebugChar(void); //static void flushDebugChannel(void); void gdb_breakpoint(void); static int dofault; /* Non zero, bus errors will raise exception */ /* debug > 0 prints ill-formed commands in valid packets & checksum errors */ static int remote_debug; //enum regnames { // R0, R1, R2, R3, R4, R5, R6, R7, // R8, R9, R10, R11, R12, R13, R14, R15, // PC, PR, GBR, VBR, MACH, MACL, SR, // FPUL, FPSCR, // FR0, FR1, FR2, FR3, FR4, FR5, FR6, FR7, // FR8, FR9, FR10, FR11, FR12, FR13, FR14, FR15 //}; /* map from KOS register context order to GDB sh4 order */ //#define KOS_REG( r ) ( ((uint32)&((irq_context_t*)0)->r) / sizeof(uint32) ) // //static uint32 kosRegMap[] = { // KOS_REG(r[0]), KOS_REG(r[1]), KOS_REG(r[2]), KOS_REG(r[3]), // KOS_REG(r[4]), KOS_REG(r[5]), KOS_REG(r[6]), KOS_REG(r[7]), // KOS_REG(r[8]), KOS_REG(r[9]), KOS_REG(r[10]), KOS_REG(r[11]), // KOS_REG(r[12]), KOS_REG(r[13]), KOS_REG(r[14]), KOS_REG(r[15]), // // KOS_REG(pc), KOS_REG(pr), KOS_REG(gbr), KOS_REG(vbr), // KOS_REG(mach), KOS_REG(macl), KOS_REG(sr), // KOS_REG(fpul), KOS_REG(fpscr), // // KOS_REG(fr[0]), KOS_REG(fr[1]), KOS_REG(fr[2]), KOS_REG(fr[3]), // KOS_REG(fr[4]), KOS_REG(fr[5]), KOS_REG(fr[6]), KOS_REG(fr[7]), // KOS_REG(fr[8]), KOS_REG(fr[9]), KOS_REG(fr[10]), KOS_REG(fr[11]), // KOS_REG(fr[12]), KOS_REG(fr[13]), KOS_REG(fr[14]), KOS_REG(fr[15]) //}; // static void arch_reboot() { typedef void (*reboot_func)() __noreturn; reboot_func rb; /* Ensure that interrupts are disabled */ irq_disable(); /* Reboot */ rb = (reboot_func)0xa0000000; rb(); } enum regnames { PR, MACH, MACL, PC, SSR, VBR, GBR, SR, DBR, R7_BANK, R6_BANK, R5_BANK, R4_BANK, R3_BANK, R2_BANK, R1_BANK, R0_BANK, R14, R13, R12, R11, R10, R9, R8, R7, R6, R5, R4, R3, R2, R1, EXC_TYPE, R0 }; #define KOS_REG( r ) ( ((uint32)&((register_stack*)0)->r) / sizeof(uint32) ) static uint32 kosRegMap[] = { KOS_REG(pr), KOS_REG(mach), KOS_REG(macl), KOS_REG(spc), KOS_REG(ssr), KOS_REG(vbr), KOS_REG(gbr), KOS_REG(sr), KOS_REG(dbr), KOS_REG(r7_bank), KOS_REG(r6_bank), KOS_REG(r5_bank), KOS_REG(r4_bank), KOS_REG(r3_bank), KOS_REG(r2_bank), KOS_REG(r1_bank), KOS_REG(r0_bank), KOS_REG(r14), KOS_REG(r13), KOS_REG(r12), KOS_REG(r11), KOS_REG(r10), KOS_REG(r9), KOS_REG(r8), KOS_REG(r7), KOS_REG(r6), KOS_REG(r5), KOS_REG(r4), KOS_REG(r3), KOS_REG(r2), KOS_REG(r1), KOS_REG(exception_type), KOS_REG(r0) }; #undef KOS_REG typedef struct { short *memAddr; short oldInstr; } stepData; static uint32 *registers; static stepData instrBuffer; static char stepped; static const char hexchars[] = "0123456789abcdef"; static char remcomInBuffer[BUFMAX], remcomOutBuffer[BUFMAX]; //static char in_dcl_buf[BUFMAX], out_dcl_buf[BUFMAX]; //static int using_dcl = 0, in_dcl_pos = 0, out_dcl_pos = 0, in_dcl_size = 0; static char highhex(int x) { return hexchars[(x >> 4) & 0xf]; } static char lowhex(int x) { return hexchars[x & 0xf]; } /* * Assembly macros */ #define BREAKPOINT() __asm__("trapa #0xff"::); /* * Routines to handle hex data */ static int hex(char ch) { if((ch >= 'a') && (ch <= 'f')) return (ch - 'a' + 10); if((ch >= '0') && (ch <= '9')) return (ch - '0'); if((ch >= 'A') && (ch <= 'F')) return (ch - 'A' + 10); return (-1); } /* convert the memory, pointed to by mem into hex, placing result in buf */ /* return a pointer to the last char put in buf (null) */ static char * mem2hex(char *mem, char *buf, uint32 count) { uint32 i; int ch; for(i = 0; i < count; i++) { ch = *mem++; *buf++ = highhex(ch); *buf++ = lowhex(ch); } *buf = 0; return (buf); } /* convert the hex array pointed to by buf into binary, to be placed in mem */ /* return a pointer to the character after the last byte written */ static char * hex2mem(char *buf, char *mem, uint32 count) { uint32 i; unsigned char ch; for(i = 0; i < count; i++) { ch = hex(*buf++) << 4; ch = ch + hex(*buf++); *mem++ = ch; } return (mem); } /**********************************************/ /* WHILE WE FIND NICE HEX CHARS, BUILD AN INT */ /* RETURN NUMBER OF CHARS PROCESSED */ /**********************************************/ static int hexToInt(char **ptr, uint32 *intValue) { int numChars = 0; int hexValue; *intValue = 0; while(**ptr) { hexValue = hex(**ptr); if(hexValue >= 0) { *intValue = (*intValue << 4) | hexValue; numChars++; } else break; (*ptr)++; } return (numChars); } /* * Routines to get and put packets */ /* scan for the sequence $<data>#<checksum> */ static unsigned char * getpacket(void) { unsigned char *buffer = (unsigned char *)(&remcomInBuffer[0]); unsigned char checksum; unsigned char xmitcsum; int count; char ch; while(1) { /* wait around for the start character, ignore all other characters */ while((ch = getDebugChar()) != '$') ; retry: checksum = 0; xmitcsum = -1; count = 0; /* now, read until a # or end of buffer is found */ while(count < BUFMAX) { ch = getDebugChar(); if(ch == '$') goto retry; if(ch == '#') break; checksum = checksum + ch; buffer[count] = ch; count = count + 1; } buffer[count] = 0; if(ch == '#') { ch = getDebugChar(); xmitcsum = hex(ch) << 4; ch = getDebugChar(); xmitcsum += hex(ch); if(checksum != xmitcsum) { putDebugChar('-'); /* failed checksum */ } else { putDebugChar('+'); /* successful transfer */ // printf("get_packet() -> %s\n", buffer); /* if a sequence char is present, reply the sequence ID */ if(buffer[2] == ':') { putDebugChar(buffer[0]); putDebugChar(buffer[1]); return &buffer[3]; } return &buffer[0]; } } } } /* send the packet in buffer. */ static void putpacket(register char *buffer) { register int checksum; /* $<packet info>#<checksum>. */ // printf("put_packet() <- %s\n", buffer); do { char *src = buffer; putDebugChar('$'); checksum = 0; while(*src) { int runlen; /* Do run length encoding */ for(runlen = 0; runlen < 100; runlen ++) { if(src[0] != src[runlen] || runlen == 99) { if(runlen > 3) { int encode; /* Got a useful amount */ putDebugChar(*src); checksum += *src; putDebugChar('*'); checksum += '*'; checksum += (encode = runlen + ' ' - 4); putDebugChar(encode); src += runlen; } else { putDebugChar(*src); checksum += *src; src++; } break; } } } putDebugChar('#'); putDebugChar(highhex(checksum)); putDebugChar(lowhex(checksum)); // flushDebugChannel(); } while(getDebugChar() != '+'); } /* * this function takes the SH-1 exception number and attempts to * translate this number into a unix compatible signal value */ static int computeSignal(int exceptionVector) { int sigval; switch(exceptionVector) { case EXC_ILLEGAL_INSTR: case EXC_SLOT_ILLEGAL_INSTR: sigval = 4; break; case EXC_DATA_ADDRESS_READ: case EXC_DATA_ADDRESS_WRITE: sigval = 10; break; case EXC_TRAPA: sigval = 5; break; default: sigval = 7; /* "software generated"*/ break; } return (sigval); } static void doSStep(void) { short *instrMem; int displacement; int reg; unsigned short opcode, br_opcode; instrMem = (short *) registers[PC]; opcode = *instrMem; stepped = 1; br_opcode = opcode & COND_BR_MASK; if(br_opcode == BT_INSTR || br_opcode == BTS_INSTR) { if(registers[SR] & T_BIT_MASK) { displacement = (opcode & COND_DISP) << 1; if(displacement & 0x80) displacement |= 0xffffff00; /* * Remember PC points to second instr. * after PC of branch ... so add 4 */ instrMem = (short *)(registers[PC] + displacement + 4); } else { /* can't put a trapa in the delay slot of a bt/s instruction */ instrMem += (br_opcode == BTS_INSTR) ? 2 : 1; } } else if(br_opcode == BF_INSTR || br_opcode == BFS_INSTR) { if(registers[SR] & T_BIT_MASK) { /* can't put a trapa in the delay slot of a bf/s instruction */ instrMem += (br_opcode == BFS_INSTR) ? 2 : 1; } else { displacement = (opcode & COND_DISP) << 1; if(displacement & 0x80) displacement |= 0xffffff00; /* * Remember PC points to second instr. * after PC of branch ... so add 4 */ instrMem = (short *)(registers[PC] + displacement + 4); } } else if((opcode & UCOND_DBR_MASK) == BRA_INSTR) { displacement = (opcode & UCOND_DISP) << 1; if(displacement & 0x0800) displacement |= 0xfffff000; /* * Remember PC points to second instr. * after PC of branch ... so add 4 */ instrMem = (short *)(registers[PC] + displacement + 4); } else if((opcode & UCOND_RBR_MASK) == JSR_INSTR) { reg = (char)((opcode & UCOND_REG) >> 8); instrMem = (short *) registers[reg]; } else if(opcode == RTS_INSTR) instrMem = (short *) registers[PR]; else if(opcode == RTE_INSTR) instrMem = (short *) registers[15]; else if((opcode & TRAPA_MASK) == TRAPA_INSTR) instrMem = (short *)((opcode & ~TRAPA_MASK) << 2); else instrMem += 1; instrBuffer.memAddr = instrMem; instrBuffer.oldInstr = *instrMem; *instrMem = SSTEP_INSTR; icache_flush_range((uint32)instrMem, 2); } /* Undo the effect of a previous doSStep. If we single stepped, restore the old instruction. */ static void undoSStep(void) { if(stepped) { short *instrMem; instrMem = instrBuffer.memAddr; *instrMem = instrBuffer.oldInstr; icache_flush_range((uint32)instrMem, 2); } stepped = 0; } /* Handle inserting/removing a hardware breakpoint. Using the SH4 User Break Controller (UBC) we can have two breakpoints, each set for either instruction and/or operand access. Break channel B can match a specific data being moved, but there is no GDB remote protocol spec for utilizing this functionality. */ #define LREG(r, o) (*((uint32*)((r)+(o)))) #define WREG(r, o) (*((uint16*)((r)+(o)))) #define BREG(r, o) (*((uint8*)((r)+(o)))) static void hardBreakpoint(int set, int brktype, uint32 addr, int length, char* resBuffer) { char* const ucb_base = (char*)0xff200000; static const int ucb_step = 0xc; static const char BAR = 0x0, BAMR = 0x4, BBR = 0x8, /*BASR = 0x14,*/ BRCR = 0x20; static const uint8 bbrBrk[] = { 0x0, /* type 0, memory breakpoint -- unsupported */ 0x14, /* type 1, hardware breakpoint */ 0x28, /* type 2, write watchpoint */ 0x24, /* type 3, read watchpoint */ 0x2c /* type 4, access watchpoint */ }; uint8 bbr = 0; char* ucb; int i; if(length <= 8) do { bbr++; } while(length >>= 1); bbr |= bbrBrk[brktype]; if(addr == 0) { /* GDB tries to watch 0, wasting a UCB channel */ memcpy(resBuffer, "OK", 2); } else if(brktype == 0) { /* we don't support memory breakpoints -- the debugger will use the manual memory modification method */ *resBuffer = '\0'; } else if(length > 8) { memcpy(resBuffer, "E22", 3); } else if(set) { WREG(ucb_base, BRCR) = 0; /* find a free UCB channel */ for(ucb = ucb_base, i = 2; i > 0; ucb += ucb_step, i--) if(WREG(ucb, BBR) == 0) break; if(i) { LREG(ucb, BAR) = addr; BREG(ucb, BAMR) = 0x4; /* no BASR bits used, all BAR bits used */ WREG(ucb, BBR) = bbr; memcpy(resBuffer, "OK", 2); } else memcpy(resBuffer, "E12", 3); } else { /* find matching UCB channel */ for(ucb = ucb_base, i = 2; i > 0; ucb += ucb_step, i--) if(LREG(ucb, BAR) == addr && WREG(ucb, BBR) == bbr) break; if(i) { WREG(ucb, BBR) = 0; memcpy(resBuffer, "OK", 2); } else memcpy(resBuffer, "E06", 3); } } #undef LREG #undef WREG /* This function does all exception handling. It only does two things - it figures out why it was called and tells gdb, and then it reacts to gdb's requests. When in the monitor mode we talk a human on the serial line rather than gdb. */ static void gdb_handle_exception(int exceptionVector) { int sigval, stepping; uint32 addr, length; char *ptr; /* reply to host that an exception has occurred */ sigval = computeSignal(exceptionVector); remcomOutBuffer[0] = 'S'; remcomOutBuffer[1] = highhex(sigval); remcomOutBuffer[2] = lowhex(sigval); remcomOutBuffer[3] = 0; putpacket(remcomOutBuffer); /* * Do the thangs needed to undo * any stepping we may have done! */ undoSStep(); stepping = 0; while(1) { remcomOutBuffer[0] = 0; ptr = (char *)getpacket(); switch(*ptr++) { case '?': remcomOutBuffer[0] = 'S'; remcomOutBuffer[1] = highhex(sigval); remcomOutBuffer[2] = lowhex(sigval); remcomOutBuffer[3] = 0; break; case 'd': remote_debug = !(remote_debug); /* toggle debug flag */ break; case 'g': { /* return the value of the CPU registers */ int i; char* outBuf = remcomOutBuffer; for(i = 0; i < NUMREGBYTES / 4; i++) outBuf = mem2hex((char *)(registers + kosRegMap[i]), outBuf, 4); } break; case 'G': { /* set the value of the CPU registers - return OK */ int i; char* inBuf = ptr; for(i = 0; i < NUMREGBYTES / 4; i++, inBuf += 8) hex2mem(inBuf, (char *)(registers + kosRegMap[i]), 4); memcpy(remcomOutBuffer, "OK", 2); } break; /* mAA..AA,LLLL Read LLLL bytes at address AA..AA */ case 'm': dofault = 0; /* TRY, TO READ %x,%x. IF SUCCEED, SET PTR = 0 */ if(hexToInt(&ptr, &addr)) if(*(ptr++) == ',') if(hexToInt(&ptr, &length)) { ptr = 0; mem2hex((char *) addr, remcomOutBuffer, length); } if(ptr) memcpy(remcomOutBuffer, "E01", 3); /* restore handler for bus error */ dofault = 1; break; /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */ case 'M': dofault = 0; /* TRY, TO READ '%x,%x:'. IF SUCCEED, SET PTR = 0 */ if(hexToInt(&ptr, &addr)) if(*(ptr++) == ',') if(hexToInt(&ptr, &length)) if(*(ptr++) == ':') { hex2mem(ptr, (char *) addr, length); icache_flush_range(addr, length); ptr = 0; memcpy(remcomOutBuffer, "OK", 2); } if(ptr) memcpy(remcomOutBuffer, "E02", 3); /* restore handler for bus error */ dofault = 1; break; /* cAA..AA Continue at address AA..AA(optional) */ /* sAA..AA Step one instruction from AA..AA(optional) */ case 's': stepping = 1; /* tRY, to read optional parameter, pc unchanged if no parm */ if(hexToInt(&ptr, &addr)) { registers[PC] = addr; } doSStep(); break; case 'c': if(hexToInt(&ptr, &addr)) { registers[PC] = addr; } if (stepping) { doSStep(); } break; /* kill the program */ case 'k': /* reboot */ arch_reboot(); break; /* set or remove a breakpoint */ case 'Z': case 'z': { int set = (*(ptr - 1) == 'Z'); int brktype = *ptr++ - '0'; if(*(ptr++) == ',') if(hexToInt(&ptr, &addr)) if(*(ptr++) == ',') if(hexToInt(&ptr, &length)) { hardBreakpoint(set, brktype, addr, length, remcomOutBuffer); ptr = 0; } if(ptr) memcpy(remcomOutBuffer, "E02", 3); } break; } /* switch */ /* reply to the request */ putpacket(remcomOutBuffer); } } /* This function will generate a breakpoint exception. It is used at the beginning of a program to sync up with a debugger and can be used otherwise as a quick means to stop program execution and "break" into the debugger. */ void gdb_breakpoint(void) { BREAKPOINT(); } static char getDebugChar(void) { int ch; // if(using_dcl) { // if(in_dcl_pos >= in_dcl_size) { // in_dcl_size = dcload_gdbpacket(NULL, 0, in_dcl_buf, BUFMAX); // in_dcl_pos = 0; // } // // ch = in_dcl_buf[in_dcl_pos++]; // } // else { /* Spin while nothing is available. */ while((ch = scif_read()) < 0); ch &= 0xff; // } return ch; } static void putDebugChar(char ch) { // if(using_dcl) { // out_dcl_buf[out_dcl_pos++] = ch; // // if(out_dcl_pos >= BUFMAX) { // dcload_gdbpacket(out_dcl_buf, out_dcl_pos, NULL, 0); // out_dcl_pos = 0; // } // } // else { /* write the char and flush it. */ scif_write(ch); scif_flush(); // } } //static void //flushDebugChannel() { // /* send the current complete packet and wait for a response */ // if(using_dcl) { // if(in_dcl_pos >= in_dcl_size) { // in_dcl_size = dcload_gdbpacket(out_dcl_buf, out_dcl_pos, in_dcl_buf, BUFMAX); // in_dcl_pos = 0; // } // else // dcload_gdbpacket(out_dcl_buf, out_dcl_pos, NULL, 0); // // out_dcl_pos = 0; // } //} //static void handle_exception(irq_t code, irq_context_t *context) { void *handle_exception(register_stack *context, void *current_vector) { registers = (uint32 *)context; // gdb_handle_exception(code); gdb_handle_exception(context->exception_type); return current_vector; } //static void handle_user_trapa(irq_t code, irq_context_t *context) { void *handle_user_trapa(register_stack *context, void *current_vector) { // (void)code; registers = (uint32 *)context; gdb_handle_exception(EXC_TRAPA); return current_vector; } //static void handle_gdb_trapa(irq_t code, irq_context_t *context) { void *handle_gdb_trapa(register_stack *context, void *current_vector) { /* * trapa 0x20 indicates a software trap inserted in * place of code ... so back up PC by one * instruction, since this instruction will * later be replaced by its original one! */ // (void)code; registers = (uint32 *)context; registers[PC] -= 2; gdb_handle_exception(EXC_TRAPA); return current_vector; } void *handle_trapa(register_stack *context, void *current_vector) { uint32 vec = (*REG_TRA) >> 2; switch(vec) { case 32: return handle_gdb_trapa(context, current_vector); case 255: return handle_user_trapa(context, current_vector); default: return current_vector; } } static exception_handler_f old_handler; void gdb_init() { // if(dcload_gdbpacket(NULL, 0, NULL, 0) == 0) // using_dcl = 1; // else // scif_set_parameters(57600, 1); // // irq_set_handler(EXC_ILLEGAL_INSTR, handle_exception); // irq_set_handler(EXC_SLOT_ILLEGAL_INSTR, handle_exception); // irq_set_handler(EXC_DATA_ADDRESS_READ, handle_exception); // irq_set_handler(EXC_DATA_ADDRESS_WRITE, handle_exception); // irq_set_handler(EXC_USER_BREAK_PRE, handle_exception); // // trapa_set_handler(32, handle_gdb_trapa); // trapa_set_handler(255, handle_user_trapa); scif_init(); exception_table_entry ent; ent.type = EXP_TYPE_GEN; ent.handler = handle_exception; ent.code = EXC_ILLEGAL_INSTR; exception_add_handler(&ent, &old_handler); ent.code = EXC_SLOT_ILLEGAL_INSTR; exception_add_handler(&ent, &old_handler); ent.code = EXC_DATA_ADDRESS_READ; exception_add_handler(&ent, &old_handler); ent.code = EXC_DATA_ADDRESS_WRITE; exception_add_handler(&ent, &old_handler); ent.code = EXC_USER_BREAK_PRE; exception_add_handler(&ent, &old_handler); ent.code = EXC_TRAPA; ent.handler = handle_trapa; exception_add_handler(&ent, &old_handler); BREAKPOINT(); } <file_sep>/firmware/isoldr/loader/utils.c /** * DreamShell ISO Loader * Utils * (c)2011-2023 SWAT <http://www.dc-swat.ru> */ #include <main.h> #include <limits.h> #include <dc/sq.h> #include <dcload.h> #include <asic.h> #include <reader.h> #include <syscalls.h> #include <exception.h> #ifndef HAVE_EXPT // Just for decreasing ifdef's with HAVE_EXPT int exception_inited(void) { return 0; } int exception_inside_int(void) { return 0; } #endif void setup_machine(void) { const uint32 val = 0xffffffff; uint32 addr = 0xffd80000; *(vuint8 *)(addr + 4) = 0; *(vuint8 *)(addr + 0) = 0; *(vuint32 *)(addr + 8) = val; *(vuint32 *)(addr + 12) = val; *(vuint32 *)(addr + 20) = val; *(vuint32 *)(addr + 24) = val; *(vuint16 *)(addr + 28) = 0; *(vuint32 *)(addr + 32) = val; *(vuint32 *)(addr + 36) = val; *(vuint16 *)(addr + 40) = 0; if (IsoInfo->boot_mode == BOOT_MODE_DIRECT) { *(vuint8 *)(addr + 4) |= 1; } /* Clear IRQ stuff */ *((vuint32 *) 0xa05f6910) = 0; *((vuint32 *) 0xa05f6914) = 0; *((vuint32 *) 0xa05f6918) = 0; *((vuint32 *) 0xa05f6920) = 0; *((vuint32 *) 0xa05f6924) = 0; *((vuint32 *) 0xa05f6928) = 0; *((vuint32 *) 0xa05f6930) = 0; *((vuint32 *) 0xa05f6934) = 0; *((vuint32 *) 0xa05f6938) = 0; *((vuint32 *) 0xa05f6940) = 0; *((vuint32 *) 0xa05f6944) = 0; *((vuint32 *) 0xa05f6950) = 0; *((vuint32 *) 0xa05f6954) = 0; addr = *((vuint8 *)0xa05f709c); addr++; // Prevent gcc optimization on register reading. *((vuint32 *) 0xA05F6900) = 0x4038; *((vuint32 *)0xa05f6904) = 0xf; *((vuint32 *)0xa05f6908) = 0x9fffff; *((vuint32 *)0xa05f74a0) = 0x2001; } void shutdown_machine(void) { const uint32 reset_regs[] = { 0xa05f6808, 0xa05f6820, 0xa05f6c14, 0xa05f7414, 0xa05f7814, 0xa05f7834, 0xa05f7854, 0xa05f7874, 0xa05f7c14, 0xffa0001c, 0xffa0002c, 0xffa0003c }; *(vuint32 *)(0xff000010) = 0; *(vuint32 *)(0xff00001c) = 0x929; uint32 addr1 = 0xa05f6938; uint32 addr2 = 0xffd0000c; for (int i = 3; i; --i) { *(vuint32 *)(addr1) = 0; addr1 -= 4; *(vuint32 *)(addr1) = 0; addr1 -= 4; *(vuint32 *)(addr1) = 0; addr1 -= 8; *(vuint32 *)(addr2) = 0; addr2 -= 4; } *(vuint32 *)(addr2) = 0; addr2 = *(vuint32 *)(addr1); addr1 -= 8; addr2 += *(vuint32 *)(addr1); *(vuint32 *)(0xa05f8044) = (*(vuint32 *)(0xa05f8044) & 0xfffffffe); for (uint32 i = 0; i < ((sizeof(reset_regs)) >> 2); ++i) { *(vuint32 *)(reset_regs[i]) = (*(vuint32 *)(reset_regs[i]) & 0xfffffffe); for (uint32 j = 0; j < 127; ++j) { if (!(*(vuint32 *)(reset_regs[i]) & 0xfffffffe)) { break; } } } } uint Load_BootBin() { int rv, bsec; uint32 bs = 0xfff000; /* FIXME: switch stack pointer for use all memory */ uint32 exec_addr = CACHED_ADDR(IsoInfo->exec.addr); const uint32 sec_size = 2048; uint8 *buff = (uint8*)(NONCACHED_ADDR(IsoInfo->exec.addr)); if(IsoInfo->exec.size < bs) { bs = IsoInfo->exec.size; } bsec = (bs / sec_size) + ( bs % sec_size ? 1 : 0); if(loader_addr > exec_addr && loader_addr < (exec_addr + bs)) { int count = (loader_addr - exec_addr) / sec_size; int part = (ISOLDR_MAX_MEM_USAGE / sec_size) + count; rv = ReadSectors(buff, IsoInfo->exec.lba, count, NULL); if(rv == COMPLETED) { rv = ReadSectors(buff + (part * sec_size), IsoInfo->exec.lba + part, bsec - part, NULL); } } else { rv = ReadSectors(buff, IsoInfo->exec.lba, bsec, NULL); } return rv == COMPLETED ? 1 : 0; } static void set_region() { char region_str[3][6] = { {"00000"}, {"00110"}, {"00211"} }; uint8 *src = (uint8 *)0xa021a000; uint8 *dst = (uint8 *)0x8c000070; uint8 *reg = (uint8 *)0x8c000020; if (*((uint32 *)0xac008030) == 0x2045554a) { *reg = 0; memcpy(dst, src, 5); } else if(*((char *)0x8c008032) == 'E') { *reg = 3; memcpy(dst, region_str[2], 5); } else if(*((char *)0x8c008031) == 'U') { *reg = 2; memcpy(dst, region_str[1], 5); } else { *reg = 1; memcpy(dst, region_str[0], 5); } } uint Load_IPBin(int header_only) { uint32 ipbin_addr = NONCACHED_ADDR(IPBIN_ADDR); uint32 lba = IsoInfo->track_lba[0]; uint32 cnt = 16; uint8 *buff = (uint8*)ipbin_addr; if(header_only) { cnt = 1; } else if(IsoInfo->boot_mode == BOOT_MODE_IPBIN_TRUNC) { lba += 12; cnt -= 12; buff += (12 * 2048); } if(ReadSectors(buff, lba, cnt, NULL) == COMPLETED) { if(IsoInfo->boot_mode != BOOT_MODE_IPBIN_TRUNC && header_only == 0) { *((uint32 *)ipbin_addr + 0x032c) = 0x8c00e000; *((uint16 *)ipbin_addr + 0x10d8) = 0x5113; *((uint16 *)ipbin_addr + 0x140a) = 0x000b; *((uint16 *)ipbin_addr + 0x140c) = 0x0009; set_region(); } else if(header_only) { set_region(); } return 1; } return 0; } static int get_ds_fd() { char *fn = "/DS/DS_CORE.BIN"; int fd = open(fn, O_RDONLY); if (fd < 0) { fd = open(fn + 3, O_RDONLY); } return fd; } int Load_DS() { LOGFF(NULL); if (iso_fd > FILEHND_INVALID) { close(iso_fd); } int fd = get_ds_fd(); if (fd < 0) { LOGFF("FAILED\n"); return -1; } restore_syscalls(); int rs = read(fd, (uint8 *)NONCACHED_ADDR(APP_ADDR), total(fd)); close(fd); return rs; } #ifdef HAVE_EXT_SYSCALLS void Load_Syscalls() { uint8_t *dst = (uint8_t *) NONCACHED_ADDR(RAM_START_ADDR); uint8_t *src = (uint8_t *) IsoInfo->syscalls; uint32 lba = 0; int fd; memcpy(dst, src, 0x4000); memcpy(dst + 0x128C, &IsoInfo->toc, 408); if (IsoInfo->image_type == ISOFS_IMAGE_TYPE_GDI) { *((uint32 *)(dst + 0x1248)) = 0x80; // GD switch_gdi_data_track(150, get_GDS()); ioctl(iso_fd, FS_IOCTL_GET_LBA, &lba); *((uint32 *)(dst + 0x1424)) = lba; switch_gdi_data_track(45150, get_GDS()); ioctl(iso_fd, FS_IOCTL_GET_LBA, &lba); *((uint32 *)(dst + 0x1428)) = lba; *((uint32 *)(dst + 0xD0)) = *((uint32 *)(dst + 0x1428)); if (IsoInfo->track_lba[0] != IsoInfo->track_lba[1]) { switch_gdi_data_track(IsoInfo->track_lba[1], get_GDS()); ioctl(iso_fd, FS_IOCTL_GET_LBA, &lba); *((uint32 *)(dst + 0x142C)) = lba; } char ch_name[sizeof(IsoInfo->image_file)]; memcpy(ch_name, IsoInfo->image_file, sizeof(IsoInfo->image_file)); memcpy(&ch_name[strlen(IsoInfo->image_file) - 6], "103.iso", 7); close(iso_fd); fd = open(ch_name, O_RDONLY); if (fd > FILEHND_INVALID) { ioctl(fd, FS_IOCTL_GET_LBA, &lba); *((uint32 *)(dst + 0xD4)) = lba; close(fd); memcpy(&ch_name[strlen(IsoInfo->image_file)-6], "203.iso", 7); fd = open(ch_name, O_RDONLY); if (fd > FILEHND_INVALID) { ioctl(fd, FS_IOCTL_GET_LBA, &lba); *((uint32 *)(dst + 0xD8)) = lba; close(fd); memcpy(&ch_name[strlen(IsoInfo->image_file)-6], "303.iso", 7); fd = open(ch_name, O_RDONLY); if (fd > FILEHND_INVALID) { ioctl(fd, FS_IOCTL_GET_LBA, &lba); *((uint32 *)(dst + 0xDC)) = lba; close(fd); } } } } else { // ISO *((uint32 *)(dst + 0x1248)) = 0x20; // CD ioctl(iso_fd, FS_IOCTL_GET_LBA, &lba); *((uint32 *)(dst + 0x1424)) = lba; *((uint32 *)(dst + 0x1428)) = 0; *((uint32 *)(dst + 0x142C)) = 0; } // IGR fd = get_ds_fd(); ioctl(fd, FS_IOCTL_GET_LBA, &lba); *((uint32 *)(dst + 0x1430)) = lba; *((uint32 *)(dst + 0x1434)) = total(fd); close(fd); if(IsoInfo->boot_mode == BOOT_MODE_DIRECT) { sys_misc_init(); } else { *((uint32 *)0xa05f8040) = 0x00c0c0c0; } } #endif void *search_memory(const uint8 *key, uint32 key_size) { uint32 start_loc = CACHED_ADDR(IsoInfo->exec.addr); uint32 end_loc = start_loc + IsoInfo->exec.size; for(uint8 *cur_loc = (uint8 *)start_loc; (uint32)cur_loc <= end_loc; cur_loc++) { if(*cur_loc == key[0]) { if(!memcmp((const uint8 *)cur_loc, key, key_size)) { return (void *)cur_loc; } } } return NULL; } int patch_memory(const uint32 key, const uint32 val) { uint32 exec_addr = NONCACHED_ADDR(IsoInfo->exec.addr); uint32 end_loc = exec_addr + IsoInfo->exec.size; uint8 *k = (uint8 *)&key; uint8 *v = (uint8 *)&val; int count = 0; for(uint8 *cur_loc = (uint8 *)exec_addr; (uint32)cur_loc <= end_loc; cur_loc++) { if(*cur_loc == k[0]) { if(!memcmp((const uint8 *)cur_loc, k, sizeof(val))) { memcpy(cur_loc, v, sizeof(val)); count++; } } } return count; } void apply_patch_list() { if(!IsoInfo->patch_addr[0]) { return; } for(uint i = 0; i < sizeof(IsoInfo->patch_addr) >> 2; ++i) { if(*(uint32 *)IsoInfo->patch_addr[i] != IsoInfo->patch_value[i]) { *(uint32 *)IsoInfo->patch_addr[i] = IsoInfo->patch_value[i]; } } } int printf(const char *fmt, ...) { if(IsoInfo != NULL && IsoInfo->fast_boot) { return 0; } static int print_y = 1; int i = 0; uint16 *vram = (uint16*)(VIDEO_VRAM_START); if(fmt == NULL) { print_y = 1; return 0; } #if defined(LOG) char buff[64]; va_list args; va_start(args, fmt); i = vsnprintf(buff, sizeof(buff), fmt, args); va_end(args); # ifndef LOG_SCREEN LOGF(buff); # endif #else char *buff = (char *)fmt; #endif bfont_draw_str(vram + ((print_y * 24 + 4) * 640) + 12, 0xffff, 0x0000, buff); if(buff[strlen(buff)-1] == '\n') { if (print_y++ > 15) { print_y = 0; memset((uint32 *)vram, 0, 2 * 1024 * 1024); } } return i; } void vid_waitvbl() { vuint32 *vbl = ((vuint32 *)0xa05f8000) + 0x010c / 4; while(!(*vbl & 0x01ff)) ; while(*vbl & 0x01ff) ; } void draw_gdtex(uint8 *src) { int xPos = 640 - 280; int yPos = 480 - 280; int r, g, b, a, pos; uint16 *vram = (uint16*)(VIDEO_VRAM_START); for (uint x = 0; x < 256; ++x) { for (uint y = 0; y < 256; ++y) { pos = (yPos + x) * 640 + y + xPos; r = src[0]; g = src[1]; b = src[2]; a = src[3]; if(a) { r >>= 3; g >>= 2; b >>= 3; if(a < 255) { uint16 p = vram[pos]; r = ((r * a) + (((p & 0xf800) >> 11) * (255 - a))) >> 8; g = ((g * a) + (((p & 0x07e0) >> 5) * (255 - a))) >> 8; b = ((b * a) + (( p & 0x001f) * (255 - a))) >> 8; } vram[pos] = (r << 11) | (g << 5) | b; } src += 4; } } } void set_file_number(char *filename, int num) { int len = strlen(filename); if (num < 10) { filename[len - 5] = '0' + num; } else if(num < 100) { filename[len - 5] = '0' + (num % 10); filename[len - 6] = '0' + (num / 10); } else if(num < 1000) { filename[len - 5] = '0' + (num % 10); filename[len - 6] = '0' + ((num % 100) / 10); filename[len - 7] = '0' + (num / 100); } } static char *replace_filename(char *filepath, char *filename) { uint8 *val = (uint8 *)filepath, *tmp = NULL; int len = strlen(filepath); do { tmp = tmp ? val + 1 : val; val = memchr(tmp, '/', len); } while(val != NULL); len = strlen(filename); memcpy(tmp, filename, len); tmp[len] = '\0'; return filepath; } char *relative_filename(char *filename) { char *result = malloc(sizeof(IsoInfo->image_file)); if (result == NULL) { LOGFF("malloc failed\n"); return NULL; } memcpy(result, IsoInfo->image_file, sizeof(IsoInfo->image_file)); return replace_filename(result, filename); } #ifdef HAVE_SCREENSHOT void video_screenshot() { static int num = 0; static uint32 req = 0; if (exception_inside_int()) { req = 1; return; } else if(req == 0) { return; } else { req = 0; } char *filename = "/DS/screenshot/game_scr_001.ppm"; const char *header = "# DreamShell ISO Loader\n640 480\n255\n"; const size_t header_len = strlen(header); const size_t fs_sector_size = 512; const size_t buffer_size = fs_sector_size * 3; uint8 *buffer = (uint8 *)malloc(buffer_size); uint8 *buffer_end = buffer + buffer_size; uint8 *pbuffer = buffer; uint32 try_cnt = 30; if (buffer == NULL) { LOGFF("Can't allocate memory\n"); return; } set_file_number(filename, ++num); file_t fd = open(filename, O_WRONLY | O_PIO); while (fd < 0) { if (--try_cnt == 0) { break; } else if(fd == FS_ERR_NO_PATH) { fd = open(filename + 3, O_WRONLY | O_PIO); if(fd == FS_ERR_NO_PATH) { break; } } else if (fd == FS_ERR_EXISTS) { num += 10; set_file_number(filename, num); fd = open(filename, O_WRONLY | O_PIO); } } if (fd < 0) { LOGFF("Can't create file: %s\n", filename); free(buffer); return; } memset(buffer, '#', buffer_size); buffer[0] = 'P'; buffer[1] = '6'; buffer[2] = '\n'; memcpy(buffer + (fs_sector_size - header_len), header, header_len); for (uint32 i = 64; i < (fs_sector_size - header_len); ++i) { if (i % 64 == 0) { buffer[i] = '\n'; } } write(fd, buffer, fs_sector_size); uint32 pixel; uint32 *vraml = (uint32 *)(VIDEO_VRAM_START); uint16 *vrams = (uint16 *)(vraml); uint8 *vramb = (uint8 *)(vraml); const uint32 display_cfg = *(vuint32 *)0xa05f8044; const uint32 pixel_mode = (display_cfg >> 2) & 0x0f; const uint32 display_size = *(vuint32 *)0xa05f805c; uint32 width = 640; uint32 height = ((display_size >> 10) & 0x3ff) + 1; if(height <= 240) { width = 320; height = 240; } else { height = 480; } const uint32 pix_num = width * height; LOGFF("%s %dx%d %d\n", filename, width, height, pixel_mode); for(uint32 i = 0; i < pix_num; ++i) { switch(pixel_mode) { case PM_RGB888P: pbuffer[0] = vramb[i * 3 + 2]; pbuffer[1] = vramb[i * 3 + 1]; pbuffer[2] = vramb[i * 3]; break; case PM_RGB0888: pixel = vraml[i]; pbuffer[0] = ((pixel >> 16) & 0xff); pbuffer[1] = ((pixel >> 8) & 0xff); pbuffer[2] = (pixel & 0xff); break; case PM_RGB555: pixel = vrams[i]; pbuffer[0] = (((pixel >> 10) & 0x1f) << 3); pbuffer[1] = (((pixel >> 5) & 0x1f) << 3); pbuffer[2] = ((pixel & 0x1f) << 3); break; case PM_RGB565: default: pixel = vrams[i]; pbuffer[0] = (((pixel >> 11) & 0x1f) << 3); pbuffer[1] = (((pixel >> 5) & 0x3f) << 2); pbuffer[2] = ((pixel & 0x1f) << 3); break; } pbuffer += 3; if(pbuffer >= buffer_end) { write(fd, buffer, buffer_size); pbuffer = buffer; } } if ((pbuffer - buffer) > 0) { write(fd, buffer, pbuffer - buffer); } close(fd); free(buffer); } #endif #ifdef LOG size_t strnlen(const char *s, size_t maxlen) { const char *e; size_t n; for (e = s, n = 0; *e && n < maxlen; e++, n++) ; return n; } int check_digit (char c) { if((c>='0') && (c<='9')) { return 1; } return 0; } static char log_buff[128]; #if _FS_READONLY == 0 && defined(LOG_FILE) static int log_fd = FS_ERR_SYSERR; static int open_log_file() { int fd = open(LOG_FILE, O_WRONLY | O_APPEND); if (fd > FS_ERR_SYSERR) { write(fd, "--- Start log ---\n", 18); ioctl(fd, FS_IOCTL_SYNC, NULL); } return fd; } #endif /* _FS_READONLY */ int OpenLog() { memset(log_buff, 0, sizeof(log_buff)); #if _FS_READONLY == 0 && defined(LOG_FILE) log_fd = open_log_file(); #endif #if defined(DEV_TYPE_DCL) || defined(LOG_DCL) dcload_init(); #elif !defined(LOG_SCREEN) scif_init(); #endif return 1; } static int PutLog(char *buff) { int len = strlen(buff); #if _FS_READONLY == 0 && defined(LOG_FILE) if (log_fd == FS_ERR_SYSERR) { log_fd = open_log_file(); } if(log_fd > FS_ERR_SYSERR) { write(log_fd, buff, len); ioctl(fd, FS_IOCTL_SYNC, NULL); } #endif #if defined(LOG_SCREEN) printf(buff); #elif defined(DEV_TYPE_DCL) || defined(LOG_DCL) dcload_write_buffer((uint8 *)buff, len); #else scif_write_buffer((uint8 *)buff, len, 1); #endif return len; } int WriteLog(const char *fmt, ...) { va_list args; int i; va_start(args, fmt); i = vsnprintf(log_buff, sizeof(log_buff), fmt, args); va_end(args); PutLog(log_buff); return i; } int WriteLogFunc(const char *func, const char *fmt, ...) { PutLog((char *)func); if(fmt == NULL) { PutLog("\n"); return 0; } PutLog(": "); va_list args; int i; va_start(args, fmt); i = vsnprintf(log_buff, sizeof(log_buff), fmt, args); va_end(args); PutLog(log_buff); return i; } #endif /* LOG */ <file_sep>/lib/libparallax/include/font.h /* Parallax for KallistiOS ##version## font.h (c)2002 <NAME> */ #ifndef __PARALLAX_FONT #define __PARALLAX_FONT #include <sys/cdefs.h> __BEGIN_DECLS /** \file Texture-based font routines. These are equivalent to DCPLIB's fntTxf routines, but are written entirely in C. */ #include <kos/vector.h> #include "texture.h" /** A font struct. This will maintain all the information we need to actually draw using this font. Note however that this does not include things like style states (italics, etc). All members are considered private and should not be tampered with. */ typedef struct plx_font { plx_texture_t * txr; /**< Our font texture */ int glyph_cnt; /**< The number of glyphs we have loaded */ int map_cnt; /**< Size of our font map in entries */ short * map; /**< Mapping from 16-bit character to glyph index */ point_t * txr_ll; /**< Lower-left texture coordinates */ point_t * txr_ur; /**< Upper-right texture coordinates */ point_t * vert_ll; /**< Lower-left vertex coordinates */ point_t * vert_ur; /**< Upper-right vertex coordinates */ } plx_font_t; /** Font drawing context struct. This struct will keep track of everything you need to actually draw text using a plx_font_t. This includes current output position, font attributes (oblique, etc), etc. All members are considered private and should not be tampered with. */ typedef struct plx_fcxt { plx_font_t * fnt; /**< Our current font */ int list; /**< Which PLX list will we use? */ float slant; /**< For oblique text output */ float size; /**< Pixel size */ float gap; /**< Extra pixels between each char */ float fixed_width; /**< Width of each character in points in fixed mode */ uint32 flags; /**< Font attributes */ uint32 color; /**< Color value */ point_t pos; /**< Output position */ } plx_fcxt_t; #define PLX_FCXT_FIXED 0x0001 /**< Fixed width flag */ /** Load a font from the VFS. Fonts are currently in the standard TXF format, though this may eventually change to add more capabilities (textured fonts, large/wide character sets, etc). */ plx_font_t * plx_font_load(const char * fn); /** Remove a previously loaded font from memory. */ void plx_font_destroy(plx_font_t * fnt); /** Create a font context from the given font struct with some reasonable default values. The list given in the list parameter will be used for low-level interactions. */ plx_fcxt_t * plx_fcxt_create(plx_font_t * fnt, int list); /** Destroy a previously created font context. Note that this will NOT affect the font the context points to. */ void plx_fcxt_destroy(plx_fcxt_t * cxt); /** Given a font context, return the metrics of the individual named character. */ void plx_fcxt_char_metrics(plx_fcxt_t * cxt, uint16 ch, float * outleft, float * outup, float * outright, float * outdown); /** Given a font context, return the metrics of the given string. */ void plx_fcxt_str_metrics(plx_fcxt_t * cxt, const char * str, float * outleft, float * outup, float * outright, float *outdown); /** Set the slant value for the given context. */ void plx_fcxt_setslant(plx_fcxt_t * cxt, float slant); /** Get the slant value for the given context. */ float plx_fcxt_getslant(plx_fcxt_t * cxt); /** Set the size value for the given context. */ void plx_fcxt_setsize(plx_fcxt_t * cxt, float size); /** Get the size value for the given context. */ float plx_fcxt_getsize(plx_fcxt_t * cxt); /** Set the color value for the given context as a set of floating point numbers. */ void plx_fcxt_setcolor4f(plx_fcxt_t * cxt, float a, float r, float g, float b); /** Get the color value for the given context as a set of floating point numbers. */ void plx_fcxt_getcolor4f(plx_fcxt_t * cxt, float * outa, float * outr, float * outg, float * outb); /** Set the color value for the given context as a packed integer. */ void plx_fcxt_setcolor1u(plx_fcxt_t * cxt, uint32 color); /** Get the color value for the given context as a packed integer. */ uint32 plx_fcxt_getcolor1u(plx_fcxt_t * cxt); /** Set the output cursor position for the given context using a point_t. */ void plx_fcxt_setpos_pnt(plx_fcxt_t * cxt, const point_t * pos); /** Set the output cursor position for the given context using 3 coords. */ void plx_fcxt_setpos(plx_fcxt_t * cxt, float x, float y, float z); /** Get the output cursor position for the given context. */ void plx_fcxt_getpos(plx_fcxt_t * cxt, point_t * outpos); /** Set the offset cursor position for the given context. */ void plx_fcxt_setoffs(plx_fcxt_t * cxt, const point_t * offs); /** Get the offset cursor position for the given context. */ void plx_fcxt_getoffs(plx_fcxt_t * cxt, point_t * outoffs); /** Add the given values to the given context's offset position. */ void plx_fcxt_addoffs(plx_fcxt_t * cxt, const point_t * offset); /** Begin a drawing operation with the given context. This must be done before any font operations where something else might have submitted a polygon header since the last font operation. */ void plx_fcxt_begin(plx_fcxt_t * cxt); /** Draw a single character with the given context and parameters. Returns the cursor advancement amount. */ float plx_fcxt_draw_ch(plx_fcxt_t * cxt, uint16 ch); /** Draw a string with the given context and parameters. */ void plx_fcxt_draw(plx_fcxt_t * cxt, const char * str); /** Finish a drawing operation with the given context. Called after you are finished with a drawing operation. This currently doesn't do much, but it might later, so call it! */ void plx_fcxt_end(plx_fcxt_t * cxt); __END_DECLS #endif /* __PARALLAX_FONT */ <file_sep>/modules/ini/Makefile # # libini module for DreamShell # Copyright (C) 2013-2022 SWAT # TARGET_NAME = ini OBJS = module.o LIBS = -lini DBG_LIBS = -lds EXPORTS_FILE = exports.txt VER_MAJOR = 1 VER_MINOR = 0 VER_MICRO = 0 KOS_LIB_PATHS += -L./libini/src/.libs all: rm-elf build_lib libini/Makefile: cd ./libini && ./configure --host=sh-elf \ --prefix="`pwd`/build" CFLAGS="${KOS_CFLAGS}" LDFLAGS="${KOS_LDFLAGS}" \ LIBS="${KOS_LIBS}" CC="${KOS_CC}" --disable-shared build_lib: libini/Makefile cd ./libini && make include ../../sdk/Makefile.loadable rm-elf: -rm -f $(TARGET) || true -rm -f $(TARGET_LIB) || true install: $(TARGET) $(TARGET_LIB) -rm -f $(DS_BUILD)/modules/$(TARGET) || true -rm -f $(DS_SDK)/lib/$(TARGET_LIB) || true cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/lib/SDL_gui/FastLabel.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" // // A label which favors speed over memory consumption. // GUI_FastLabel::GUI_FastLabel(const char *aname, int x, int y, int w, int h, GUI_Font *afont, const char *s) : GUI_Picture(aname, x, y, w, h), font(afont) { SetTransparent(1); textcolor.r = 255; textcolor.g = 255; textcolor.b = 255; font->IncRef(); SetImage(font->RenderQuality(s, textcolor)); } GUI_FastLabel::~GUI_FastLabel() { font->DecRef(); } void GUI_FastLabel::SetFont(GUI_Font *afont) { if (GUI_ObjectKeep((GUI_Object **) &font, afont)) MarkChanged(); // FIXME: should re-draw the text } void GUI_FastLabel::SetTextColor(int r, int g, int b) { textcolor.r = r; textcolor.g = g; textcolor.b = b; /* FIXME: should re-draw the text in the new color */ } void GUI_FastLabel::SetText(const char *s) { SetImage(font->RenderQuality(s, textcolor)); } <file_sep>/modules/aicaos/install.lua -- @name: OPKG installation script -- @author: SWAT print("DS_OK: AICAOS installed to " .. os.getenv("PATH") .. "\n"); -- Some code after installation... <file_sep>/lib/libparallax/include/context.h /* Parallax for KallistiOS ##version## context.h (c)2002 <NAME> */ #ifndef __PARALLAX_CONTEXT #define __PARALLAX_CONTEXT #include <sys/cdefs.h> __BEGIN_DECLS /** \file Here we implement a "context" system. This handles things like whether face culling is enabled, blending modes, selected texture (or lack thereof), etc. This slows your stuff down a bit but adds a lot of flexibility, so like everything else in Parallax it's optional. */ #include <dc/pvr.h> #include "texture.h" /** Initialize the context system */ void plx_cxt_init(); /** Select a texture for use with the context system. If you delete the texture this has selected and then try to use contexts without setting another texture, you'll probably get some gross garbage on your output. Specify a NULL texture here to disable texturing. */ void plx_cxt_texture(plx_texture_t * txr); /** Set the blending mode to use with the context. What's available is platform dependent, but we have defines for DC below. */ void plx_cxt_blending(int src, int dst); /* Constants for blending modes */ #define PLX_BLEND_ZERO PVR_BLEND_ZERO #define PLX_BLEND_ONE PVR_BLEND_ONE #define PLX_BLEND_DESTCOLOR PVR_BLEND_DESTCOLOR #define PLX_BLEND_INVDESTCOLOR PVR_BLEND_INVDESTCOLOR #define PLX_BLEND_SRCALPHA PVR_BLEND_SRCALPHA #define PLX_BLEND_INVSRCALPHA PVR_BLEND_INVSRCALPHA #define PLX_BLEND_DESTALPHA PVR_BLEND_DESTALPHA #define PLX_BLEND_INVDESTALPHA PVR_BLEND_INVDESTALPHA /** Set the culling mode. */ void plx_cxt_culling(int type); /* Constants for culling modes */ #define PLX_CULL_NONE PVR_CULLING_NONE /**< Show everything */ #define PLX_CULL_CW PVR_CULLING_CW /**< Remove clockwise polys */ #define PLX_CULL_CCW PVR_CULLING_CCW /**< Remove counter-clockwise polys */ /** Set the fog mode. */ void plx_cxt_fog(int type); /* Constants for fog modes */ #define PLX_FOG_NONE PVR_FOG_DISABLE #define PLX_FOG_TABLE PVR_FOG_TABLE /** Submit the selected context for rendering. */ void plx_cxt_send(int list); __END_DECLS #endif /* __PARALLAX_TEXTURE */ <file_sep>/modules/isoldr/Makefile # # ISO Loader module for DreamShell # Copyright (C) 2009-2022 SWAT # TARGET_NAME = isoldr OBJS = module.o exec.o execasm.o DBG_LIBS = -lds -lisofs EXPORTS_FILE = exports.txt VER_MAJOR = 0 VER_MINOR = 8 VER_MICRO = 0 all: rm-elf include ../../sdk/Makefile.loadable rm-elf: -rm -f $(TARGET) module.o install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/src/vmu/vmu.c /**************************** * DreamShell ##version## * * vmu.c * * DreamShell VMU utils * * Created by SWAT * ****************************/ #include <kos.h> #include <string.h> #include "vmu_font.h" inline void vmu_flip_bit(uint8 bitmap[192], uint8 x, uint8 y) /* (0, 0) is upper-left corner */ { if (x < 48 && y < 32) bitmap[6*(31-y)+(5-(x/8))] ^= (1 << (x%8)); } /* static void vmu_invert_bitmap(uint8 bitmap[192]) { int x, y; for (x = 0; x < 48; x++) for (y = 0; y < 32; y++) vmu_flip_bit(bitmap, x, y); }*/ inline void vmu_set_bit(uint8 bitmap[192], uint8 x, uint8 y) /* (0, 0) is upper-left corner */ { if (x < 48 && y < 32) bitmap[6*(31-y)+(5-(x/8))] |= (1 << (x%8)); } static void vmu_draw_char(uint8 bitmap[192], unsigned char c, int x, int y) /* (x, y) is position for upper-left corner of character, (0, 0) is upper-left corner of screen */ { int i, j; if (x < -4 || x > 47 || y < -9 || y > 31) return; for (i = 0; i < 10; i++) { for (j = 0; j < 5; j++) { if (vmufont[(int)c][i] & (0x80 >> j)) vmu_set_bit(bitmap, x+j, y+i); } } } static void vmu_draw_str(uint8 bitmap[192], unsigned char *str, int x, int y) /* (x, y) is position for upper-left corner of string, (0, 0) is upper-left corner of screen */ { int i; if (y < -9 || y > 31) return; for (i = 0; str[i] != '\0'; i++) { if (x < -4) { x += 5; continue; } vmu_draw_char(bitmap, str[i], x, y); x += 5; if (x > 47) break; } } void vmu_draw_string_xy(const char *str, int x, int y) { uint8 bitmap[192]; maple_device_t *mvmu = NULL; mvmu = maple_enum_type(0, MAPLE_FUNC_LCD); if (mvmu) { memset(bitmap, 0, sizeof(bitmap)); vmu_draw_str(bitmap, (uint8*)str, x, y); vmu_draw_lcd(mvmu, bitmap); } } void vmu_draw_string(const char *str) { int i; char msg[32]; char *pmsg = msg; uint8 bitmap[192]; maple_device_t *mvmu = NULL; int len = strlen(str); int c; int x; int y = len <= 10 ? 10 : 5; if(len > 20) { y = 0; } mvmu = maple_enum_type(0, MAPLE_FUNC_LCD); if (mvmu) { memset(bitmap, 0, sizeof(bitmap)); // FIXME: ugly code if(len <= 10) { c = (10 - len); x = len >= 10 ? 0 : ((c / 2) * 5) + ((c % 2) ? 3 : 0); vmu_draw_str(bitmap, (uint8*)str, x, y); } else { strncpy(msg, str, sizeof(msg)); for(i = 0; i < sizeof(msg); i++) { if(msg[i] == '\0') { len = strlen(pmsg); c = (10 - len); x = len >= 10 ? 0 : ((c / 2) * 5) + ((c % 2) ? 3 : 0); vmu_draw_str(bitmap, (uint8*)pmsg, x, y); break; } else if(msg[i] == ' ') { msg[i] = '\0'; len = strlen(pmsg); c = (10 - len); x = len >= 10 ? 0 : ((c / 2) * 5) + ((c % 2) ? 3 : 0); vmu_draw_str(bitmap, (uint8*)pmsg, x, y); y += 10; pmsg += i + 1; } } } vmu_draw_lcd(mvmu, bitmap); } } <file_sep>/src/img/pvr.c /* DreamShell ##version## pvr.c SWAT */ #include "ds.h" /* Open the pvr texture and send it to VRAM */ int pvr_to_img(const char *filename, kos_img_t *rv) { /* set up the files and buffers */ file_t f; char header[32]; uint16 *buffer = NULL; int header_len = 0, color = 0, fmt = 0; /* open the pvr file */ f = fs_open(filename, O_RDONLY); if(f < 0) { ds_printf ("pvr_to_img: Can't open %s\n", filename); return -1; } /* Read the possible 0x00100000 byte header */ fs_read(f, header, 32); if(header[0] == 'G' && header[1] == 'B' && header[2] == 'I' && header[3] == 'X') { /* GBIX = 0x00100000 byte header */ header_len = 32; } else if (header[0] == 'P' && header[1] == 'V' && header[2] == 'R') { /* PVRT = 0x00010000 byte header */ header_len = 16; } /* Move past the header */ fs_seek(f, header_len, SEEK_SET); rv->byte_count = fs_total(f) - header_len; /* Allocate RAM to contain the PVR file */ buffer = (uint16*) memalign(32, rv->byte_count); if (buffer == NULL) { ds_printf("pvr_to_img: Memory error\n"); return -1; } rv->data = (void*) buffer; /* Read the pvr texture data into RAM and close the file */ fs_read(f, buffer, rv->byte_count); fs_close(f); rv->byte_count = (rv->byte_count + 31) & ~31; /* Get PVR Colorspace */ color = (unsigned int)header[header_len-8]; switch(color) { case 0x00: rv->fmt = PVR_TXRFMT_ARGB1555; break; //(bilevel translucent alpha 0,255) case 0x01: rv->fmt = PVR_TXRFMT_RGB565; break; //(non translucent RGB565 ) case 0x02: rv->fmt = PVR_TXRFMT_ARGB4444; break; //(translucent alpha 0-255) case 0x03: rv->fmt = PVR_TXRFMT_YUV422; break; //(non translucent UYVY ) case 0x04: rv->fmt = PVR_TXRFMT_BUMP; break; //(special bump-mapping format) case 0x05: rv->fmt = PVR_TXRFMT_PAL4BPP; break; //(4-bit palleted texture) case 0x06: rv->fmt = PVR_TXRFMT_PAL8BPP; break; //(8-bit palleted texture) default: break; } /* Get PVR Format. Mip-Maps and Palleted Textures not Currently handled */ fmt = (unsigned int)header[header_len-7]; switch(fmt) { case 0x01: rv->fmt |= PVR_TXRFMT_TWIDDLED; break;//SQUARE TWIDDLED //case 0x02: rv->fmt |= SQUARE TWIDDLED & MIPMAP case 0x03: rv->fmt |= PVR_TXRFMT_VQ_ENABLE | PVR_TXRFMT_TWIDDLED; break;//VQ TWIDDLED //case 0x04: rv->fmt |= VQ & MIPMAP //case 0X05: rv->fmt |= 8-BIT CLUT TWIDDLED //case 0X06: rv->fmt |= 4-BIT CLUT TWIDDLED //case 0x07: rv->fmt |= 8-BIT DIRECT TWIDDLED //case 0X08: rv->fmt |= 4-BIT DIRECT TWIDDLED case 0x09: rv->fmt |= PVR_TXRFMT_NONTWIDDLED; break;//RECTANGLE case 0x0B: rv->fmt |= PVR_TXRFMT_STRIDE | PVR_TXRFMT_NONTWIDDLED; break;//RECTANGULAR STRIDE case 0x0D: rv->fmt |= PVR_TXRFMT_TWIDDLED; break;//RECTANGULAR TWIDDLED case 0x10: rv->fmt |= PVR_TXRFMT_VQ_ENABLE | PVR_TXRFMT_NONTWIDDLED; break;//SMALL VQ //case 0x11: pvr.txrFmt = SMALL VQ & MIPMAP //case 0x12: pvr.txrFmt = SQUARE TWIDDLED & MIPMAP default: rv->fmt |= PVR_TXRFMT_NONE; break; } /* Get PVR Texture Width */ if( (unsigned int)header[header_len-4] == 0x08 && (unsigned int)header[header_len-3] == 0x00 ) rv->w = 8; else if( (unsigned int)header[header_len-4] == 0x10 && (unsigned int)header[header_len-3] == 0x00 ) rv->w = 16; else if( (unsigned int)header[header_len-4] == 0x20 && (unsigned int)header[header_len-3] == 0x00 ) rv->w = 32; else if( (unsigned int)header[header_len-4] == 0x40 && (unsigned int)header[header_len-3] == 0x00 ) rv->w = 64; else if( (unsigned int)header[header_len-4] == -0x80 && (unsigned int)header[header_len-3] == 0x00 ) rv->w = 128; else if( (unsigned int)header[header_len-4] == 0x00 && (unsigned int)header[header_len-3] == 0x01 ) rv->w = 256; else if( (unsigned int)header[header_len-4] == 0x00 && (unsigned int)header[header_len-3] == 0x02 ) rv->w = 512; else if( (unsigned int)header[header_len-4] == 0x00 && (unsigned int)header[header_len-3] == 0x04 ) rv->w = 1024; /* Get PVR Texture Height */ if( (unsigned int)header[header_len-2] == 0x08 && (unsigned int)header[header_len-1] == 0x00 ) rv->h = 8; else if( (unsigned int)header[header_len-2] == 0x10 && (unsigned int)header[header_len-1] == 0x00 ) rv->h = 16; else if( (unsigned int)header[header_len-2] == 0x20 && (unsigned int)header[header_len-1] == 0x00 ) rv->h = 32; else if( (unsigned int)header[header_len-2] == 0x40 && (unsigned int)header[header_len-1] == 0x00 ) rv->h = 64; else if( (unsigned int)header[header_len-2] == -0x80 && (unsigned int)header[header_len-1] == 0x00 ) rv->h = 128; else if( (unsigned int)header[header_len-2] == 0x00 && (unsigned int)header[header_len-1] == 0x01 ) rv->h = 256; else if( (unsigned int)header[header_len-2] == 0x00 && (unsigned int)header[header_len-1] == 0x02 ) rv->h = 512; else if( (unsigned int)header[header_len-2] == 0x00 && (unsigned int)header[header_len-1] == 0x04 ) rv->h = 1024; return 0; } <file_sep>/commands/bin2iso/main.c /* BIN2ISO (C) 2000 by DeXT This is a very simple utility to convert a BIN image (either RAW/2352 or Mode2/2336 format) to standard ISO format (2048 b/s). Structure of images are as follows: Mode 1 (2352): Sync (12), Address (3), Mode (1), Data (2048), ECC (288) Mode 2 (2352): Sync (12), Address (3), Mode (1), Subheader (8), Data (2048), ECC (280) Mode 2 (2336): Subheader (8), Data (2048), ECC (280) Mode 2 / 2336 is the same as Mode 2 / 2352 but without header (sync+addr+mode) Sector size is detected by the presence of Sync data. Mode is detected from Mode field. Tip for Mac users: for Mode 2 tracks preserve Subheader. (sub 8 from seek_header and write 2056 bytes per sector) Changelog: 2000-11-16 - Added mode detection for RAW data images (adds Mode2/2352 support) 2007-03-13 - Added input validation checks (Magnus-swe). /* [COPY] --- T2-COPYRIGHT-NOTE-BEGIN --- [COPY] This copyright note is auto-generated by ./scripts/Create-CopyPatch. [COPY] [COPY] T2 SDE: package/.../bin2iso/bin2iso.desc [COPY] Copyright (C) 2006 The T2 SDE Project [COPY] [COPY] More information can be found in the files COPYING and README. [COPY] [COPY] This program is free software; you can redistribute it and/or modify [COPY] it under the terms of the GNU General Public License as published by [COPY] the Free Software Foundation; version 2 of the License. A copy of the [COPY] GNU General Public License can be found in the file COPYING. [COPY] --- T2-COPYRIGHT-NOTE-END --- [I] A Bin to ISO converter [T] The command line program bin2iso converts BIN image files to [T] standard ISO image files. [U] http://mange.dynalias.org/linux/bin2iso/ [A] DeXT <<EMAIL>> [M] <NAME> <<EMAIL>> [C] extra/tool [L] OpenSource [S] Stable [V] 0.4 [D] http://mange.dynalias.org/linux/bin2iso/ [X] Copyright recieved from: [X] http://svn.exactcode.de/t2/trunk/package/filesystem/bin2iso/bin2iso.desc */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "ds.h" #define MAX_FILENAME_LENGTH 20000 /* Uncomment the following line for MAC */ // #define MAC TRUE int main(int argc, char **argv) { FILE *fdest, *fsource; long i, source_length; char buf[2352], destfilename[MAX_FILENAME_LENGTH+10]; int seek_header, seek_ecc, sector_size; const char SYNC_HEADER[12] = { 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }; if(argc < 2) { ds_printf("Usage: bin2iso image.bin [image.iso]\n"); return CMD_NO_ARG; } for(i=1; argv[i]!='\0'; i++) if(strlen(argv[i]) > MAX_FILENAME_LENGTH) { ds_printf("DS_ERROR: Filename too long.\n\nUsage is: bin2iso image.bin [image.iso]\n"); return CMD_ERROR; } if(argc >= 3) strcpy(destfilename, argv[2]); else { strcpy(destfilename, argv[1]); if(strlen(argv[1]) < 5 || strcmp(destfilename+strlen(argv[1])-4, ".bin")) strcpy(destfilename+strlen(argv[1]), ".iso"); else strcpy(destfilename+strlen(argv[1])-4, ".iso"); } if((fsource=fopen(argv[1],"rb"))==NULL) { ds_printf("DS_ERROR: Source file doesnt exist.\n\nUsage is: bin2iso image.bin [image.iso]\n"); return CMD_ERROR; } if((fdest=fopen(destfilename,"wb"))==NULL) { ds_printf("DS_ERROR: Cant write destination file.\n\nUsage is: bin2iso image.bin [image.iso]\n"); return CMD_ERROR; } fread(buf, sizeof(char), 16, fsource); if(memcmp(SYNC_HEADER, buf, 12)) { #ifdef MAC /* MAC */ seek_header = 0; seek_ecc = 280; sector_size = 2336; /* Mode 2 / 2336 */ #else /* Linux and others */ seek_header = 8; seek_ecc = 280; sector_size = 2336; /* Mode 2 / 2336 */ #endif } else switch(buf[15]) { case 2: #ifdef MAC /* MAC */ seek_header = 16; seek_ecc = 280; sector_size = 2352; /* Mode 2 / 2352 */ #else /* Linux and others */ seek_header = 24; seek_ecc = 280; sector_size = 2352; /* Mode 2 / 2352 */ #endif break; case 1: seek_header = 16; seek_ecc = 288; sector_size = 2352; /* Mode 1 / 2352 */ break; default: ds_printf("DS_ERROR: Unsupported track mode"); return CMD_ERROR; } fseek(fsource, 0L, SEEK_END); source_length = ftell(fsource)/sector_size; fseek(fsource, 0L, SEEK_SET); for(i=0; i<source_length; i++) { fseek(fsource, seek_header, SEEK_CUR); #ifdef MAC /* MAC */ fread(buf, sizeof(char), 2048, fsource); /* Mac: change to 2056 for Mode 2 */ fwrite(buf, sizeof(char), 2048, fdest); /* same as above */ #else /* Linux and others */ fread(buf, sizeof(char), 2048, fsource); fwrite(buf, sizeof(char), 2048, fdest); #endif fseek(fsource, seek_ecc, SEEK_CUR); } fclose(fdest); fclose(fsource); return CMD_OK; } <file_sep>/modules/mp3/libmp3/xingmp3/msis.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** msis.c *************************************************** Layer III antialias, ms and is stereo precessing **** is_process assumes never switch from short to long in is region ***** is_process does ms or stereo in "forbidded sf regions" //ms_mode = 0 lr[0][i][0] = 1.0f; lr[0][i][1] = 0.0f; // ms_mode = 1, in is bands is routine does ms processing lr[1][i][0] = 1.0f; lr[1][i][1] = 1.0f; ******************************************************************/ #include <float.h> #include <math.h> #include <string.h> #include "L3.h" #include "mhead.h" /* The functions are different than their prototypes, by design */ typedef float ARRAY2[2]; typedef float ARRAY8_2[8][2]; /* nBand[0] = long, nBand[1] = short */ /* intensity stereo */ /* if ms mode quant pre-scales all values by 1.0/sqrt(2.0) ms_mode in table compensates */ /* intensity stereo MPEG2 */ /* lr2[intensity_scale][ms_mode][sflen_offset+sf][left/right] */ typedef float ARRAY2_64_2[2][64][2]; typedef float ARRAY64_2[64][2]; #ifdef ASM_X86 extern void antialias_asm(float x[], int n, float *t); #endif /* ASM_X86 */ /*===============================================================*/ ARRAY2 *alias_init_addr(MPEG *m) { return m->cupl.csa; } /*-----------------------------------------------------------*/ ARRAY8_2 *msis_init_addr(MPEG *m) { /*------- pi = 4.0*atan(1.0); t = pi/12.0; for(i=0;i<7;i++) { s = sin(i*t); c = cos(i*t); // ms_mode = 0 m->cupl.lr[0][i][0] = (float)(s/(s+c)); m->cupl.lr[0][i][1] = (float)(c/(s+c)); // ms_mode = 1 m->cupl.lr[1][i][0] = (float)(sqrt(2.0)*(s/(s+c))); m->cupl.lr[1][i][1] = (float)(sqrt(2.0)*(c/(s+c))); } //sf = 7 //ms_mode = 0 m->cupl.lr[0][i][0] = 1.0f; m->cupl.lr[0][i][1] = 0.0f; // ms_mode = 1, in is bands is routine does ms processing m->cupl.lr[1][i][0] = 1.0f; m->cupl.lr[1][i][1] = 1.0f; ------------*/ return m->cupl.lr; } /*-------------------------------------------------------------*/ ARRAY2_64_2 *msis_init_addr_MPEG2(MPEG *m) { return m->cupl.lr2; } /*===============================================================*/ void antialias(MPEG *m, float x[], int n) { #ifdef ASM_X86 antialias_asm(x, n, (float *)m->cupl.csa); #else int i, k; float a, b; for (k = 0; k < n; k++) { for (i = 0; i < 8; i++) { a = x[17 - i]; b = x[18 + i]; x[17 - i] = a * m->cupl.csa[i][0] - b * m->cupl.csa[i][1]; x[18 + i] = b * m->cupl.csa[i][0] + a * m->cupl.csa[i][1]; } x += 18; } #endif } /*===============================================================*/ void ms_process(float x[][1152], int n) /* sum-difference stereo */ { int i; float xl, xr; /*-- note: sqrt(2) done scaling by dequant ---*/ for (i = 0; i < n; i++) { xl = x[0][i] + x[1][i]; xr = x[0][i] - x[1][i]; x[0][i] = xl; x[1][i] = xr; } return; } /*===============================================================*/ void is_process_MPEG1(MPEG *vm, float x[][1152], /* intensity stereo */ SCALEFACT * sf, CB_INFO cb_info[2], /* [ch] */ int nsamp, int ms_mode) { int i, j, n, cb, w; float fl, fr; int m; int isf; float fls[3], frs[3]; int cb0; cb0 = cb_info[1].cbmax; /* start at end of right */ i = vm->cupl.sfBandIndex[cb_info[1].cbtype][cb0]; cb0++; m = nsamp - i; /* process to len of left */ if (cb_info[1].cbtype) goto short_blocks; /*------------------------*/ /* long_blocks: */ for (cb = cb0; cb < 21; cb++) { isf = sf->l[cb]; n = vm->cupl.nBand[0][cb]; fl = vm->cupl.lr[ms_mode][isf][0]; fr = vm->cupl.lr[ms_mode][isf][1]; for (j = 0; j < n; j++, i++) { if (--m < 0) goto exit; x[1][i] = fr * x[0][i]; x[0][i] = fl * x[0][i]; } } return; /*------------------------*/ short_blocks: for (cb = cb0; cb < 12; cb++) { for (w = 0; w < 3; w++) { isf = sf->s[w][cb]; fls[w] = vm->cupl.lr[ms_mode][isf][0]; frs[w] = vm->cupl.lr[ms_mode][isf][1]; } n = vm->cupl.nBand[1][cb]; for (j = 0; j < n; j++) { m -= 3; if (m < 0) goto exit; x[1][i] = frs[0] * x[0][i]; x[0][i] = fls[0] * x[0][i]; x[1][1 + i] = frs[1] * x[0][1 + i]; x[0][1 + i] = fls[1] * x[0][1 + i]; x[1][2 + i] = frs[2] * x[0][2 + i]; x[0][2 + i] = fls[2] * x[0][2 + i]; i += 3; } } exit: return; } /*===============================================================*/ void is_process_MPEG2(MPEG *vm, float x[][1152], /* intensity stereo */ SCALEFACT * sf, CB_INFO cb_info[2], /* [ch] */ IS_SF_INFO * is_sf_info, int nsamp, int ms_mode) { int i, j, k, n, cb, w; float fl, fr; int m; int isf; int il[21]; int tmp; int r; ARRAY2 *lr; int cb0, cb1; memset(il, 0, sizeof(il)); lr = vm->cupl.lr2[is_sf_info->intensity_scale][ms_mode]; if (cb_info[1].cbtype) goto short_blocks; /*------------------------*/ /* long_blocks: */ cb0 = cb_info[1].cbmax; /* start at end of right */ i = vm->cupl.sfBandIndex[0][cb0]; m = nsamp - i; /* process to len of left */ /* gen sf info */ for (k = r = 0; r < 3; r++) { tmp = (1 << is_sf_info->slen[r]) - 1; for (j = 0; j < is_sf_info->nr[r]; j++, k++) il[k] = tmp; } for (cb = cb0 + 1; cb < 21; cb++) { isf = il[cb] + sf->l[cb]; fl = lr[isf][0]; fr = lr[isf][1]; n = vm->cupl.nBand[0][cb]; for (j = 0; j < n; j++, i++) { if (--m < 0) goto exit; x[1][i] = fr * x[0][i]; x[0][i] = fl * x[0][i]; } } return; /*------------------------*/ short_blocks: for (k = r = 0; r < 3; r++) { tmp = (1 << is_sf_info->slen[r]) - 1; for (j = 0; j < is_sf_info->nr[r]; j++, k++) il[k] = tmp; } for (w = 0; w < 3; w++) { cb0 = cb_info[1].cbmax_s[w]; /* start at end of right */ i = vm->cupl.sfBandIndex[1][cb0] + w; cb1 = cb_info[0].cbmax_s[w]; /* process to end of left */ for (cb = cb0 + 1; cb <= cb1; cb++) { isf = il[cb] + sf->s[w][cb]; fl = lr[isf][0]; fr = lr[isf][1]; n = vm->cupl.nBand[1][cb]; for (j = 0; j < n; j++) { x[1][i] = fr * x[0][i]; x[0][i] = fl * x[0][i]; i += 3; } } } exit: return; } /*===============================================================*/ <file_sep>/lib/SDL_image/SegaPVRImage.h // // SegaPVRImage.h // SEGAPVR // // Created by <NAME> on 4/13/14. // Copyright (c) 2014 yev. All rights reserved. // #ifndef SEGAPVRIMAGE_H #define SEGAPVRIMAGE_H enum TextureTypeMasks { TTM_Twiddled = 0x01, TTM_TwiddledMipMaps = 0x02, TTM_VectorQuantized = 0x03, TTM_VectorQuantizedMipMaps = 0x04, TTM_VectorQuantizedCustomCodeBook = 0x10, TTM_VectorQuantizedCustomCodeBookMipMaps = 0x11, TTM_Raw = 0x0B, TTM_RawNonSquare = 0x09, TTM_TwiddledNonSquare = 0x0D }; enum TextureFormatMasks { TFM_ARGB1555 = 0x00, TFM_RGB565, TFM_ARGB4444, TFM_YUV422 }; #pragma pack(push,4) struct GBIXHeader // Global index header { unsigned int version; // ID, "GBIX" in ASCII unsigned int nextTagOffset; // Bytes number to the next tag unsigned long long globalIndex; }; #pragma pack(pop) #pragma pack(push,4) struct PVRTHeader { unsigned int version; // ID, "PVRT" in ASCII unsigned int textureDataSize; unsigned int textureAttributes; unsigned short width; // Width of the texture. unsigned short height; // Height of the texture. }; #pragma pack(pop) extern void BuildTwiddleTable(); extern int LoadPVRFromFile(const char* filename, unsigned char** image, unsigned long int* imageSize); extern unsigned int ReadPVRHeader(unsigned char* srcData, struct PVRTHeader* pvrtHeader); extern int DecodePVR(unsigned char* srcData, const struct PVRTHeader* pvrtHeader, unsigned char* dstData); #endif <file_sep>/applications/iso_loader/modules/app_module.h /* DreamShell ##version## module.c - ISO Loader app module Copyright (C) 2011 Superdefault Copyright (C) 2011-2023 SWAT */ #include <ds.h> void isoLoader_DefaultPreset(); int isoLoader_LoadPreset(); int isoLoader_SavePreset(); void isoLoader_ResizeUI(); void isoLoader_toggleMemory(GUI_Widget *widget); void isoLoader_toggleBootMode(GUI_Widget *widget); void isoLoader_toggleIconSize(GUI_Widget *widget); void isoLoader_Rotate_Image(GUI_Widget *widget); void isoLoader_ShowPage(GUI_Widget *widget); void isoLoader_ShowSettings(GUI_Widget *widget); void isoLoader_ShowExtensions(GUI_Widget *widget); void isoLoader_ShowGames(GUI_Widget *widget); void isoLoader_ShowLink(GUI_Widget *widget); void isoLoader_MakeShortcut(GUI_Widget *widget); void isoLoader_toggleIconSize(GUI_Widget *widget); void isoLoader_toggleLinkName(GUI_Widget *widget); void isoLoader_toggleHideName(GUI_Widget *widget); void isoLoader_toggleOptions(GUI_Widget *widget); void isoLoader_togglePatchAddr(GUI_Widget *widget); /* Switch to the selected volume */ void isoLoader_SwitchVolume(void *dir); void isoLoader_toggleOS(GUI_Widget *widget); void isoLoader_toggleAsync(GUI_Widget *widget); void isoLoader_toggleDMA(GUI_Widget *widget); void isoLoader_toggleCDDA(GUI_Widget *widget); void isoLoader_toggleHeap(GUI_Widget *widget); void isoLoader_toggleMemory(GUI_Widget *widget); void isoLoader_toggleBootMode(GUI_Widget *widget); void isoLoader_toggleExtension(GUI_Widget *widget); void isoLoader_Run(GUI_Widget *widget); void isoLoader_ItemClick(dirent_fm_t *fm_ent); void isoLoader_ItemContextClick(dirent_fm_t *fm_ent); void isoLoader_Init(App_t *app); void isoLoader_ResizeUI(); void isoLoader_Shutdown(App_t *app); void isoLoader_Exit(GUI_Widget *widget); <file_sep>/firmware/aica/codec/ir.c /* * based on <NAME> Code (http://www.mikrocontroller.net/topic/12216) */ #include "AT91SAM7S64.h" #include "Board.h" #include "ir.h" #include "systime.h" #include "interrupt_utils.h" static unsigned int ir_address(unsigned int received); static unsigned int ir_command(unsigned int received); unsigned int rc5_bit; // bit value unsigned int rc5_time; // count bit time unsigned int rc5_tmp; // shift bits in volatile unsigned int rc5_data; // store received data #define IRINPUT (*AT91C_PIOA_PDSR) #define IRPIN 30 #define RC5TIME 1.778e-3 // 1.778msec #define PULSE_MIN (unsigned int)((float)TCK * RC5TIME * 0.4 + 0.5) #define PULSE_1_2 (unsigned int)((float)TCK * RC5TIME * 0.8 + 0.5) #define PULSE_MAX (unsigned int)((float)TCK * RC5TIME * 1.2 + 0.5) void ir_receive() { unsigned int tmp = rc5_tmp; // for faster access if( ++rc5_time > PULSE_MAX ){ // count pulse time // only if 14 bits received if( !(tmp & 0x4000) && tmp & 0x2000 ) { // check for correct address (CD player, see http://www.sbprojects.com/knowledge/ir/rc5.htm) if(ir_address(tmp) >= 0x14 && ir_address(tmp) <= 0x20) { rc5_data = tmp; } } tmp = 0; } if( (rc5_bit ^ IRINPUT) & 1<<IRPIN ){ // change detect rc5_bit = ~rc5_bit; // 0x00 -> 0xFF -> 0x00 if( rc5_time < PULSE_MIN ) // to short tmp = 0; if( !tmp || rc5_time > PULSE_1_2 ){ // start or long pulse time if( !(tmp & 0x4000) ) // not to many bits tmp <<= 1; // shift if( !(rc5_bit & 1<<IRPIN) ) // inverted bit tmp |= 1; // insert new bit rc5_time = 0; // count next pulse time } } rc5_tmp = tmp; } // return last received command; -1 if no new command is available int ir_get_cmd(void) { int x; unsigned state; state = disableIRQ(); if (rc5_data) { x = ir_command(rc5_data); rc5_data = 0; } else { x = -1; } restoreIRQ(state); return x; } void ir_init(void) { // enable PIO *AT91C_PIOA_PER = (1<<IRPIN); // disable output *AT91C_PIOA_ODR = (1<<IRPIN); } static unsigned int ir_address(unsigned int received) { // 5 address bits, starting from bit 7 return (received >> 6) & 0x1F; } static unsigned int ir_command(unsigned int received) { // 6 command bits return received & 0x3F; } <file_sep>/applications/settings/modules/module.c /* DreamShell ##version## module.c - Settings app module Copyright (C)2016-2022 SWAT */ #include "ds.h" #include <drivers/rtc.h> DEFAULT_MODULE_EXPORTS(app_settings); /* The first child of panel with checkboxes it's a label */ #define WIDGET_VALUE_OFFSET 1 enum { NATIVE_MODE_AUTO = 0, NATIVE_MODE_PAL, NATIVE_MODE_NTSC, NATIVE_MODE_VGA }; enum { SCREEN_MODE_4_3 = 0, SCREEN_MODE_3_2, SCREEN_MODE_16_10, SCREEN_MOVE_16_9 }; enum { SCREEN_FILTER_AUTO = 0, SCREEN_FILTER_NEAREST, SCREEN_FILTER_BILINEAR, SCREEN_FILTER_TRILINEAR }; static struct { App_t *app; Settings_t *settings; GUI_Widget *pages; GUI_Widget *sysdate[6]; } self; static void SetupVideoSettings(); static void SetupBootSettings(); static int UncheckBesides(GUI_Widget *widget, char *label) { int index = 0; GUI_Widget *panel, *child; if(label) { panel = widget; for(int i = 0; i < GUI_ContainerGetCount(panel); ++i) { widget = GUI_ContainerGetChild(panel, i); GUI_Widget *l = GUI_ToggleButtonGetCaption(widget); if(!strcasecmp(label, GUI_LabelGetText(l))) { break; } } } else { panel = GUI_WidgetGetParent(widget); } if(!GUI_WidgetGetState(widget)) { GUI_WidgetSetState(widget, 1); } for(int i = 0; i < GUI_ContainerGetCount(panel); ++i) { child = GUI_ContainerGetChild(panel, i); if(widget != child) { GUI_WidgetSetState(child, 0); } else { index = i; } } return index - WIDGET_VALUE_OFFSET; } void SettingsApp_Init(App_t *app) { if(app != NULL) { memset(&self, 0, sizeof(self)); self.app = app; self.settings = GetSettings(); self.pages = APP_GET_WIDGET("pages"); self.sysdate[0] = APP_GET_WIDGET("year"); self.sysdate[1] = APP_GET_WIDGET("month"); self.sysdate[2] = APP_GET_WIDGET("day"); self.sysdate[3] = APP_GET_WIDGET("hours"); self.sysdate[4] = APP_GET_WIDGET("minute"); SetupVideoSettings(); SetupBootSettings(); } } void SettingsApp_ShowPage(GUI_Widget *widget) { const char *object_name, *name_ptr; char name[64]; size_t size; ScreenFadeOut(); object_name = GUI_ObjectGetName((GUI_Object *)widget); name_ptr = strchr(object_name, '-'); size = (name_ptr - object_name); if(size < sizeof(name) - 5) { strncpy(name, object_name, size); strncpy(name + size, "-page", 6); thd_sleep(200); GUI_CardStackShow(self.pages, name); } ScreenFadeIn(); } void SettingsApp_ResetSettings(GUI_Widget *widget) { ResetSettings(); SetupBootSettings(); SetupVideoSettings(); SetScreenMode(self.settings->video.virt_width, self.settings->video.virt_height, 0.0f, 0.0f, 1.0f); SetScreenFilter(self.settings->video.tex_filter); } void SettingsApp_ToggleNativeMode(GUI_Widget *widget) { int value = UncheckBesides(widget, NULL); switch(value) { case NATIVE_MODE_AUTO: memset(&self.settings->video.mode, 0, sizeof(self.settings->video.mode)); // SetVideoMode(-1); break; case NATIVE_MODE_PAL: memcpy(&self.settings->video.mode, &vid_builtin[DM_640x480_PAL_IL], sizeof(self.settings->video.mode)); // SetVideoMode(DM_640x480_PAL_IL); break; case NATIVE_MODE_NTSC: memcpy(&self.settings->video.mode, &vid_builtin[DM_640x480_NTSC_IL], sizeof(self.settings->video.mode)); // SetVideoMode(DM_640x480_NTSC_IL); break; case NATIVE_MODE_VGA: memcpy(&self.settings->video.mode, &vid_builtin[DM_640x480_VGA], sizeof(self.settings->video.mode)); // SetVideoMode(DM_640x480_VGA); break; default: return; } } void SettingsApp_ToggleScreenMode(GUI_Widget *widget) { int value = UncheckBesides(widget, NULL); switch(value) { case SCREEN_MODE_4_3: self.settings->video.virt_width = 640; break; case SCREEN_MODE_3_2: self.settings->video.virt_width = 720; break; case SCREEN_MODE_16_10: self.settings->video.virt_width = 768; break; case SCREEN_MOVE_16_9: self.settings->video.virt_width = 854; break; default: return; } self.settings->video.virt_height = 480; SetScreenMode(self.settings->video.virt_width, self.settings->video.virt_height, 0.0f, 0.0f, 1.0f); } void SettingsApp_ToggleScreenFilter(GUI_Widget *widget) { int value = UncheckBesides(widget, NULL); switch(value) { case SCREEN_FILTER_AUTO: self.settings->video.tex_filter = -1; break; case SCREEN_FILTER_NEAREST: self.settings->video.tex_filter = PVR_FILTER_NEAREST; break; case SCREEN_FILTER_BILINEAR: self.settings->video.tex_filter = PVR_FILTER_BILINEAR; break; // case SCREEN_FILTER_TRILINEAR: // self.settings->video.tex_filter = PVR_FILTER_TRILINEAR1; // break; default: return; } SetScreenFilter(self.settings->video.tex_filter); } static void SetupVideoSettings() { GUI_Widget *panel; int value = NATIVE_MODE_AUTO; panel = APP_GET_WIDGET("display-native-mode"); if(self.settings->video.mode.width > 0) { for(int i = 0; i < DM_SENTINEL; ++i) { if(!memcmp(&self.settings->video.mode, &vid_builtin[i], sizeof(vid_builtin[i]))) { switch(i) { case DM_640x480_PAL_IL: value = NATIVE_MODE_PAL; break; case DM_640x480_NTSC_IL: value = NATIVE_MODE_NTSC; break; case DM_640x480_VGA: value = NATIVE_MODE_VGA; break; default: break; } break; } } } UncheckBesides(GUI_ContainerGetChild(panel, value + WIDGET_VALUE_OFFSET), NULL); panel = APP_GET_WIDGET("display-screen-mode"); switch(self.settings->video.virt_width) { case 640: value = SCREEN_MODE_4_3; break; case 720: value = SCREEN_MODE_3_2; break; case 854: value = SCREEN_MOVE_16_9; break; default: value = SCREEN_MODE_4_3; break; } UncheckBesides(GUI_ContainerGetChild(panel, value + WIDGET_VALUE_OFFSET), NULL); panel = APP_GET_WIDGET("display-screen-filter"); switch(self.settings->video.tex_filter) { case -1: value = SCREEN_FILTER_AUTO; break; case PVR_FILTER_NEAREST: value = SCREEN_FILTER_AUTO; break; case PVR_FILTER_BILINEAR: value = SCREEN_FILTER_AUTO; break; // case PVR_FILTER_TRILINEAR1: // value = SCREEN_FILTER_TRILINEAR; // break; default: value = SCREEN_FILTER_AUTO; break; } UncheckBesides(GUI_ContainerGetChild(panel, value + WIDGET_VALUE_OFFSET), NULL); } void SettingsApp_ToggleApp(GUI_Widget *widget) { UncheckBesides(widget, NULL); strncpy(self.settings->app, GUI_ObjectGetName((GUI_Object *)widget), sizeof(self.settings->app)); } void SettingsApp_ToggleRoot(GUI_Widget *widget) { UncheckBesides(widget, NULL); GUI_Widget *label = GUI_ToggleButtonGetCaption(widget); if(label) { char *value = GUI_LabelGetText(label); strncpy(self.settings->root, value, sizeof(self.settings->root)); } } void SettingsApp_ToggleStartup(GUI_Widget *widget) { UncheckBesides(widget, NULL); GUI_Widget *label = GUI_ToggleButtonGetCaption(widget); if(label) { char *value = GUI_LabelGetText(label); strncpy(self.settings->startup, value, sizeof(self.settings->root)); } } static void SetupBootSettings() { Item_list_t *applist = GetAppList(); GUI_Widget *panel = APP_GET_WIDGET("boot-root"); GUI_Font *font = APP_GET_FONT("arial"); GUI_Surface *check_on = APP_GET_SURFACE("check-on"); GUI_Surface *check_on_hl = APP_GET_SURFACE("check-on-hl"); GUI_Surface *check_off = APP_GET_SURFACE("check-off"); GUI_Surface *check_off_hl = APP_GET_SURFACE("check-off-hl"); if(self.settings->root[0] == 0) { UncheckBesides(GUI_ContainerGetChild(panel, WIDGET_VALUE_OFFSET), NULL); } else { UncheckBesides(panel, self.settings->root); } panel = APP_GET_WIDGET("boot-startup"); UncheckBesides(panel, self.settings->startup); panel = APP_GET_WIDGET("boot-app"); if(applist && panel) { if(GUI_ContainerGetCount(panel) > 1) { UncheckBesides(panel, self.settings->app); return; } Item_t *item = listGetItemFirst(applist); while(item != NULL) { App_t *app = (App_t *)item->data; item = listGetItemNext(item); SDL_Rect ts = GUI_FontGetTextSize(font, app->name); int w = ts.w + GUI_SurfaceGetWidth(check_on) + 16; int h = GUI_SurfaceGetHeight(check_on) + 6; GUI_Widget *b = GUI_ToggleButtonCreate(app->name, 0, 0, w, h); GUI_ToggleButtonSetOnNormalImage(b, check_on); GUI_ToggleButtonSetOnHighlightImage(b, check_on_hl); GUI_ToggleButtonSetOffNormalImage(b, check_off); GUI_ToggleButtonSetOffHighlightImage(b, check_off_hl); GUI_Callback *c = GUI_CallbackCreate((GUI_CallbackFunction *)SettingsApp_ToggleApp, NULL, b); GUI_ToggleButtonSetClick(b, c); GUI_ObjectDecRef((GUI_Object *) c); if(!strncasecmp(app->name, self.settings->app, sizeof(app->name))) { GUI_WidgetSetState(b, 1); } else { GUI_WidgetSetState(b, 0); } GUI_Widget *l = GUI_LabelCreate(app->name, 22, 0, w, h - 5, font, app->name); GUI_LabelSetTextColor(l, 0, 0, 0); GUI_WidgetSetAlign(l, WIDGET_HORIZ_LEFT | WIDGET_VERT_CENTER); GUI_ButtonSetCaption(b, l); GUI_ObjectDecRef((GUI_Object *) l); GUI_ContainerAdd(panel, b); GUI_ObjectDecRef((GUI_Object *) b); } } } void SettingsApp_TimeChange(GUI_Widget *widget) { struct tm time; if(strcmp(GUI_ObjectGetName(widget),"get-time") == 0) { char buf[5]; rtc_gettimeutc(&time); sprintf(buf,"%04d",time.tm_year + 1900); GUI_TextEntrySetText(self.sysdate[0], buf); sprintf(buf,"%02d",time.tm_mon + 1); GUI_TextEntrySetText(self.sysdate[1], buf); sprintf(buf,"%02d",time.tm_mday); GUI_TextEntrySetText(self.sysdate[2], buf); sprintf(buf,"%02d",time.tm_hour); GUI_TextEntrySetText(self.sysdate[3], buf); sprintf(buf,"%02d",time.tm_min); GUI_TextEntrySetText(self.sysdate[4], buf); } else if(strcmp(GUI_ObjectGetName(widget),"set-time") == 0) { time.tm_sec = 0; time.tm_min = atoi(GUI_TextEntryGetText(self.sysdate[4])); time.tm_hour = atoi(GUI_TextEntryGetText(self.sysdate[3])); time.tm_mday = atoi(GUI_TextEntryGetText(self.sysdate[2])); time.tm_mon = atoi(GUI_TextEntryGetText(self.sysdate[1])) - 1; time.tm_year = atoi(GUI_TextEntryGetText(self.sysdate[0])) - 1900; rtc_settimeutc(&time); } } void SettingsApp_Time(GUI_Widget *widget) { char wname[32]; sprintf(wname,"%s",GUI_ObjectGetName(widget)); int entryvar = atoi(GUI_TextEntryGetText(widget)); switch (wname[strlen(wname)-1]) { case 'r': if(entryvar < 1998) GUI_TextEntrySetText(widget, "1998"); if(entryvar > 2086) GUI_TextEntrySetText(widget, "2086"); break; case 'h': if(entryvar < 1) GUI_TextEntrySetText(widget, "01"); if(entryvar > 12) GUI_TextEntrySetText(widget, "12"); break; case 'y': if(entryvar < 1) GUI_TextEntrySetText(widget, "01"); if(entryvar > 31) GUI_TextEntrySetText(widget, "31"); break; case 's': if(entryvar < 1) GUI_TextEntrySetText(widget, "00"); if(entryvar > 23) GUI_TextEntrySetText(widget, "23"); break; case 'e': if(entryvar < 1) GUI_TextEntrySetText(widget, "00"); if(entryvar > 59) GUI_TextEntrySetText(widget, "59"); break; } } void SettingsApp_Time_Clr(GUI_Widget *widget) { GUI_TextEntrySetText(widget, ""); } <file_sep>/include/isoldr.h /** * \file isoldr.h * \brief DreamShell ISO loader * \date 2009-2023 * \author SWAT www.dc-swat.ru */ #ifndef _DS_ISOLDR_H_ #define _DS_ISOLDR_H_ #include <arch/types.h> #include <dc/cdrom.h> #include "isofs/isofs.h" #include "isofs/ciso.h" /** * Loader params size */ #define ISOLDR_PARAMS_SIZE 1024 /** * Maximum memory usage by loader and params */ #define ISOLDR_MAX_MEM_USAGE 32768 /** * It's a default loader addresses * * 0x8c004000 - Can't be used with dcl loader * * You can find more suitable by own experience. */ #define ISOLDR_DEFAULT_ADDR 0x8ce00000 #define ISOLDR_DEFAULT_ADDR_LOW 0x8c004000 #define ISOLDR_DEFAULT_ADDR_HIGH 0x8cfe8000 #define ISOLDR_DEFAULT_ADDR_MIN 0x8c000100 /** * Supported devices */ #define ISOLDR_DEV_GDROM "cd" #define ISOLDR_DEV_SDCARD "sd" #define ISOLDR_DEV_G1ATA "ide" #define ISOLDR_DEV_DCLOAD "dcl" /** * Supported types */ #define ISOLDR_TYPE_DEFAULT "" #define ISOLDR_TYPE_EXTENDED "ext" #define ISOLDR_TYPE_FULL "full" /** * Boot mode */ typedef enum isoldr_boot_mode { BOOT_MODE_DIRECT = 0, BOOT_MODE_IPBIN = 1, /* Bootstrap 1 */ BOOT_MODE_IPBIN_TRUNC /* Bootstrap 2 */ } isoldr_boot_mode_t; /** * Executable types */ typedef enum isoldr_exec_type { BIN_TYPE_AUTO = 0, BIN_TYPE_KOS = 1, BIN_TYPE_KATANA, BIN_TYPE_WINCE } isoldr_exec_type_t; /** * Executable info */ typedef struct isoldr_exec_info { uint32 lba; /* File LBA */ uint32 size; /* Size in bytes */ uint32 addr; /* Memory address */ char file[16]; /* File name */ uint32 type; /* See isoldr_exec_type_t */ } isoldr_exec_info_t; /** * Heap memory modes */ typedef enum isoldr_heap_mode { HEAP_MODE_AUTO = 0, HEAP_MODE_BEHIND = 1, HEAP_MODE_INGAME, HEAP_MODE_MAPLE, HEAP_MODE_SPECIFY = 0x8c000000 // +offset } isoldr_heap_mode_t; /** * CDDA modes */ typedef enum isoldr_cdda_mode { CDDA_MODE_DISABLED = 0, CDDA_MODE_DMA_TMU2 = 1, CDDA_MODE_DMA_TMU1, CDDA_MODE_SQ_TMU2, CDDA_MODE_SQ_TMU1 } isoldr_cdda_mode_t; typedef struct isoldr_info { char magic[12]; /* isoldr magic code - 'DSISOLDRXXX' where XXX is version */ uint32 image_type; /* See isofs_image_type_t */ char image_file[256]; /* Full path to image */ char image_second[12]; /* Second data track file for the multitrack GDI image */ char fs_dev[8]; /* Device name, see supported devices */ char fs_type[8]; /* Extend device name */ uint32 fs_part; /* Partition on device (0-3), only for SD and IDE devices */ CISO_header_t ciso; /* CISO header for CSO/ZSO images */ CDROM_TOC toc; /* Table of content */ uint32 track_offset; /* Data track offset, for the CDI images only */ uint32 track_lba[2]; /* Data track LBA, second value for the multitrack GDI image */ uint32 sector_size; /* Data track sector size */ uint32 boot_mode; /* See isoldr_boot_mode_t */ uint32 emu_cdda; /* Emulate CDDA audio. See isoldr_cdda_mode_t */ uint32 emu_async; /* Emulate async data transfer (value is sectors count per frame) */ uint32 use_dma; /* Use DMA data transfer for G1-bus devices (GD drive and IDE) */ uint32 fast_boot; /* Don't show any info on screen */ isoldr_exec_info_t exec; /* Executable info */ uint32 gdtex; /* Memory address for GD texture (draw it on screen) */ uint32 patch_addr[2]; /* Memory addresses for patching every frame */ uint32 patch_value[2]; /* Values for patching */ uint32 heap; /* Memory address or mode for heap. See isoldr_heap_mode_t */ uint32 use_irq; /* Use IRQ hooking */ uint32 emu_vmu; /* Emulate VMU on port A1. Set number for VMU dump or zero for disabled. */ uint32 syscalls; /* Memory address for syscalls binary or 1 for auto load. */ uint32 scr_hotkey; /* Creating screenshots by hotkey (zero for disabled). */ uint32 cdda_offset[45]; /* CDDA tracks offset, only for CDI images */ } isoldr_info_t; /** * Get some info from CD image and fill info structure */ isoldr_info_t *isoldr_get_info(const char *file, int use_gdtex); /** * Execute loader for specified device at any valid memory address */ void isoldr_exec(isoldr_info_t *info, uint32 addr); #endif /* ifndef _DS_ISOLDR_H_*/ <file_sep>/modules/bzip2/bzip2/Makefile TARGET = libbz2_1.0.6.a OBJS= blocksort.o \ huffman.o \ crctable.o \ randtable.o \ compress.o \ decompress.o \ bzlib.o KOS_CFLAGS += -I../include/bzlib #-D_FILE_OFFSET_BITS=64 include $(KOS_BASE)/ds/sdk/Makefile.library <file_sep>/lib/SDL_Console/src/Makefile # Makefile created by SWAT # http://www.dc-swat.ru TARGET = libSDL_Console.a OBJS = SDL_console.o DT_drawtext.o internal.o KOS_CFLAGS += -I$(KOS_BASE)/../kos-ports/include/SDL -I../include -DHAVE_SDLIMAGE include ../../Makefile.prefab <file_sep>/modules/mp3/libmp3/xingmp3/isbtb.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** isbtb.c *************************************************** include to isbt.c MPEG audio decoder, integer dct and window, 8 bit output ******************************************************************/ /* asm is quick only, c code does not need separate window for right */ /* full is opposite of quick */ #ifdef FULL_INTEGER #define i_windowB_dual_right i_windowB_dual #define i_windowB16_dual_right i_windowB16_dual #define i_windowB8_dual_right i_windowB8_dual #endif void i_windowB(WININT * vbuf, int vb_ptr, unsigned char *pcm); void i_windowB_dual(WININT * vbuf, int vb_ptr, unsigned char *pcm); void i_windowB_dual_right(WININT * vbuf, int vb_ptr, unsigned char *pcm); void i_windowB16(WININT * vbuf, int vb_ptr, unsigned char *pcm); void i_windowB16_dual(WININT * vbuf, int vb_ptr, unsigned char *pcm); void i_windowB16_dual_right(WININT * vbuf, int vb_ptr, unsigned char *pcm); void i_windowB8(WININT * vbuf, int vb_ptr, unsigned char *pcm); void i_windowB8_dual(WININT * vbuf, int vb_ptr, unsigned char *pcm); void i_windowB8_dual_right(WININT * vbuf, int vb_ptr, unsigned char *pcm); /*==============================================================*/ /*==============================================================*/ /*==============================================================*/ void i_sbtB_mono(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct32(sample, vbuf + vb_ptr); i_windowB(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ void i_sbtB_dual(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct32_dual(sample, vbuf + vb_ptr); i_dct32_dual(sample + 1, vbuf2 + vb_ptr); i_windowB_dual(vbuf, vb_ptr, pcm); i_windowB_dual_right(vbuf2, vb_ptr, pcm + 1); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 64; } } /*------------------------------------------------------------*/ /* convert dual to mono */ void i_sbtB_dual_mono(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct32_dual_mono(sample, vbuf + vb_ptr); i_windowB(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /* convert dual to left */ void i_sbtB_dual_left(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct32_dual(sample, vbuf + vb_ptr); i_windowB(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /* convert dual to right */ void i_sbtB_dual_right(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; sample++; /* point to right chan */ for (i = 0; i < n; i++) { i_dct32_dual(sample, vbuf + vb_ptr); i_windowB(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /*---------------- 16 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ void i_sbtB16_mono(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct16(sample, vbuf + vb_ptr); i_windowB16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void i_sbtB16_dual(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct16_dual(sample, vbuf + vb_ptr); i_dct16_dual(sample + 1, vbuf2 + vb_ptr); i_windowB16_dual(vbuf, vb_ptr, pcm); i_windowB16_dual_right(vbuf2, vb_ptr, pcm + 1); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 32; } } /*------------------------------------------------------------*/ void i_sbtB16_dual_mono(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct16_dual_mono(sample, vbuf + vb_ptr); i_windowB16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void i_sbtB16_dual_left(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct16_dual(sample, vbuf + vb_ptr); i_windowB16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void i_sbtB16_dual_right(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; sample++; for (i = 0; i < n; i++) { i_dct16_dual(sample, vbuf + vb_ptr); i_windowB16(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ /*---------------- 8 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ void i_sbtB8_mono(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct8(sample, vbuf + vb_ptr); i_windowB8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void i_sbtB8_dual(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct8_dual(sample, vbuf + vb_ptr); i_dct8_dual(sample + 1, vbuf2 + vb_ptr); i_windowB8_dual(vbuf, vb_ptr, pcm); i_windowB8_dual_right(vbuf2, vb_ptr, pcm + 1); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 16; } } /*------------------------------------------------------------*/ void i_sbtB8_dual_mono(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct8_dual_mono(sample, vbuf + vb_ptr); i_windowB8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void i_sbtB8_dual_left(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { i_dct8_dual(sample, vbuf + vb_ptr); i_windowB8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void i_sbtB8_dual_right(SAMPLEINT * sample, unsigned char *pcm, int n) { int i; sample++; for (i = 0; i < n; i++) { i_dct8_dual(sample, vbuf + vb_ptr); i_windowB8(vbuf, vb_ptr, pcm); sample += 64; vb_ptr = (vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ <file_sep>/applications/region_changer/modules/rc.h /* DreamShell ##version## module.c - Region Changer module Copyright (C)2010-2014 SWAT */ #include "ds.h" typedef struct flash_factory_values { int country; int broadcast; int lang; int black_swirl; } flash_factory_values_t; /** * Application data */ flash_factory_values_t *flash_factory_get_values(uint8 *data); uint8 *flash_factory_set_lang(uint8 *data, int lang); uint8 *flash_factory_set_broadcast(uint8 *data, int broadcast); uint8 *flash_factory_set_country(uint8 *data, int country, int black_swirl); int flash_clear(int block); uint8 *flash_read_factory(); int flash_write_factory(uint8 *data); void flash_factory_free_values(flash_factory_values_t *values); void flash_factory_free_data(uint8 *data); /* Read file to RAM and write to flashrom */ int flash_write_file(const char *filename); /* Read flashrom to RAM and write to file */ int flash_read_file(const char *filename); /** * Lua binding */ int tolua_RC_open (lua_State* tolua_S); <file_sep>/include/isofs/gdi.h /** * Copyright (c) 2014 by SWAT <<EMAIL>> www.dc-swat.ru * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef _ISOFS_GDI_H #define _ISOFS_GDI_H #include <kos.h> /** * \file * nullDC GDI support for isofs * * \author SWAT */ #define GDI_MAX_TRACKS 99 typedef struct GDI_track { uint32 start_lba; uint32 flags; uint32 sector_size; uint32 offset; char filename[NAME_MAX]; } GDI_track_t; typedef struct GDI_header { file_t track_fd; uint16 track_current; uint16 track_count; GDI_track_t *tracks[GDI_MAX_TRACKS]; } GDI_header_t; GDI_header_t *gdi_open(file_t fd, const char *path); int gdi_close(GDI_header_t *hdr); #define gdi_track_sector_size(track) track->sector_size GDI_track_t *gdi_get_track(GDI_header_t *hdr, uint32 lba); uint32 gdi_get_offset(GDI_header_t *hdr, uint32 lba, uint16 *sector_size); int gdi_get_toc(GDI_header_t *hdr, CDROM_TOC *toc); int gdi_read_sectors(GDI_header_t *hdr, uint8 *buff, uint32 start, uint32 count); #endif /* _ISOFS_GDI_H */ <file_sep>/src/lua/lua_ds.c /**************************** * DreamShell ##version## * * lua_ds.h * * DreamShell LUA functions * * Created by SWAT * ****************************/ #include <kos.h> #include <dirent.h> #include "lua.h" #include "list.h" #include "module.h" #include "app.h" #include "console.h" #include "utils.h" static int l_ShowConsole(lua_State *L) { ShowConsole(); return 0; } static int l_HideConsole(lua_State *L) { HideConsole(); return 0; } static int l_PeriphExists(lua_State *L) { const char *s = luaL_checkstring(L, 1); if(PeriphExists(s)) { lua_pushnumber(L, 1); } else { lua_pushnil(L); } return 1; } static int l_OpenModule(lua_State *L) { const char *s = NULL; Module_t *m; s = luaL_checkstring(L, 1); m = OpenModule((char*)s); if(m != NULL) { lua_pushnumber(L, m->libid); } else { lua_pushnil(L); } return 1; } static int l_CloseModule(lua_State *L) { libid_t id = luaL_checkinteger(L, 1); Module_t *m = GetModuleById(id); if(m != NULL) { lua_pushnumber(L, CloseModule(m)); } else { lua_pushnil(L); } return 1; } static int l_GetModuleByName(lua_State *L) { const char *s = NULL; Module_t *m; s = luaL_checkstring(L, 1); m = GetModuleByName(s); if(m != NULL) { lua_pushnumber(L, m->libid); } else { lua_pushnil(L); } return 1; } static int l_AddApp(lua_State *L) { const char *fn = NULL; App_t *app; fn = luaL_checkstring(L, 1); app = AddApp(fn); if(app != NULL) { lua_pushstring(L, app->name); } else { lua_pushnil(L); } return 1; } static int l_OpenApp(lua_State *L) { const char *s = NULL, *a = NULL; App_t *app; s = luaL_checkstring(L, 1); a = luaL_optstring(L, 2, NULL); app = GetAppByName(s); if(app != NULL && OpenApp(app, a)) { lua_pushnumber(L, app->id); } else { lua_pushnil(L); } return 1; } static int l_CloseApp(lua_State *L) { const char *s = NULL; int u = 1; App_t *app; s = luaL_checkstring(L, 1); u = luaL_optint(L, 2, 1); app = GetAppByName(s); if(app != NULL && CloseApp(app, u)) { lua_pushnumber(L, app->id); } else { lua_pushnil(L); } return 1; } static int l_set_dbgio(lua_State *L) { const char *s = NULL; s = luaL_checkstring(L, 1); if(!strncasecmp(s, "scif", 4)) { scif_init(); dbgio_set_dev_scif(); SetConsoleDebug(1); } else if(!strncasecmp(s, "dclsocket", 9)) { dbgio_dev_select("fs_dclsocket"); } else if(!strncasecmp(s, "fb", 2)) { dbgio_set_dev_fb(); SetConsoleDebug(1); } else if(!strncasecmp(s, "ds", 2)) { dbgio_set_dev_ds(); SetConsoleDebug(0); } else if(!strncasecmp(s, "sd", 2)) { dbgio_set_dev_sd(); SetConsoleDebug(1); } else { lua_pushnil(L); return 1; } lua_pushnumber(L, 1); return 1; } static int l_Sleep(lua_State *L) { int ms = luaL_checkinteger(L, 1); thd_sleep(ms); lua_pushnil(L); return 0; } static int l_bit_or(lua_State *L) { int a, b; a = luaL_checkinteger(L, 1); b = luaL_checkinteger(L, 2); lua_pushnumber(L, (a | b)); return 1; } static int l_bit_and(lua_State *L) { int a, b; a = luaL_checkinteger(L, 1); b = luaL_checkinteger(L, 2); lua_pushnumber(L, (a & b)); return 1; } static int l_bit_not(lua_State *L) { int a; a = luaL_checkinteger(L, 1); lua_pushnumber(L, ~a); return 1; } static int l_bit_xor(lua_State *L) { int a, b; a = luaL_checkinteger(L, 1); b = luaL_checkinteger(L, 2); lua_pushnumber(L, (a ^ b)); return 1; } static int change_dir (lua_State *L) { const char *path = luaL_checkstring(L, 1); if (fs_chdir((char*)path)) { lua_pushnil (L); lua_pushfstring (L,"Unable to change working directory to '%s'\n", path); return 2; } else { lua_pushboolean (L, 1); return 1; } } static int get_dir (lua_State *L) { const char *path; if ((path = fs_getwd()) == NULL) { lua_pushnil(L); lua_pushstring(L, "getcwd error\n"); return 2; } else { lua_pushstring(L, path); return 1; } } static int make_dir (lua_State *L) { const char *path = luaL_checkstring (L, 1); int fail; fail = fs_mkdir(path); if (fail < 0) { lua_pushnil (L); lua_pushfstring (L, "Can't make dir"); return 2; } lua_pushboolean (L, 1); return 1; } /* ** Removes a directory. ** @param #1 Directory path. */ static int remove_dir (lua_State *L) { const char *path = luaL_checkstring (L, 1); int fail; fail = fs_rmdir(path); if (fail < 0) { lua_pushnil(L); lua_pushfstring(L, "Can't remove dir"); return 2; } lua_pushboolean(L, 1); return 1; } #define DIR_METATABLE "directory metatable" typedef struct dir_data { int closed; uint32 dir; } dir_data; /* ** Directory iterator */ static int dir_iter (lua_State *L) { dirent_t *entry; dir_data *d = (dir_data *)lua_touserdata (L, lua_upvalueindex (1)); luaL_argcheck (L, !d->closed, 1, "closed directory"); if ((entry = fs_readdir(d->dir)) != NULL) { lua_newtable (L); //ds_printf("entry = %s\n", entry->name); lua_pushstring(L, "name"); lua_pushstring(L, entry->name); //lua_rawset(L, -3); lua_settable(L, -3); lua_pushstring(L, "size"); lua_pushinteger(L, entry->size); //lua_rawset(L, -3); lua_settable(L, -3); lua_pushstring(L, "attr"); lua_pushinteger(L, entry->attr); //lua_rawset(L, -3); lua_settable(L, -3); lua_pushstring(L, "time"); lua_pushinteger(L, entry->time); //lua_rawset(L, -3); lua_settable(L, -3); return 1; } else { /* no more entries => close directory */ fs_close(d->dir); d->closed = 1; return 0; } return 0; } /* ** Closes directory iterators */ static int dir_close (lua_State *L) { dir_data *d = (dir_data *)lua_touserdata (L, 1); if (!d->closed && d->dir) { fs_close(d->dir); d->closed = 1; } return 0; } /* ** Factory of directory iterators */ static int dir_iter_factory (lua_State *L) { const char *path = luaL_checkstring (L, 1); dir_data *d = (dir_data *) lua_newuserdata (L, sizeof(dir_data)); d->closed = 0; luaL_getmetatable (L, DIR_METATABLE); lua_setmetatable (L, -2); d->dir = fs_open(path, O_RDONLY | O_DIR); if (d->dir < 0) luaL_error (L, "cannot open %s", path); lua_pushcclosure (L, dir_iter, 1); return 1; } /* ** Creates directory metatable. */ static int dir_create_meta (lua_State *L) { luaL_newmetatable (L, DIR_METATABLE); /* set its __gc field */ lua_pushstring (L, "__gc"); lua_pushcfunction (L, dir_close); lua_settable (L, -3); return 1; } static const struct luaL_reg bit_lib[] = { {"or", l_bit_or}, {"and", l_bit_and}, {"not", l_bit_not}, {"xor", l_bit_xor}, {NULL, NULL}, }; static const struct luaL_reg fs_lib[] = { {"chdir", change_dir}, {"currentdir", get_dir}, {"dir", dir_iter_factory}, {"mkdir", make_dir}, {"rmdir", remove_dir}, {NULL, NULL}, }; int luaopen_lfs (lua_State *L) { dir_create_meta (L); luaL_register (L, "lfs", fs_lib); return 1; } int luaopen_bit (lua_State *L) { luaL_register (L, "bit", bit_lib); return 1; } void RegisterLuaFunctions(lua_State *L) { lua_register(L, "OpenModule", l_OpenModule); lua_register(L, "CloseModule", l_CloseModule); lua_register(L, "GetModuleByName", l_GetModuleByName); lua_register(L, "AddApp", l_AddApp); lua_register(L, "OpenApp", l_OpenApp); lua_register(L, "CloseApp", l_CloseApp); lua_register(L, "ShowConsole", l_ShowConsole); lua_register(L, "HideConsole", l_HideConsole); lua_register(L, "SetDebugIO", l_set_dbgio); lua_register(L, "Sleep", l_Sleep); lua_register(L, "MapleAttached", l_PeriphExists); luaopen_lfs(L); luaopen_bit(L); } <file_sep>/modules/adx/libADXplay.c /* ** LibADXPlay (c)2012 <NAME> ** <EMAIL> */ #include <kos.h> #include "LibADX/libadx.h" /* ADX Decoder Library */ #include "LibADX/snddrv.h" /* Direct Access to Sound Driver */ #define CONT_RESUME 0x01 #define CONT_PAUSE 0x02 #define CONT_RESTART 0x03 #define CONT_STOP 0x04 #define CONT_VOLUP 0x05 #define CONT_VOLDN 0x06 int check_cont() { int ret=0; maple_device_t *cont; cont_state_t *state; cont = maple_enum_type(0, MAPLE_FUNC_CONTROLLER); if(cont) { state = (cont_state_t *)maple_dev_status(cont); if (!state) ret = 0; if (state->buttons & CONT_START) ret = CONT_STOP; if (state->buttons & CONT_X) ret = CONT_RESTART; if (state->buttons & CONT_A) ret = CONT_PAUSE; if (state->buttons & CONT_B) ret = CONT_RESUME; if (state->buttons & CONT_DPAD_UP) ret = CONT_VOLUP; if (state->buttons & CONT_DPAD_DOWN) ret = CONT_VOLDN; } return ret; } int main() { /* Print some text to the screen */ int o = 20*640+20; bfont_set_encoding(BFONT_CODE_ISO8859_1); bfont_draw_str(vram_s+o,640,1,"LibADX (C) PH3NOM 2012"); o+=640*48; printf("LibADX (C) PH3NOM 2012\n"); /* Start the ADX stream, with looping enabled */ if( adx_dec( "/cd/sample.adx", 1 ) < 1 ) { printf("Invalid ADX file\n"); return 0; } /* Wait for the stream to start */ while( snddrv.drv_status == SNDDRV_STATUS_NULL ) thd_pass(); bfont_draw_str(vram_s+o,640,1,"Press Start to stop, press X to restart"); o+=640*48; bfont_draw_str(vram_s+o,640,1,"Press A to pause, press B to resume"); o+=640*48; bfont_draw_str(vram_s+o,640,1,"Press UP or Down to increase/decrease volume"); /* Check for user input and eof */ while( snddrv.drv_status != SNDDRV_STATUS_NULL ) { int vol; switch (check_cont()) { case CONT_RESTART: if(adx_restart()) printf("ADX streaming restarted\n"); break; case CONT_STOP: if(adx_stop()) printf("ADX streaming stopped\n"); break; case CONT_PAUSE: if(adx_pause()) printf("ADX streaming paused\n"); break; case CONT_RESUME: if(adx_resume()) printf("ADX streaming resumed\n"); break; case CONT_VOLUP: vol = snddrv_volume_up(); printf("SNDDRV: Volume set to %i%s\n", ((vol*100)/255), "%"); break; case CONT_VOLDN: vol = snddrv_volume_down(); printf("SNDDRV: Volume set to %i%s\n", ((vol*100)/255), "%"); break; default: break; } thd_sleep(50); } /* when (snddrv.drv_status == SNDDRV_STATUS_NULL) the stream is finished*/ printf( "LibADX Example Finished\n"); return 0; } <file_sep>/sdk/toolchain/environ.sh # KallistiOS environment variable settings # # This is a sample script. Configure to suit your setup. Some possible # alternatives for the values below are included as an example. # # This script should be sourced in your current shell environment (probably # by bashrc or something similar). # # Build architecture. Set the major architecture you'll be building for. # The only option here is "dreamcast" as of KOS 2.0.0. export KOS_ARCH="dreamcast" # Build sub-architecture. If you need a particular sub-architecture, then set # that here; otherwise use "pristine". # Possible subarch options include: # "pristine" - a normal Dreamcast console or HKT-0120 devkit # "naomi" - a NAOMI or NAOMI 2 arcade board export KOS_SUBARCH="pristine" # KOS main base path export KOS_BASE="/usr/local/dc/kos/kos" export KOS_PORTS="${KOS_BASE}/../kos-ports" # Make utility export KOS_MAKE="make" #export KOS_MAKE="gmake" # CMake toolchain export KOS_CMAKE_TOOLCHAIN="${KOS_BASE}/utils/cmake/dreamcast.toolchain.cmake" # Load utility export KOS_LOADER="dc-tool -x" # dcload, preconfigured # export KOS_LOADER="dc-tool-ser -t /dev/ttyS0 -x" # dcload-serial # Genromfs utility export KOS_GENROMFS="${KOS_BASE}/utils/genromfs/genromfs" #export KOS_GENROMFS="genromfs" # Compiler prefixes #export KOS_CC_BASE="/usr/local/dc/dc-elf" #export KOS_CC_PREFIX="dc" export KOS_CC_BASE="/opt/toolchains/dc/sh-elf" # DC export KOS_CC_PREFIX="sh-elf" # If you are compiling for DC and have an ARM compiler, use these too. # If you're using a newer compiler (GCC 4.7.0 and newer), you should probably be # using arm-eabi as the target, rather than arm-elf. dc-chain now defaults to # arm-eabi, so that's the default here. #export DC_ARM_BASE="/usr/local/dc/arm-elf" #export DC_ARM_PREFIX="arm-elf" export DC_ARM_BASE="/opt/toolchains/dc/arm-eabi" export DC_ARM_PREFIX="arm-eabi" # Expand PATH if not already set (comment out if you don't want this done here) if [[ ":$PATH:" != *":${KOS_CC_BASE}/bin:/opt/toolchains/dc/bin:"* ]]; then export PATH="${PATH}:${KOS_CC_BASE}/bin:/opt/toolchains/dc/bin" fi # reset some options because there's no reason for them to persist across # multiple sourcing of this export KOS_INC_PATHS="" export KOS_CFLAGS="" export KOS_CPPFLAGS="" export KOS_LDFLAGS="" export KOS_AFLAGS="" export DC_ARM_LDFLAGS="" # Setup some default CFLAGS for compilation. The things that will go here # are user specifyable, like optimization level and whether you want stack # traces enabled. Some platforms may have optimization restrictions, # please check README. # GCC seems to have made -fomit-frame-pointer the default on many targets, so # hence you may need -fno-omit-frame-pointer to actually have GCC spit out frame # pointers. It won't hurt to have it in there either way. # Link-time optimizations can be enabled by adding -flto. It however requires a # recent toolchain (GCC 10+), and has not been thoroughly tested. export KOS_CFLAGS="-O2 -fomit-frame-pointer" # export KOS_CFLAGS="-O2 -DFRAME_POINTERS -fno-omit-frame-pointer" # Comment out this line to enable GCC to use its own builtin implementations of # certain standard library functions. Under certain conditions, this can allow # compiler-optimized implementations to replace standard function invocations. # The downside of this is that it COULD interfere with Newlib or KOS implementations # of these functions, and it has not been tested thoroughly to ensure compatibility. export KOS_CFLAGS="${KOS_CFLAGS} -fno-builtin" # Uncomment this line to enable the optimized fast-math instructions (FSSRA, # FSCA, and FSQRT) for calculating sin/cos, inverse square root, and square roots. # These can result in substantial performance gains for these kinds of operations; # however, they do so at the price of accuracy and are not IEEE compliant. # NOTE: This also requires -fno-builtin be removed from KOS_CFLAGS to take effect! # export KOS_CFLAGS="${KOS_CFLAGS} -ffast-math -ffp-contract=fast -mfsrra -mfsca" # Everything else is pretty much shared. If you want to configure compiler # options or other such things, look at this file. . ${KOS_BASE}/environ_base.sh <file_sep>/firmware/isoldr/loader/fs/fat/src/fstime.c // $$$ : fstime.c -- #include "fstime.h" typedef unsigned long ulong; #define RTC (*((volatile ulong *)0xa0710000)) #define RTC2 (*((volatile ulong *)0xa0710004)) #define S_P_MIN 60L #define S_P_HOUR (60L * S_P_MIN) #define S_P_DAY (24L * S_P_HOUR) #define S_P_YEAR (365L * S_P_DAY) #define JAPAN_ADJ (-9L * S_P_HOUR) static ulong _rtc_secs(void) { return((RTC << 16)|(RTC2 & 0xffff)); } ulong rtc_secs(void) { ulong t; do { t = _rtc_secs(); } while (t != _rtc_secs()); return(t); } struct _time_block *conv_gmtime(ulong t) { static int day_p_m[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int day, mon, yr, cumday; static struct _time_block tm; tm.sec = t % 60L; t /= 60L; tm.min = t % 60L; t /= 60L; tm.hour = t % 24L; day = t / 24L; yr = 1950; cumday = 0; while ((cumday += (yr % 4 ? 365 : 366)) <= day) yr++; tm.year = yr; cumday -= yr % 4 ? 365 : 366; day -= cumday; cumday = 0; mon = 0; day_p_m[1] = (yr % 4) == 0 ? 29 : 28; while ((cumday += day_p_m[mon]) <= day) mon++; cumday -= day_p_m[mon]; day -= cumday; tm.day = day + 1; tm.mon = mon + 1; return &tm; } // end of : fstime.c <file_sep>/modules/aicaos/arm/aica_syscalls.c #include <sys/types.h> #include <sys/stat.h> #include <sys/times.h> #include <sys/reent.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <errno.h> int _execve_r(struct _reent *r, const char *name, char * const argv[], char * const env[]) { r->_errno = ENOMEM; return -1; } int _fork_r(struct _reent *r) { r->_errno = EAGAIN; return -1; } int _getpid_r(struct _reent *r) { return 1; } int _kill_r(struct _reent *r, int pid, int sig) { r->_errno = EINVAL; return -1; } clock_t _times_r(struct _reent *r, struct tms *buf) { r->_errno = EACCES; return -1; } int _wait_r(struct _reent *r, int *status) { r->_errno = ECHILD; return -1; } _READ_WRITE_RETURN_TYPE _write_r(struct _reent *, int, const void *, size_t); static char *heap_end = (char*) 0; void * _sbrk_r(struct _reent *r, ptrdiff_t incr) { extern char _end; /* Defined by the linker */ char *prev_heap_end; if (heap_end == 0) heap_end = &_end; prev_heap_end = heap_end; heap_end += incr; return prev_heap_end; } /* AICA-specific syscalls */ #include "../aica_syscalls.h" AICA_ADD_REMOTE(sh4_open, PRIORITY_DEFAULT); AICA_ADD_REMOTE(sh4_close, PRIORITY_DEFAULT); AICA_ADD_REMOTE(sh4_fstat, PRIORITY_DEFAULT); AICA_ADD_REMOTE(sh4_stat, PRIORITY_DEFAULT); AICA_ADD_REMOTE(sh4_isatty, PRIORITY_DEFAULT); AICA_ADD_REMOTE(sh4_link, PRIORITY_DEFAULT); AICA_ADD_REMOTE(sh4_lseek, PRIORITY_DEFAULT); AICA_ADD_REMOTE(sh4_read, PRIORITY_DEFAULT); AICA_ADD_REMOTE(sh4_write, PRIORITY_DEFAULT); int _open_r(struct _reent *r, const char *name, int flags, int mode) { struct open_param params = { name, strlen(name), flags, mode, }; return sh4_open(NULL, &params); } int _close_r(struct _reent *r, int file) { return sh4_close(NULL, &file); } int _fstat_r(struct _reent *r, int file, struct stat *st) { struct fstat_param params = { file, st, }; return sh4_fstat(NULL, &params); } int _stat_r(struct _reent *r, const char *file, struct stat *st) { struct stat_param params = { file, strlen(file), st, }; return sh4_stat(NULL, &params); } int _isatty_r(struct _reent *r, int file) { return sh4_isatty(NULL, &file); } int _link_r(struct _reent *r, const char *old, const char *new) { struct link_param params = { old, strlen(old), new, strlen(new), }; return sh4_link(NULL, &params); } off_t _lseek_r(struct _reent *r, int file, off_t ptr, int dir) { struct lseek_param params = { file, ptr, dir, }; return sh4_lseek(NULL, &params); } _READ_WRITE_RETURN_TYPE _read_r(struct _reent *r, int file, void *ptr, size_t len) { struct read_param params = { file, ptr, len, }; return sh4_read(NULL, &params); } _READ_WRITE_RETURN_TYPE _write_r(struct _reent *r, int file, const void *ptr, size_t len) { struct write_param params = { file, ptr, len, }; return sh4_write(NULL, &params); } <file_sep>/applications/main/modules/app_module.h /* DreamShell ##version## module.h - Main app module header Copyright (C)2023 SWAT */ #include <ds.h> void MainApp_SlideLeft(); void MainApp_SlideRight(); void MainApp_Init(App_t *app); <file_sep>/modules/luaTask/Makefile # # luaTask module for DreamShell # Copyright (C) 2011-2014 SWAT # http://www.dc-swat.ru # TARGET_NAME = luaTask OBJS = module.o src/ltask.o src/queue.o src/syncos.o DBG_LIBS = -lds EXPORTS_FILE = exports.txt VER_MAJOR = 1 VER_MINOR = 6 VER_MICRO = 4 all: rm-elf include ../../sdk/Makefile.loadable KOS_CFLAGS += -I./src -I$(DS_SDK)/include/lua rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/modules/mp3/libmp3/xingmp3/icdct.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** icdct.c *************************************************** MPEG audio decoder, dct portable C integer dct mod 1/8/97 warnings ******************************************************************/ #include <float.h> #include <math.h> #include "itype.h" /*-------------------------------------------------------------------*/ static DCTCOEF coef32[32]; /* 32 pt dct coefs */ #define forward_bf idx_forward_bf /*--- #define forward_bf ptr_forward_bf ---*/ /*------------------------------------------------------------*/ DCTCOEF *i_dct_coef_addr() { return coef32; } /*------------------------------------------------------------*/ static void idx_forward_bf(int m, int n, INT32 x[], INT32 f[], DCTCOEF coef[]) { int i, j, n2; int p, q, p0, k; p0 = 0; n2 = n >> 1; for (i = 0; i < m; i++, p0 += n) { k = 0; p = p0; q = p + n - 1; for (j = 0; j < n2; j++, p++, q--, k++) { f[p] = x[p] + x[q]; f[n2 + p] = ((x[p] - x[q]) * coef[k]) >> DCTBITS; } } } /*------------------------------------------------------------*/ /*-- static void ptr_forward_bf(int m, int n, INT32 x[], INT32 f[], DCTCOEF coef[]) { int i, j, n2; DCTCOEF *c; INT32 *y; n2 = n >> 1; for(i=0; i<m; i++) { c = coef; y = x+n; for(j=0; j<n2; j++) { *f = *x + *--y; *((f++)+n2) = ( (*x++ - *y) * (*c++) ) >> DCTBITS; } f+=n2; x+=n2; } } ---*/ /*------------------------------------------------------------*/ static void forward_bfm(int m, INT32 x[], INT32 f[]) { int i; int p; /*--- special case last fwd stage ----*/ for (p = 0, i = 0; i < m; i++, p += 2) { f[p] = x[p] + x[p + 1]; f[p + 1] = ((x[p] - x[p + 1]) * coef32[30]) >> DCTBITS; } } /*------------------------------------------------------------*/ static void back_bf(int m, int n, INT32 x[], INT32 f[]) { int i, j, n2, n21; int p, q, p0; p0 = 0; n2 = n >> 1; n21 = n2 - 1; for (i = 0; i < m; i++, p0 += n) { p = p0; q = p0; for (j = 0; j < n2; j++, p += 2, q++) f[p] = x[q]; p = p0 + 1; for (j = 0; j < n21; j++, p += 2, q++) f[p] = x[q] + x[q + 1]; f[p] = x[q]; } } /*------------------------------------------------------------*/ static void back_bf0(int n, INT32 x[], WININT f[]) { int p, q; n--; #if DCTSATURATE for (p = 0, q = 0; p < n; p += 2, q++) { tmp = x[q]; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; f[p] = tmp; } for (p = 1; q < n; p += 2, q++) { tmp = x[q] + x[q + 1]; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; f[p] = tmp; } tmp = x[q]; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; f[p] = tmp; #else for (p = 0, q = 0; p < n; p += 2, q++) f[p] = x[q]; for (p = 1; q < n; p += 2, q++) f[p] = x[q] + x[q + 1]; f[p] = x[q]; #endif } /*------------------------------------------------------------*/ void i_dct32(SAMPLEINT x[], WININT c[]) { INT32 a[32]; /* ping pong buffers */ INT32 b[32]; int p, q; /* special first stage */ for (p = 0, q = 31; p < 16; p++, q--) { a[p] = (INT32) x[p] + x[q]; a[16 + p] = (coef32[p] * ((INT32) x[p] - x[q])) >> DCTBITS; } forward_bf(2, 16, a, b, coef32 + 16); forward_bf(4, 8, b, a, coef32 + 16 + 8); forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); forward_bfm(16, b, a); back_bf(8, 4, a, b); back_bf(4, 8, b, a); back_bf(2, 16, a, b); back_bf0(32, b, c); } /*------------------------------------------------------------*/ void i_dct32_dual(SAMPLEINT x[], WININT c[]) { INT32 a[32]; /* ping pong buffers */ INT32 b[32]; int p, pp, qq; /* special first stage for dual chan (interleaved x) */ pp = 0; qq = 2 * 31; for (p = 0; p < 16; p++, pp += 2, qq -= 2) { a[p] = (INT32) x[pp] + x[qq]; a[16 + p] = (coef32[p] * ((INT32) x[pp] - x[qq])) >> DCTBITS; } forward_bf(2, 16, a, b, coef32 + 16); forward_bf(4, 8, b, a, coef32 + 16 + 8); forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); forward_bfm(16, b, a); back_bf(8, 4, a, b); back_bf(4, 8, b, a); back_bf(2, 16, a, b); back_bf0(32, b, c); } /*---------------convert dual to mono------------------------------*/ void i_dct32_dual_mono(SAMPLEINT x[], WININT c[]) { INT32 a[32]; /* ping pong buffers */ INT32 b[32]; INT32 t1, t2; int p, pp, qq; /* special first stage */ pp = 0; qq = 2 * 31; for (p = 0; p < 16; p++, pp += 2, qq -= 2) { t1 = ((INT32) x[pp] + x[pp + 1]); t2 = ((INT32) x[qq] + x[qq + 1]); a[p] = (t1 + t2) >> 1; a[16 + p] = coef32[p] * (t1 - t2) >> (DCTBITS + 1); } forward_bf(2, 16, a, b, coef32 + 16); forward_bf(4, 8, b, a, coef32 + 16 + 8); forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); forward_bfm(16, b, a); back_bf(8, 4, a, b); back_bf(4, 8, b, a); back_bf(2, 16, a, b); back_bf0(32, b, c); } /*------------------------------------------------------------*/ /*---------------- 16 pt dct -------------------------------*/ void i_dct16(SAMPLEINT x[], WININT c[]) { INT32 a[16]; /* ping pong buffers */ INT32 b[16]; int p, q; /* special first stage (drop highest sb) */ a[0] = x[0]; a[8] = (a[0] * coef32[16]) >> DCTBITS; for (p = 1, q = 14; p < 8; p++, q--) { a[p] = (INT32) x[p] + x[q]; a[8 + p] = (((INT32) x[p] - x[q]) * coef32[16 + p]) >> DCTBITS; } forward_bf(2, 8, a, b, coef32 + 16 + 8); forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); forward_bfm(8, a, b); back_bf(4, 4, b, a); back_bf(2, 8, a, b); back_bf0(16, b, c); } /*------------------------------------------------------------*/ /*---------------- 16 pt dct dual chan---------------------*/ void i_dct16_dual(SAMPLEINT x[], WININT c[]) { int p, pp, qq; INT32 a[16]; /* ping pong buffers */ INT32 b[16]; /* special first stage for interleaved input */ a[0] = x[0]; a[8] = (coef32[16] * a[0]) >> DCTBITS; pp = 2; qq = 2 * 14; for (p = 1; p < 8; p++, pp += 2, qq -= 2) { a[p] = (INT32) x[pp] + x[qq]; a[8 + p] = (coef32[16 + p] * ((INT32) x[pp] - x[qq])) >> DCTBITS; } forward_bf(2, 8, a, b, coef32 + 16 + 8); forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); forward_bfm(8, a, b); back_bf(4, 4, b, a); back_bf(2, 8, a, b); back_bf0(16, b, c); } /*------------------------------------------------------------*/ /*---------------- 16 pt dct dual to mono-------------------*/ void i_dct16_dual_mono(SAMPLEINT x[], WININT c[]) { INT32 a[16]; /* ping pong buffers */ INT32 b[16]; INT32 t1, t2; int p, pp, qq; /* special first stage */ a[0] = ((INT32) x[0] + x[1]) >> 1; a[8] = (coef32[16] * a[0]) >> DCTBITS; pp = 2; qq = 2 * 14; for (p = 1; p < 8; p++, pp += 2, qq -= 2) { t1 = (INT32) x[pp] + x[pp + 1]; t2 = (INT32) x[qq] + x[qq + 1]; a[p] = (t1 + t2) >> 1; a[8 + p] = (coef32[16 + p] * (t1 - t2)) >> (DCTBITS + 1); } forward_bf(2, 8, a, b, coef32 + 16 + 8); forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); forward_bfm(8, a, b); back_bf(4, 4, b, a); back_bf(2, 8, a, b); back_bf0(16, b, c); } /*------------------------------------------------------------*/ /*---------------- 8 pt dct -------------------------------*/ void i_dct8(SAMPLEINT x[], WININT c[]) { int p, q; INT32 a[8]; /* ping pong buffers */ INT32 b[8]; /* special first stage */ for (p = 0, q = 7; p < 4; p++, q--) { b[p] = (INT32) x[p] + x[q]; b[4 + p] = (coef32[16 + 8 + p] * ((INT32) x[p] - x[q])) >> DCTBITS; } forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); forward_bfm(4, a, b); back_bf(2, 4, b, a); back_bf0(8, a, c); } /*------------------------------------------------------------*/ /*---------------- 8 pt dct dual chan---------------------*/ void i_dct8_dual(SAMPLEINT x[], WININT c[]) { int p, pp, qq; INT32 a[8]; /* ping pong buffers */ INT32 b[8]; /* special first stage for interleaved input */ for (p = 0, pp = 0, qq = 14; p < 4; p++, pp += 2, qq -= 2) { b[p] = (INT32) x[pp] + x[qq]; b[4 + p] = (coef32[16 + 8 + p] * ((INT32) x[pp] - x[qq])) >> DCTBITS; } forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); forward_bfm(4, a, b); back_bf(2, 4, b, a); back_bf0(8, a, c); } /*------------------------------------------------------------*/ /*---------------- 8 pt dct dual to mono---------------------*/ void i_dct8_dual_mono(SAMPLEINT x[], WININT c[]) { int p, pp, qq; INT32 a[8]; /* ping pong buffers */ INT32 b[8]; INT32 t1, t2; /* special first stage */ for (p = 0, pp = 0, qq = 14; p < 4; p++, pp += 2, qq -= 2) { t1 = (INT32) x[pp] + x[pp + 1]; t2 = (INT32) x[qq] + x[qq + 1]; b[p] = (t1 + t2) >> 1; b[4 + p] = (coef32[16 + 8 + p] * (t1 - t2)) >> (DCTBITS + 1); } forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); forward_bfm(4, a, b); back_bf(2, 4, b, a); back_bf0(8, a, c); } /*------------------------------------------------------------*/ <file_sep>/modules/luaSTD/module.c /* DreamShell ##version## module.c - luaSTD module Copyright (C)2007-2013 SWAT */ #include <kos.h> #include <kos/exports.h> #include "ds.h" DEFAULT_MODULE_HEADER(luaSTD); int tolua_STD_open(lua_State* tolua_S); int lib_open(klibrary_t * lib) { tolua_STD_open(GetLuaState()); RegisterLuaLib(lib_get_name(), (LuaRegLibOpen *)tolua_STD_open); return nmmgr_handler_add(&ds_luaSTD_hnd.nmmgr); } int lib_close(klibrary_t * lib) { UnregisterLuaLib(lib_get_name()); return nmmgr_handler_remove(&ds_luaSTD_hnd.nmmgr); } <file_sep>/modules/ftpd/lftpd/lftpd_inet.c #include "private/lftpd_inet.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdarg.h> #include <stdbool.h> #include <unistd.h> #include <ctype.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "private/lftpd_log.h" int lftpd_inet_listen(int port) { int s = socket(AF_INET6, SOCK_STREAM, 0); if (s < 0) { lftpd_log_error("error creating listener socket"); return -1; } struct sockaddr_in6 server_addr = { .sin6_family = AF_INET6, .sin6_addr = in6addr_any, .sin6_port = htons(port), }; int err = bind(s, (struct sockaddr *) &server_addr, sizeof(server_addr)); if (err < 0) { lftpd_log_error("error binding listener port %d", port); return -1; } err = listen(s, 10); if (err < 0) { lftpd_log_error("error listening on socket"); return -1; } return s; } int lftpd_inet_get_socket_port(int socket) { struct sockaddr_in6 data_port_addr; socklen_t data_port_addr_len = sizeof(struct sockaddr_in6); int err = getsockname(socket, (struct sockaddr*) &data_port_addr, &data_port_addr_len); if (err != 0) { lftpd_log_error("error getting listener socket port number"); return -1; } return ntohs(data_port_addr.sin6_port); } int lftpd_inet_read_line(int socket, char* buffer, size_t buffer_len) { memset(buffer, 0, buffer_len); int total_read_len = 0; while (total_read_len < buffer_len) { // read up to length - 1 bytes. the - 1 leaves room for the // null terminator. int read_len = read(socket, buffer + total_read_len, buffer_len - total_read_len - 1); if (read_len == 0) { // end of stream - since we didn't find the end of line in // the previous pass we won't find it in this one, so this // is an error. return -1; } else if (read_len < 0) { // general error return read_len; } total_read_len += read_len; char* p = strstr(buffer, "\r\n"); if (p) { // null terminate the line and return *p = '\0'; lftpd_log_debug("< '%s'", buffer); return 0; } } return -1; } int lftpd_inet_write_string(int socket, const char* message) { char* p = (char*) message; int length = strlen(message); while (length) { int write_len = write(socket, p, length); if (write_len < 0) { lftpd_log_error("write error"); return write_len; } p += write_len; length -= write_len; } lftpd_log_debug("> %s", message); return 0; } <file_sep>/lib/SDL_gui/Makefile # Makefile created by SWAT # http://www.dc-swat.ru TARGET = libSDL_gui.a KOS_CPPFLAGS += -fno-operator-names -fno-rtti -fno-exceptions OBJS = \ SDL_gui.o Exception.o Object.o Surface.o Font.o Callback.o \ Drawable.o Screen.o Widget.o Container.o \ FastFont.o TrueTypeFont.o \ Layout.o Panel.o CardStack.o \ FastLabel.o Label.o Picture.o TextEntry.o \ AbstractButton.o Button.o ToggleButton.o \ ProgressBar.o ScrollBar.o \ AbstractTable.o ListBox.o \ VBoxLayout.o RealScreen.o \ Mouse.o ScrollPanel.o \ Window.o SDLScreen.o \ RTF.o FileManager.o KOS_CFLAGS += -I../../include/SDL -I../include -I../../include include $(KOS_BASE)/ds/lib/Makefile.prefab <file_sep>/firmware/isoldr/loader/exception.c /** * DreamShell ISO Loader * Exception handling * (c)2014-2023 SWAT <http://www.dc-swat.ru> * Based on Netplay VOOT code by <NAME> <<EMAIL>> */ #include <main.h> #include <exception.h> #include <arch/cache.h> extern uint32 exception_os_type; extern uint32 interrupt_stack; static exception_table exp_table; static volatile int inside_int = 0; static int inited = 0; /* Pointers to the VBR Buffer */ static uint8 *vbr_buffer; static uint8 *vbr_buffer_orig; int exception_inited(void) { return inited; //exception_vbr_ok(); } static int exception_vbr_ok(void) { uint32 int_changed; #ifdef HAVE_UBC uint32 gen_changed; #endif // uint32 cache_changed; /* Check to see if our VBR hooks are still installed. */ int_changed = memcmp( VBR_INT(vbr_buffer) - (interrupt_sub_handler_base - interrupt_sub_handler), interrupt_sub_handler, interrupt_sub_handler_end - interrupt_sub_handler ); #ifdef HAVE_UBC gen_changed = memcmp( VBR_GEN (vbr_buffer) - (general_sub_handler_base - general_sub_handler), general_sub_handler, general_sub_handler_end - general_sub_handler ); #endif // // cache_changed = memcmp( // VBR_GEN (vbr_buffer) - (cache_sub_handler_base - cache_sub_handler), // cache_sub_handler, // cache_sub_handler_end - cache_sub_handler // ); /* After enough exceptions, allow the initialization. */ return !( int_changed #ifdef HAVE_UBC || gen_changed #endif /* || cache_changed*/ ); } int exception_init(uint32 vbr_addr) { vbr_buffer = vbr_addr > 0 ? (void *)vbr_addr : vbr(); if (!vbr_buffer/* || exception_vbr_ok () || (exp_table.ubc_exception_count < 7)*/) { return -1; } if(exception_vbr_ok()) { LOGFF("already initialized\n"); return 0; } exception_os_type = IsoInfo->exec.type; /* Relocate the VBR index - bypass our entry logic. */ if (exception_os_type == BIN_TYPE_KATANA) { // Skip one more instruction because it in paired using with old replaced instruction. vbr_buffer_orig = vbr_buffer + (sizeof (uint16) * 4); } else if(exception_os_type == BIN_TYPE_KOS) { // Direct usage of _irq_save_regs by fixed offset. vbr_buffer_orig = vbr_buffer - 0x188; } else { // Normally skip only 3 replaced instruction. vbr_buffer_orig = vbr_buffer + (sizeof (uint16) * 3); } // if(IsoInfo->exec.type != BIN_TYPE_WINCE) { // interrupt_stack = (uint32)malloc(2048); // } // LOGFF("VBR buffer 0x%08lx -> 0x%08lx, stack 0x%08lx\n", vbr_buffer, vbr_buffer_orig, interrupt_stack); LOGFF("VBR buffer 0x%08lx -> 0x%08lx\n", vbr_buffer, vbr_buffer_orig); /* Interrupt hack for VBR. */ memcpy( VBR_INT(vbr_buffer) - (interrupt_sub_handler_base - interrupt_sub_handler), interrupt_sub_handler, interrupt_sub_handler_end - interrupt_sub_handler ); if (exception_os_type != BIN_TYPE_WINCE) { uint16 *change_stack_instr = VBR_INT(vbr_buffer) - (interrupt_sub_handler_base - interrupt_sub_handler); *change_stack_instr = 0x0009; // nop } #ifdef HAVE_UBC /* General exception hack for VBR. */ memcpy( VBR_GEN(vbr_buffer) - (general_sub_handler_base - general_sub_handler), general_sub_handler, general_sub_handler_end - general_sub_handler ); #endif /* Cache exception hack for VBR. */ // memcpy( // VBR_CACHE(vbr_buffer) - (cache_sub_handler_base - cache_sub_handler), // cache_sub_handler, // cache_sub_handler_end - cache_sub_handler // ); /* Flush cache after modifying application memory. */ dcache_flush_range((uint32)vbr_buffer, 0xC08); icache_flush_range((uint32)vbr_buffer, 0xC08); inited = 1; return 0; } int exception_inside_int(void) { return inside_int; } int exception_add_handler(const exception_table_entry *new_entry, exception_handler_f *parent_handler) { uint32 index; /* Search the entire table for either a match or an opening. */ for (index = 0; index < EXP_TABLE_SIZE; index++) { /* If the entry is configured with same type and code as the new handler, push it on the stack and let's roll! */ if ((exp_table.table[index].type == new_entry->type) && (exp_table.table[index].code == new_entry->code)) { if(parent_handler) *parent_handler = exp_table.table[index].handler; exp_table.table[index].handler = new_entry->handler; return 1; } else if (!(exp_table.table[index].type)) { /* We've reached the end of the filled entries, I guess we have to create our own. */ if(parent_handler) *parent_handler = NULL; memcpy(&exp_table.table[index], new_entry, sizeof(exception_table_entry)); return 1; } } return 0; } void *exception_handler(register_stack *stack) { uint32 exception_code; uint32 index; void *back_vector; if (inside_int) { LOGFF("ERROR: already in IRQ\n"); return my_exception_finish; } inside_int = 1; #if 0 LOGFF("0x%02x 0x%08lx\n", stack->exception_type & 0xff, stack->exception_type == EXP_TYPE_INT ? *REG_INTEVT : *REG_EXPEVT); // dump_regs(stack); #endif /* Ensure vbr buffer is set... */ // vbr_buffer = (uint8 *) stack->vbr; /* Increase our counters and set the proper back_vectors. */ switch (stack->exception_type) { #ifdef HAVE_UBC case EXP_TYPE_GEN : { //exp_table.general_exception_count++; exception_code = *REG_EXPEVT; /* Never pass on UBC interrupts to the game. */ if ((exception_code == EXP_CODE_UBC) || (exception_code == EXP_CODE_TRAP)) { //exp_table.ubc_exception_count++; back_vector = my_exception_finish; } else { back_vector = exception_os_type == BIN_TYPE_KOS ? vbr_buffer_orig : VBR_GEN(vbr_buffer_orig); } break; } #endif // // case EXP_TYPE_CACHE : // { // //exp_table.cache_exception_count++; // exception_code = *REG_EXPEVT; // back_vector = exception_os_type == BIN_TYPE_KOS ? vbr_buffer_orig : VBR_CACHE(vbr_buffer_orig); // break; // } case EXP_TYPE_INT : { //exp_table.interrupt_exception_count++; exception_code = *REG_INTEVT; back_vector = exception_os_type == BIN_TYPE_KOS ? vbr_buffer_orig : VBR_INT(vbr_buffer_orig); break; } default : { //exp_table.odd_exception_count++; exception_code = EXP_CODE_BAD; back_vector = exception_os_type == BIN_TYPE_KOS ? vbr_buffer_orig : VBR_INT(vbr_buffer_orig); break; } } /* Handle exception table */ for (index = 0; index < EXP_TABLE_SIZE; index++) { if (((exp_table.table[index].code == exception_code) || (exp_table.table[index].code == EXP_CODE_ALL)) && ((exp_table.table[index].type == stack->exception_type) || (exp_table.table[index].type == EXP_TYPE_ALL))) { /* Call the handler and use whatever hook it returns. */ back_vector = exp_table.table[index].handler(stack, back_vector); } } // irq_disable(); inside_int = 0; /* We're all done. Return however we were instructed. */ return back_vector; } #ifdef LOG void dump_regs(register_stack *stack) { LOGF(" R0 = 0x%08lx R1 = 0x%08lx R2 = 0x%08lx\n R3 = 0x%08lx R4 = 0x%08lx R5 = 0x%08lx\n", stack->r0, stack->r1, stack->r2, stack->r3, stack->r4, stack->r5); LOGF(" R6 = 0x%08lx R7 = 0x%08lx R8 = 0x%08lx\n R9 = 0x%08lx R10 = 0x%08lx R11 = 0x%08lx\n", stack->r6, stack->r7, stack->r8, stack->r9, stack->r10, stack->r11); LOGF("R12 = 0x%08lx R13 = 0x%08lx R14 = 0x%08lx\n PR = 0x%08lx PC = 0x%08lx SR = 0x%08lx\n", stack->r12, stack->r13, stack->r14, stack->pr, stack->spc, stack->ssr); // LOGF(" SGR = 0x%08lx STACK = 0x%08lx\n", sgr(), r15()); } #endif <file_sep>/include/setjmp.h /** * \file setjmp.h * \brief setjmp * \date 2007-2014 * \author SWAT www.dc-swat.ru */ #ifndef _JMPBUF_H_ #define _JMPBUF_H_ typedef char jmp_buf[13*4]; int longjmp(jmp_buf buf, int what_is_that); int setjmp(jmp_buf buf); #endif <file_sep>/sdk/bin/src/mkbios/Makefile CFLAGS = -O2 INSTALL = install DESTDIR = ../.. all : mkbios ciso : mkbios.o $(LD) -o mkbios mkbios.o ciso.o : mkbios.c $(CC) -o mkbios.o -c mkbios.c install : mkbios $(INSTALL) -m 755 mkbios $(DESTDIR)/mkbios clean: rm -rf *.o rm -rf mkbios <file_sep>/src/drivers/rtc.c /* DreamShell ##version## rtc.c Copyright (C) 2015-2016 SWAT Copyright (C) 2016 Megavolt85 */ #include <arch/types.h> #include <dc/g2bus.h> #include <drivers/rtc.h> /* The AICA RTC has an Epoch of 1/1/1950, so we must subtract 20 years (in seconds to get the standard Unix Epoch when getting the time, and add 20 years when setting the time. */ #define TWENTY_YEARS ((20 * 365LU + 5) * 86400) /* The AICA RTC is represented by a 32-bit seconds counter stored in 2 16-bit registers.*/ #define AICA_RTC_SECS_H 0xa0710000 #define AICA_RTC_SECS_L 0xa0710004 #define AICA_RTC_WRITE_EN 0xa0710008 #define AICA_RTC_ATTEMPTS_COUNT 10 time_t rtc_gettime() { time_t val1, val2; int i = 0; do { val1 = ((g2_read_32(AICA_RTC_SECS_H) & 0xffff) << 16) | (g2_read_32(AICA_RTC_SECS_L) & 0xffff); val2 = ((g2_read_32(AICA_RTC_SECS_H) & 0xffff) << 16) | (g2_read_32(AICA_RTC_SECS_L) & 0xffff); if(i++ > AICA_RTC_ATTEMPTS_COUNT) { return (-1); } } while (val1 != val2); return (val1 - TWENTY_YEARS); } int rtc_settime(time_t time) { time_t val1, val2; time_t secs = time + TWENTY_YEARS; int i = 0; do { g2_write_32(1, AICA_RTC_WRITE_EN); g2_write_32((secs & 0xffff0000) >> 16, AICA_RTC_SECS_H); g2_write_32((secs & 0xffff), AICA_RTC_SECS_L); val1 = ((g2_read_32(AICA_RTC_SECS_H) & 0xffff) << 16) | (g2_read_32(AICA_RTC_SECS_L) & 0xffff); val2 = ((g2_read_32(AICA_RTC_SECS_H) & 0xffff) << 16) | (g2_read_32(AICA_RTC_SECS_L) & 0xffff); if(i++ > AICA_RTC_ATTEMPTS_COUNT) { return (-1); } } while ((val1 != val2) && ((val1 & 0xffffff80) != (secs & 0xffffff80))); return 0; } int rtc_gettimeutc(struct tm *time) { time_t timestamp = rtc_gettime(); if(time == NULL || timestamp == -1) { return -1; } localtime_r(&timestamp, time); return 0; } int rtc_settimeutc(const struct tm *time) { time_t timestamp = mktime((struct tm *)time); if(time == NULL || timestamp == -1) { return -1; } return rtc_settime(timestamp); } void rtc_gettimeofday(struct timeval *tv) { tv->tv_sec = rtc_gettime(); /* Can't get microseconds with just a seconds counter. */ tv->tv_usec = 0; } int rtc_settimeofday(const struct timeval *tv) { return rtc_settime(tv->tv_sec); } <file_sep>/firmware/isoldr/loader/Makefile # # DreamShell ISO Loader # (c) 2009-2023 SWAT # include Makefile.cfg DEFS = ENABLE_CISO=1 DEFS_EXTENDED = ENABLE_CDDA=1 ENABLE_IRQ=1 ENABLE_LIMIT=1 DEFS_FULL = ENABLE_CISO=1 ENABLE_CDDA=1 ENABLE_IRQ=1 \ ENABLE_MAPLE=1 ENABLE_WRITE=1 ENABLE_ESC=1 \ ENABLE_SCR=1 TARGETS = cd_full cd_ext cd sd_full sd_ext sd ide_full ide_ext ide # TARGETS += dcl_full dcl_ext dcl net_full net_ext net all: clean $(TARGETS) sd: $(BUILD)/sd.bin $(BUILD)/sd.bin: make -f Makefile.sd $(DEFS) sd_ext: $(BUILD)/sd_ext.bin $(BUILD)/sd_ext.bin: make -f Makefile.sd $(DEFS_EXTENDED) mv $(BUILD)/sd.bin $(BUILD)/sd_ext.bin sd_full: $(BUILD)/sd_full.bin $(BUILD)/sd_full.bin: make -f Makefile.sd $(DEFS_FULL) mv $(BUILD)/sd.bin $(BUILD)/sd_full.bin ide: $(BUILD)/ide.bin $(BUILD)/ide.bin: make -f Makefile.ide $(DEFS) ide_ext: $(BUILD)/ide_ext.bin $(BUILD)/ide_ext.bin: make -f Makefile.ide $(DEFS_EXTENDED) mv $(BUILD)/ide.bin $(BUILD)/ide_ext.bin ide_full: $(BUILD)/ide_full.bin $(BUILD)/ide_full.bin: make -f Makefile.ide $(DEFS_FULL) mv $(BUILD)/ide.bin $(BUILD)/ide_full.bin net: $(BUILD)/net.bin $(BUILD)/net.bin: make -f Makefile.net $(DEFS) net_ext: $(BUILD)/net_ext.bin $(BUILD)/net_ext.bin: make -f Makefile.net $(DEFS_EXTENDED) mv $(BUILD)/net.bin $(BUILD)/net_ext.bin net_full: $(BUILD)/net_full.bin $(BUILD)/net_full.bin: make -f Makefile.net $(DEFS_FULL) mv $(BUILD)/net.bin $(BUILD)/net_full.bin cd: $(BUILD)/cd.bin $(BUILD)/cd.bin: make -f Makefile.cd $(DEFS) cd_ext: $(BUILD)/cd_ext.bin $(BUILD)/cd_ext.bin: make -f Makefile.cd $(DEFS_EXTENDED) mv $(BUILD)/cd.bin $(BUILD)/cd_ext.bin cd_full: $(BUILD)/cd_full.bin $(BUILD)/cd_full.bin: make -f Makefile.cd $(DEFS_FULL) mv $(BUILD)/cd.bin $(BUILD)/cd_full.bin dcl: $(BUILD)/dcl.bin $(BUILD)/dcl.bin: make -f Makefile.dcl $(DEFS) dcl_ext: $(BUILD)/dcl_ext.bin $(BUILD)/dcl_ext.bin: make -f Makefile.dcl $(DEFS_EXTENDED) mv $(BUILD)/dcl.bin $(BUILD)/dcl_ext.bin dcl_full: $(BUILD)/dcl_full.bin $(BUILD)/dcl_full.bin: make -f Makefile.dcl $(DEFS_FULL) mv $(BUILD)/dcl.bin $(BUILD)/dcl_full.bin clean: rm -f $(KOS) $(EXEC) $(MAIN) $(SD) $(IDE) $(CD) $(DCL) #$(NET) rm -f $(BUILD)/*.elf rm -f $(BUILD)/*.bin install: -mkdir -p $(INSTALL_PATH) cp $(BUILD)/*.bin $(INSTALL_PATH) test_cd: clean cd_full cd_ext cd -mkdir -p $(INSTALL_PATH) cp $(BUILD)/cd*.bin $(INSTALL_PATH) test_ide: clean ide_full ide_ext ide -mkdir -p $(INSTALL_PATH) cp $(BUILD)/ide*.bin $(INSTALL_PATH) test_sd: clean sd_full sd_ext sd -mkdir -p $(INSTALL_PATH) cp $(BUILD)/sd*.bin $(INSTALL_PATH) <file_sep>/modules/aicaos/aica_common.c #include <stdlib.h> #include <string.h> #include <sys/queue.h> #include "aica_common.h" struct Handler { aica_funcp_t handler; const char *funcname; unsigned int id; SLIST_ENTRY(Handler) next; }; static SLIST_HEAD(Head, Handler) head = SLIST_HEAD_INITIALIZER(head); void __aica_share(aica_funcp_t func, const char *funcname, size_t sz_in, size_t sz_out) { unsigned int id; struct Handler *hdl = malloc(sizeof(*hdl)); if (SLIST_FIRST(&head) == NULL) id = 0; else id = SLIST_FIRST(&head)->id + 1; struct function_params fparams = { { sz_in, sz_in ? malloc(sz_in) : NULL, }, { sz_out, sz_out ? malloc(sz_out) : NULL, }, FUNCTION_CALL_AVAIL, }; aica_update_fparams_table(id, &fparams); hdl->id = id; hdl->handler = func; hdl->funcname = funcname; SLIST_INSERT_HEAD(&head, hdl, next); } int aica_clear_handler(unsigned int id) { struct Handler *hdl; SLIST_FOREACH(hdl, &head, next) { if (hdl->id == id) { SLIST_REMOVE(&head, hdl, Handler, next); free(hdl); return 0; } } return -1; } void aica_clear_handler_table(void) { struct Handler *hdl; while (1) { hdl = SLIST_FIRST(&head); if (!hdl) return; SLIST_REMOVE_HEAD(&head, next); free(hdl); } } int aica_find_id(unsigned int *id, char *funcname) { struct Handler *hdl; SLIST_FOREACH(hdl, &head, next) { if (strcmp(hdl->funcname, funcname) == 0) { *id = hdl->id; return 0; } } return -EAGAIN; } aica_funcp_t aica_get_func_from_id(unsigned int id) { struct Handler *hdl; SLIST_FOREACH(hdl, &head, next) { if (hdl->id == id) return hdl->handler; } return NULL; } const char * aica_get_funcname_from_id(unsigned int id) { struct Handler *hdl; SLIST_FOREACH(hdl, &head, next) { if (hdl->id == id) return hdl->funcname; } return NULL; } <file_sep>/include/list.h /** * \file list.h * \brief DreamShell lists * \date 2007-2014 * \author SWAT www.dc-swat.ru */ #ifndef _DS_LIST_H #define _DS_LIST_H #include <kos.h> #include <stdlib.h> /** * Определенные типы данных элемента, которые есть в DreamShell. Вы можете добавлять свои. * Если вы используете список, где данные элемента не подходят не под один существующий тип, * то можно использовать универсальный тип LIST_ITEM_USERDATA. */ typedef enum { LIST_ITEM_USERDATA = 0, LIST_ITEM_SDL_SURFACE, LIST_ITEM_SDL_RWOPS, LIST_ITEM_GUI_SURFACE, LIST_ITEM_GUI_FONT, LIST_ITEM_GUI_WIDGET, LIST_ITEM_MODULE, LIST_ITEM_APP, LIST_ITEM_EVENT, LIST_ITEM_THREAD, LIST_ITEM_CMD, LIST_ITEM_LUA_LIB, LIST_ITEM_XML_NODE } ListItemType; /* Структура элемента списка */ typedef struct Item { /* Точка входа SLIST, только для внутреннего использования. */ SLIST_ENTRY(Item) list; /* Имя элемента списка */ const char *name; /* ID элемента списка */ uint32 id; /* Тип элемента списка */ ListItemType type; /* Данные элемента списка */ void *data; /* Размер данных (не обязателен) */ uint32 size; } Item_t; /** * Определение типа для списка. Используется SLIST из библиотеки newlib */ typedef SLIST_HEAD(ItemList, Item) Item_list_t; /** * Определение типа функции, освобождающей память, занимаемую данными элемента. */ typedef void listFreeItemFunc(void *); /** * Создает список и возвращает указатель на него. Возвращает NULL в случае не удачи. */ Item_list_t *listMake(); #define listNew listMake; /** * Удаляет все элементы списка и сам список, аргумент ifree является функцией, для освобождения памяти, которую занимают данные элемента. * В основном подходит функция free, она же используется там по умолчанию, если указать вместо аргумента ifree - NULL */ void listDestroy(Item_list_t *lst, listFreeItemFunc *ifree); /** * Получает ID последнего элемента (существующего или уже нет) из списка. */ uint32 listGetLastId(Item_list_t *lst); /** * Добавляет элемент в список и возвращает ссылку на него при успехе, а при ошибке возвращает NULL. */ Item_t *listAddItem(Item_list_t *lst, ListItemType type, const char *name, void *data, uint32 size); /** * Удаляет элемент из списка. */ void listRemoveItem(Item_list_t *lst, Item_t *i, listFreeItemFunc *ifree); /** * Ищет элемент в списке по его имени. * Если элемент найден, возвращается ссылка на него, если нет, то возвращает NULL. */ Item_t *listGetItemByName(Item_list_t *lst, const char *name); /** * Ищет элемент в списке по типу. * Если элемент найден, возвращается ссылка на него, если нет, то возвращает NULL. */ Item_t *listGetItemByType(Item_list_t *lst, ListItemType type); /** * Ищет элемент в списке по его имени и типу. * Если элемент найден, возвращается ссылка на него, если нет, то возвращает NULL. */ Item_t *listGetItemByNameAndType(Item_list_t *lst, const char *name, ListItemType type); /** * Ищет элемент в списке по его ID. * Если элемент найден, возвращается ссылка на него, если же нет, то возвращает NULL. */ Item_t *listGetItemById(Item_list_t *lst, uint32 id); /** * Возвращает первый элемент списка. */ Item_t *listGetItemFirst(Item_list_t *lst); /** * Возвращает следующий элемент списка, находящийся после элемента переданного аргументом i. */ Item_t *listGetItemNext(Item_t *i); /** * Примечание: * Функции listGetItemFirst и listGetItemNext служат для создания циклической обработки списков. */ #endif <file_sep>/src/video.c /**************************** * DreamShell ##version## * * video.c * * DreamShell video * * Created by SWAT * ****************************/ #include "ds.h" #include "console.h" #include <kmg/kmg.h> #include <zlib/zlib.h> static int sdl_dc_no_ask_60hz = 0; static int sdl_dc_default_60hz = 0; #include "../lib/SDL/src/video/dc/60hz.h" //#define DEBUG_VIDEO 1 static SDL_Surface *DScreen = NULL; static mutex_t video_mutex = MUTEX_INITIALIZER; static kthread_t *video_thd; static int video_inited = 0; static int video_mode = -1; static float screen_opacity = 1.0f; static float plx_opacity = 1.0f; static volatile int scr_fade_act = 0, first_fade = 1; static volatile int screen_changed = 1, draw_screen = 1; extern int sdl_dc_width; extern int sdl_dc_height; extern int sdl_dc_wtex; extern int sdl_dc_htex; static float native_width = 640.0f; static float native_height = 480.0f; static float sdl_dc_x = 0.0f; static float sdl_dc_y = 0.0f; static float sdl_dc_z = 1.0f; static float sdl_dc_rot_x = 0; /* X Rotation */ static float sdl_dc_rot_y = 0; /* Y Rotation */ static float sdl_dc_rot_z = 0; /* Y Rotation */ static float sdl_dc_trans_x = 0; static float sdl_dc_trans_y = 0; static float sdl_dc_trans_z = 0; static pvr_ptr_t logo_txr; static int logo_w = 1024; static int logo_h = 512; pvr_ptr_t sdl_dc_memtex; unsigned short *sdl_dc_buftex; static plx_font_t *plx_fnt; static plx_fcxt_t *plx_cxt; static plx_texture_t *plx_screen_texture; static int screen_filter = PVR_FILTER_NEAREST; static float sdl_dc_u1 = 0.3f; static float sdl_dc_u2 = 0.3f; static float sdl_dc_v1 = 0.9f; static float sdl_dc_v2 = 0.6f; static void *VideoThread(void *ptr); SDL_Surface *GetScreen() { return DScreen; } int GetScreenWidth() { return DScreen->w; } int GetScreenHeight() { return DScreen->h; } pvr_ptr_t GetScreenTexture() { return sdl_dc_memtex; } int GetVideoMode() { return video_mode; } void SetVideoMode(int mode) { int pm; Settings_t *settings = GetSettings(); switch(settings->video.bpp) { case 15: pm = PM_RGB555; break; case 16: pm = PM_RGB565; break; case 24: case 32: pm = PM_RGB888; break; default: pm = PM_RGB565; break; } if(mode < 0) { if(vid_check_cable() == CT_VGA) { video_mode = DM_640x480_VGA; } else { int region = flashrom_get_region_only(); switch(region) { case FLASHROM_REGION_US: case FLASHROM_REGION_JAPAN: video_mode = DM_640x480_NTSC_IL; break; case FLASHROM_REGION_EUROPE: video_mode = DM_640x480_PAL_IL; break; case FLASHROM_REGION_UNKNOWN: default: if(!sdl_dc_ask_60hz()) { video_mode = DM_640x480_PAL_IL; } else { video_mode = DM_640x480_NTSC_IL; } break; } } } else { video_mode = mode; } vid_set_mode(video_mode, pm); } void SetScreenTexture(pvr_ptr_t *txr) { LockVideo(); sdl_dc_memtex = txr; UnlockVideo(); } void SetScreen(SDL_Surface *new_screen) { LockVideo(); DScreen = new_screen; UnlockVideo(); } void SetScreenOpacity(float opacity) { LockVideo(); screen_opacity = opacity; UnlockVideo(); } float GetScreenOpacity() { return screen_opacity; } void SetScreenFilter(int filter) { LockVideo(); if(filter < 0) { Settings_t *settings = GetSettings(); if(settings->video.virt_width > 640 || settings->video.virt_height > 480) { screen_filter = PVR_FILTER_BILINEAR; //PVR_FILTER_TRILINEAR1 } else { screen_filter = PVR_FILTER_NEAREST; } } else { screen_filter = filter; } plx_txr_setfilter(plx_screen_texture, screen_filter); UnlockVideo(); } void DisableScreen() { LockVideo(); draw_screen = 0; UnlockVideo(); } void EnableScreen() { LockVideo(); draw_screen = 1; UnlockVideo(); } int ScreenIsEnabled() { return draw_screen; } void ScreenChanged() { #if 0 if(VideoMustLock()) { // ds_printf("%s outside\n", __func__); LockVideo(); screen_changed = 1; UnlockVideo(); } else { //ds_printf("%s inside\n", __func__); screen_changed = 1; } #else #ifdef DEBUG_VIDEO //ds_printf("%s\n", __func__); #endif screen_changed = 1; #endif } int ScreenUpdated() { return screen_changed != 1; } void ScreenWaitUpdate() { if(!video_inited) return; while(screen_changed) thd_pass(); } void SetScreenVertex(float u1, float v1, float u2, float v2) { LockVideo(); sdl_dc_u1 = u1; sdl_dc_v1 = v1; sdl_dc_u2 = u2; sdl_dc_v2 = v2; UnlockVideo(); } void ScreenFadeIn() { LockVideo(); scr_fade_act = 1; UnlockVideo(); } void ScreenFadeOut() { LockVideo(); scr_fade_act = 2; UnlockVideo(); } void ScreenFadeStop() { LockVideo(); scr_fade_act = 0; UnlockVideo(); } static inline void ScreenFadeStep() { switch(scr_fade_act) { case 1: if(screen_opacity >= 1.0f) { scr_fade_act = 0; if(first_fade) { first_fade = 0; // pvr_set_bg_color(0.85f, 0.85f, 0.85f); } } else { screen_opacity += 0.05f; plx_opacity -= 0.05f; } break; case 2: if(screen_opacity <= 0.0f) { scr_fade_act = 0; } else { screen_opacity -= 0.05f; plx_opacity += 0.05f; } break; default: break; } } void ScreenRotate(float x, float y, float z) { LockVideo(); sdl_dc_rot_x = x; sdl_dc_rot_y = y; sdl_dc_rot_z = z; UnlockVideo(); } void ScreenTranslate(float x, float y, float z) { LockVideo(); sdl_dc_trans_x = x; sdl_dc_trans_y = y; sdl_dc_trans_z = z; UnlockVideo(); } void InitVideoThread() { video_inited = 1; video_thd = thd_create(0, VideoThread, NULL); strncpy(video_thd->label, "[video]\0", 8); thd_pass(); } void ShutdownVideoThread() { // LockVideo(); video_inited = 0; // UnlockVideo(); if(video_thd) { thd_join(video_thd, NULL); } // if(VideoIsLocked()) UnlockVideo(); } int VideoIsLocked() { //if(!video_inited) return 0; return mutex_is_locked(&video_mutex); } int VideoMustLock() { #ifdef DEBUG_VIDEO kthread_t *ct = thd_get_current(); printf("%s: %p != %p\n", __func__, video_thd, ct); #endif return (video_inited && video_thd != thd_get_current()); } void LockVideo() { // if(!video_inited) return; #ifdef DEBUG_VIDEO printf("%s\n", __func__); #endif mutex_lock(&video_mutex); // mutex_lock_timed(&video_mutex, 60000); } void UnlockVideo() { // if(!video_inited) return; #ifdef DEBUG_VIDEO printf("%s\n", __func__); #endif mutex_unlock(&video_mutex); } void plx_fill_contexts(plx_texture_t * txr) { pvr_poly_cxt_txr(&txr->cxt_opaque, PVR_LIST_OP_POLY, txr->fmt, txr->w, txr->h, txr->ptr, screen_filter); pvr_poly_cxt_txr(&txr->cxt_trans, PVR_LIST_TR_POLY, txr->fmt, txr->w, txr->h, txr->ptr, screen_filter); pvr_poly_cxt_txr(&txr->cxt_pt, PVR_LIST_PT_POLY, txr->fmt, txr->w, txr->h, txr->ptr, screen_filter); plx_txr_flush_hdrs(txr); } void InitVideoHardware() { Settings_t *settings = GetSettings(); if(settings->video.mode.width > 0 && settings->video.mode.height > 0) { vid_set_mode_ex(&settings->video.mode); native_width = (float)settings->video.mode.width; native_height = (float)settings->video.mode.height; } else { SetVideoMode(-1); } // dbglog(DBG_INFO, "PVR hardware ID: %08lx Revision: %08lx\n", PVR_GET(PVR_ID), PVR_GET(PVR_REVISION)); pvr_init_defaults(); // pvr_dma_init(); } int InitVideo(int w, int h, int bpp) { int sdl_init_flags, sdl_video_flags, tex_mode; char fn[NAME_MAX]; Settings_t *settings = GetSettings(); SDL_DC_ShowAskHz(SDL_TRUE); SDL_DC_Default60Hz(SDL_FALSE); SDL_DC_VerticalWait(SDL_TRUE); SDL_DC_EmulateKeyboard(SDL_FALSE); SDL_DC_EmulateMouse(SDL_TRUE); sdl_init_flags = SDL_INIT_VIDEO|SDL_INIT_JOYSTICK; sdl_video_flags = SDL_HWSURFACE|SDL_DOUBLEBUF; SDL_DC_SetVideoDriver(SDL_DC_TEXTURED_VIDEO); if (SDL_Init(sdl_init_flags) < 0) { ds_printf("SDL init failed: %s\n", SDL_GetError()); return 0; } if(!(DScreen = SDL_SetVideoMode(w, h, bpp, sdl_video_flags))) { dbglog(DBG_ERROR, "Change SDL video mode failed: %s\n", SDL_GetError()); return 0; } //SDL_DC_EmulateMouse(SDL_TRUE); //SDL_DC_EmulateKeyboard(SDL_TRUE); SDL_JoystickOpen(0); SDL_JoystickEventState(SDL_ENABLE); SDL_EnableUNICODE(SDL_ENABLE); SDL_ShowCursor(SDL_DISABLE); /* Init matrices */ plx_mat3d_init(); /* Clear internal to an identity matrix */ plx_mat3d_mode(PLX_MAT_PROJECTION); /** Projection (frustum, screenview) matrix */ plx_mat3d_identity(); /** Load an identity matrix */ plx_mat3d_perspective(45.0f, native_width / native_height, 0.1f, 100.0f); plx_mat3d_mode(PLX_MAT_MODELVIEW); /** Modelview (rotate, scale) matrix */ plx_mat_identity(); plx_mat3d_apply_all(); if(settings->video.tex_filter >= PVR_FILTER_NEAREST) { screen_filter = settings->video.tex_filter; } plx_screen_texture = (plx_texture_t*) malloc(sizeof(plx_texture_t)); switch(settings->video.bpp) { case 15: tex_mode = PVR_TXRFMT_ARGB1555; break; case 16: case 24: case 32: default: tex_mode = PVR_TXRFMT_RGB565; break; } if(plx_screen_texture != NULL) { plx_screen_texture->ptr = sdl_dc_memtex; plx_screen_texture->w = w; plx_screen_texture->h = h; plx_screen_texture->fmt = tex_mode|PVR_TXRFMT_NONTWIDDLED;//|PVR_TXRFMT_STRIDE; plx_fill_contexts(plx_screen_texture); plx_txr_setfilter(plx_screen_texture, screen_filter); } plx_cxt_init(); sprintf(fn, "%s/fonts/txf/axaxax.txf", getenv("PATH")); plx_fnt = plx_font_load(fn); if(plx_fnt) { plx_cxt = plx_fcxt_create(plx_fnt, PVR_LIST_TR_POLY); plx_fcxt_setcolor4f(plx_cxt, plx_opacity, 0.9f, 0.9f, 0.9f); } else { ds_printf("DS_ERROR: Can't load %s\n", fn); } mutex_init((mutex_t *)&video_mutex, MUTEX_TYPE_NORMAL); return 1; } void ShutdownVideo() { mutex_destroy(&video_mutex); if(plx_screen_texture) { free(plx_screen_texture); plx_screen_texture = NULL; } if (plx_cxt) { plx_fcxt_destroy(plx_cxt); plx_cxt = NULL; } if (plx_fnt) { plx_font_destroy(plx_fnt); plx_fnt = NULL; } SDL_Quit(); } void SDL_DS_SetWindow(int width, int height) { LockVideo(); sdl_dc_width = width; sdl_dc_height = height; sdl_dc_u1 = 0.3f*(1.0f/((float)sdl_dc_wtex)); sdl_dc_v1 = 0.3f*(1.0f/((float)sdl_dc_wtex)); sdl_dc_u2 = (((float)sdl_dc_width)+0.5f)*(1.0f/((float)sdl_dc_wtex)); sdl_dc_v2 = (((float)sdl_dc_height)+0.5f)*(1.0f/((float)sdl_dc_htex)); //plx_mat3d_perspective(45.0f, (float)sdl_dc_width / (float)sdl_dc_height, 0.1f, 100.0f); /* dbg_printf(" sdl_dc_width=%d\n sdl_dc_height=%d\n sdl_dc_wtex=%d\n sdl_dc_htex=%d\n sdl_dc_u1=%f\n sdl_dc_v1=%f\n sdl_dc_u2=%f\n sdl_dc_v2=%f\n", sdl_dc_width, sdl_dc_height, sdl_dc_wtex, sdl_dc_htex, sdl_dc_u1, sdl_dc_v1, sdl_dc_u2, sdl_dc_v2); */ UnlockVideo(); } void SDL_DS_Blit_Textured() { if(!first_fade && screen_opacity < 0.9f && plx_fnt) { point_t w; w.x = 255.0f; w.y = 230.0f; w.z = 12.0f; pvr_list_begin(PVR_LIST_TR_POLY); plx_fcxt_begin(plx_cxt); plx_fcxt_setpos_pnt(plx_cxt, &w); // plx_fcxt_setcolor4f(plx_cxt, plx_opacity, 0.2f, 0.2f, 0.2f); plx_fcxt_setcolor4f(plx_cxt, plx_opacity, 0.9f, 0.9f, 0.9f); plx_fcxt_draw(plx_cxt, "Loading..."); plx_fcxt_end(plx_cxt); } //printf("Draw frame: %d\n", ++frame); if (screen_changed) { #ifdef DEBUG_VIDEO ds_printf("%s: buftex=%p memtex=%p size=%d\n", __func__, (unsigned)sdl_dc_buftex, sdl_dc_memtex, sdl_dc_wtex * sdl_dc_htex * 2); #endif //if(wait_dma_ready() < 0) { //pvr_txr_load(sdl_dc_buftex, sdl_dc_memtex, sdl_dc_wtex * sdl_dc_htex * 2); sq_cpy(sdl_dc_memtex, sdl_dc_buftex, sdl_dc_wtex * sdl_dc_htex * 2); //} else { // dcache_flush_range((unsigned)sdl_dc_buftex, sdl_dc_wtex * sdl_dc_htex * 2); // pvr_txr_load_dma(sdl_dc_buftex, sdl_dc_memtex, sdl_dc_wtex * sdl_dc_htex * 2, -1, NULL, 0); //} screen_changed = 0; } pvr_list_begin(PVR_LIST_TR_POLY); plx_mat3d_identity(); plx_mat3d_translate(sdl_dc_trans_x, sdl_dc_trans_y, sdl_dc_trans_z); //plx_mat3d_translate((sdl_dc_wtex/2)+512.0f*sdl_dc_trans_x/native_width,(sdl_dc_htex/2)+512.0f*sdl_dc_trans_y/native_height,sdl_dc_trans_z - 3); /* Clear internal to an identity matrix */ plx_mat_identity(); /* "Applying" all matrixs: multiply a matrix onto the "internal" one */ plx_mat3d_apply_all(); plx_mat3d_rotate(sdl_dc_rot_x, 1.0f, 0.0f, 0.0f); plx_mat3d_rotate(sdl_dc_rot_y, 0.0f, 1.0f, 0.0f); plx_mat3d_rotate(sdl_dc_rot_z, 0.0f, 0.0f, 1.0f); plx_mat3d_translate(0, 0, 0); plx_cxt_texture(plx_screen_texture); //plx_cxt_culling(PLX_CULL_NONE); plx_cxt_send(PLX_LIST_TR_POLY); uint32 color = PVR_PACK_COLOR(screen_opacity, 1.0f, 1.0f, 1.0f); plx_vert_ifpm3(PLX_VERT, sdl_dc_x, sdl_dc_y, sdl_dc_z, color, sdl_dc_u1, sdl_dc_v1); plx_vert_ifpm3(PLX_VERT, sdl_dc_x + native_width, sdl_dc_y, sdl_dc_z, color, sdl_dc_u2, sdl_dc_v1); plx_vert_ifpm3(PLX_VERT, sdl_dc_x, sdl_dc_y + native_height, sdl_dc_z, color, sdl_dc_u1, sdl_dc_v2); plx_vert_ifpm3(PLX_VERT_EOS, sdl_dc_x + native_width, sdl_dc_y + native_height, sdl_dc_z, color, sdl_dc_u2, sdl_dc_v2); } static void *VideoThread(void *ptr) { while(video_inited) { /* plx_mat3d_identity(); plx_mat_identity(); plx_mat3d_apply_all(); */ pvr_wait_ready(); pvr_scene_begin(); LockVideo(); if(draw_screen) { ScreenFadeStep(); ProcessVideoEventsRender(); SDL_DS_Blit_Textured(); } else { ProcessVideoEventsRender(); } UnlockVideo(); pvr_list_finish(); pvr_scene_finish(); } //dbglog(DBG_DEBUG, "Exiting from video thread\n"); return NULL; } void SetScreenMode(int w, int h, float x, float y, float z) { Settings_t *settings = GetSettings(); if(settings->video.tex_filter < PVR_FILTER_NEAREST) { if(w > 640 || h > 480) { SetScreenFilter(PVR_FILTER_BILINEAR); // SetScreenFilter(PVR_FILTER_TRILINEAR1); } else { SetScreenFilter(PVR_FILTER_NEAREST); } } #if 0 if(h > 512) { sdl_dc_htex = 1024; DScreen->h = h; SDL_DS_FreeScreenTexture(0); SDL_DS_AllocScreenTexture(DScreen); if(plx_screen_texture != NULL) { plx_screen_texture->h = sdl_dc_htex; plx_screen_texture->ptr = sdl_dc_memtex; plx_fill_contexts(plx_screen_texture); } } else { if(DScreen->h > 512) { DScreen->h = h; sdl_dc_htex = 512; SDL_DS_FreeScreenTexture(0); SDL_DS_AllocScreenTexture(DScreen); if(plx_screen_texture != NULL) { plx_screen_texture->h = sdl_dc_htex; plx_screen_texture->ptr = sdl_dc_memtex; plx_fill_contexts(plx_screen_texture); } } } #else DScreen->h = h; #endif DScreen->w = w; sdl_dc_x = x; sdl_dc_y = y; sdl_dc_z = z; SDL_DS_SetWindow(w, h); /* FIXME: resize console ConsoleInformation *console = GetConsole(); if(console != NULL && (console->ConsoleSurface->w != w || console->ConsoleSurface->h != h)) { SDL_Rect rect; rect.w = w; rect.h = h; rect.x = 0; rect.y = 0; CON_Resize(console, rect); } */ } Uint32 SDL_GetPixel(SDL_Surface *surface, int x, int y) { int bpp = surface->format->BytesPerPixel; /* Here p is the address to the pixel we want to retrieve */ Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp; switch(bpp) { case 1: return *p; break; case 2: return *(Uint16 *)p; break; case 3: if(SDL_BYTEORDER == SDL_BIG_ENDIAN) return p[0] << 16 | p[1] << 8 | p[2]; else return p[0] | p[1] << 8 | p[2] << 16; break; case 4: return *(Uint32 *)p; break; default: return 0; /* shouldn't happen, but avoids warnings */ } } void SDL_PutPixel(SDL_Surface *surface, int x, int y, Uint32 pixel) { int bpp = surface->format->BytesPerPixel; /* Here p is the address to the pixel we want to set */ Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp; switch(bpp) { case 1: *p = pixel; break; case 2: *(Uint16 *)p = pixel; break; case 3: if(SDL_BYTEORDER == SDL_BIG_ENDIAN) { p[0] = (pixel >> 16) & 0xff; p[1] = (pixel >> 8) & 0xff; p[2] = pixel & 0xff; } else { p[0] = pixel & 0xff; p[1] = (pixel >> 8) & 0xff; p[2] = (pixel >> 16) & 0xff; } break; case 4: *(Uint32 *)p = pixel; break; } } int gzip_kmg_to_img(const char * fn, kos_img_t * rv) { gzFile f; kmg_header_t hdr; /* Open the file */ f = gzopen(fn, "r"); if (f == NULL) { dbglog(DBG_ERROR, "%s: can't open file '%s'\n", __func__, fn); return -1; } /* Read the header */ if (gzread(f, &hdr, sizeof(hdr)) != sizeof(hdr)) { gzclose(f); dbglog(DBG_ERROR, "%s: can't read header from file '%s'\n", __func__, fn); return -2; } /* Verify a few things */ if (hdr.magic != KMG_MAGIC || hdr.version != KMG_VERSION || hdr.platform != KMG_PLAT_DC) { gzclose(f); dbglog(DBG_ERROR, "%s: file '%s' is incompatible:\n" " magic %08lx version %d platform %d\n", __func__, fn, hdr.magic, (int)hdr.version, (int)hdr.platform); return -3; } /* Setup the kimg struct */ rv->w = hdr.width; rv->h = hdr.height; rv->byte_count = hdr.byte_count; rv->data = malloc(hdr.byte_count); if (!rv->data) { dbglog(DBG_ERROR, "%s: can't malloc(%d) while loading '%s'\n", __func__, (int)hdr.byte_count, fn); gzclose(f); return -4; } int dep = 0; if (hdr.format & KMG_DCFMT_VQ) dep |= PVR_TXRLOAD_FMT_VQ; if (hdr.format & KMG_DCFMT_TWIDDLED) dep |= PVR_TXRLOAD_FMT_TWIDDLED; switch (hdr.format & KMG_DCFMT_MASK) { case KMG_DCFMT_RGB565: rv->fmt = KOS_IMG_FMT(KOS_IMG_FMT_RGB565, dep); break; case KMG_DCFMT_ARGB4444: rv->fmt = KOS_IMG_FMT(KOS_IMG_FMT_ARGB4444, dep); break; case KMG_DCFMT_ARGB1555: rv->fmt = KOS_IMG_FMT(KOS_IMG_FMT_ARGB1555, dep); break; case KMG_DCFMT_YUV422: rv->fmt = KOS_IMG_FMT(KOS_IMG_FMT_YUV422, dep); break; case KMG_DCFMT_BUMP: /* XXX */ rv->fmt = KOS_IMG_FMT(KOS_IMG_FMT_RGB565, dep); break; case KMG_DCFMT_4BPP_PAL: case KMG_DCFMT_8BPP_PAL: default: dbglog(DBG_ERROR, "%s: currently-unsupported KMG pixel format", __func__); gzclose(f); free(rv->data); return -5; } if (gzread(f, rv->data, rv->byte_count) != rv->byte_count) { dbglog(DBG_ERROR, "%s: can't read %d bytes while loading '%s'\n", __func__, (int)hdr.byte_count, fn); gzclose(f); free(rv->data); return -6; } /* Ok, all done */ gzclose(f); /* If the byte count is not a multiple of 32, bump it up as well. This is for DMA/SQ usage. */ rv->byte_count = (rv->byte_count + 31) & ~31; return 0; } void ShowLogo() { kos_img_t img; float opacity = 0.0f; float w = native_width; //(float)DScreen->w; float h = native_height; //(float)DScreen->h; float u1, v1, u2, v2; pvr_poly_cxt_t cxt; pvr_poly_hdr_t hdr; pvr_vertex_t vert; screen_opacity = 0.0f; if(gzip_kmg_to_img("/rd/logo.kmg.gz", &img)) { //if(png_to_img(fn, &img)) { dbglog(DBG_ERROR, "%s: error in gzip_kmg_to_img\n", __func__); return; } logo_txr = pvr_mem_malloc(img.byte_count); if(!logo_txr) { kos_img_free(&img, 0); return; } if(img.w) logo_w = img.w; if(img.h) logo_h = img.h; u1 = 0.3f * (1.0f / ((float)logo_w)); v1 = 0.3f * (1.0f / ((float)logo_w)); u2 = (w + 0.5f) * (1.0f / ((float)logo_w)); v2 = (h + 0.5f) * (1.0f / ((float)logo_h)); pvr_txr_load_kimg(&img, logo_txr, 0); kos_img_free(&img, 0); if(video_inited) { ShutdownVideoThread(); } while(opacity < 1.0f) { pvr_wait_ready(); pvr_scene_begin(); pvr_list_begin(PVR_LIST_TR_POLY); pvr_poly_cxt_txr(&cxt, PVR_LIST_TR_POLY, PVR_TXRFMT_RGB565, logo_w, logo_h, logo_txr, PVR_FILTER_BILINEAR); pvr_poly_compile(&hdr, &cxt); pvr_prim(&hdr, sizeof(hdr)); vert.argb = PVR_PACK_COLOR(opacity, 1.0f, 1.0f, 1.0f); vert.oargb = 0; vert.flags = PVR_CMD_VERTEX; vert.x = 1.0f; vert.y = 1.0f; vert.z = 1.0f; vert.u = u1; vert.v = v1; pvr_prim(&vert, sizeof(vert)); vert.x = native_width; vert.y = 1.0f; vert.z = 1.0f; vert.u = u2; vert.v = v1; pvr_prim(&vert, sizeof(vert)); vert.x = 1.0f; vert.y = native_height; vert.z = 1.0f; vert.u = u1; vert.v = v2; pvr_prim(&vert, sizeof(vert)); vert.x = native_width; vert.y = native_height; vert.z = 1.0f; vert.u = u2; vert.v = v2; vert.flags = PVR_CMD_VERTEX_EOL; pvr_prim(&vert, sizeof(vert)); pvr_list_finish(); pvr_scene_finish(); opacity += 0.04f; } } void HideLogo() { float opacity = 1.0f; float w = native_width;//(float)DScreen->w; float h = native_height;//(float)DScreen->h; float u1 = 0.3f * (1.0f / ((float)logo_w)); float v1 = 0.3f * (1.0f / ((float)logo_w)); float u2 = (w + 0.5f) * (1.0f / ((float)logo_w)); float v2 = (h + 0.5f) * (1.0f / ((float)logo_h)); pvr_poly_cxt_t cxt; pvr_poly_hdr_t hdr; pvr_vertex_t vert; if(!logo_txr) { scr_fade_act = 1; return; } while(opacity > 0.0f) { pvr_wait_ready(); pvr_scene_begin(); pvr_list_begin(PVR_LIST_TR_POLY); pvr_poly_cxt_txr(&cxt, PVR_LIST_TR_POLY, PVR_TXRFMT_RGB565, logo_w, logo_h, logo_txr, PVR_FILTER_BILINEAR); pvr_poly_compile(&hdr, &cxt); pvr_prim(&hdr, sizeof(hdr)); vert.argb = PVR_PACK_COLOR(opacity, 1.0f, 1.0f, 1.0f); vert.oargb = 0; vert.flags = PVR_CMD_VERTEX; vert.x = 1.0f; vert.y = 1.0f; vert.z = 1.0f; vert.u = u1; vert.v = v1; pvr_prim(&vert, sizeof(vert)); vert.x = native_width; vert.y = 1.0f; vert.z = 1.0f; vert.u = u2; vert.v = v1; pvr_prim(&vert, sizeof(vert)); vert.x = 1.0f; vert.y = native_height; vert.z = 1.0f; vert.u = u1; vert.v = v2; pvr_prim(&vert, sizeof(vert)); vert.x = native_width; vert.y = native_height; vert.z = 1.0f; vert.u = u2; vert.v = v2; vert.flags = PVR_CMD_VERTEX_EOL; pvr_prim(&vert, sizeof(vert)); pvr_list_finish(); pvr_scene_finish(); opacity -= 0.05f; } pvr_mem_free(logo_txr); scr_fade_act = 1; if(!video_inited) { InitVideoThread(); } } <file_sep>/applications/vmu_manager/modules/vmdfs.c /* KallistiOS ##version## vmdfs.c Copyright (C) 2003 <NAME> Copyright (C) 2015 megavolt85 */ #include <stdio.h> #include <string.h> #include <malloc.h> #include <time.h> #include <kos/mutex.h> #include "fs_vmd.h" #include <ds.h> #define BLOCK_SIZE 512 /* This is a whole new module that sits between the fs_vmd module and the maple VMD driver. It's based loosely on the stuff in the old fs_vmd, but it's been rewritten and reworked to be clearer, more clean, use threads better, etc. Unlike the fs_vmd module, this code is stateless. You make a call and you get back data (or have written it). There are no handles involved or anything else like that. The new fs_vmd sits on top of this and provides a (mostly) nice VFS interface similar to the old fs_vmd. This module tends to do more work than it really needs to for some functions (like reading a named file) but it does it that way to have very clear, concise code that can be audited for bugs more easily. It's not like you load and save on the VMD every frame or something. ;) But the user may never give your program another frame of time if it corrupts their save games! If you want better control to save loading and saving stuff for a big batch of changes, then use the low-level funcs. Function comments located in vmdfs.h. */ /* ****************** Low level functions ******************** */ /* We need some sort of access control here for threads. This is somewhat less than optimal (one mutex for all VMDs) but I doubt it'll really be much of an issue :) */ static mutex_t mutex; static int vmdfs_dir_blocks(vmd_root_t * root_buf) { return root_buf->dir_size * 512; } static int vmdfs_fat_blocks(vmd_root_t * root_buf) { return root_buf->fat_size * 512; } /* Common code for both dir_read and dir_write */ static int vmdfs_dir_read(const char *vmdfile, vmd_root_t * root, vmd_dir_t * dir_buf) { uint16 dir_block, dir_size; unsigned int i; int needsop;//, rv; int write = 0; /* Find the directory starting block and length */ dir_block = root->dir_loc; dir_size = root->dir_size; /* The dir is stored backwards, so we start at the end and go back. */ while(dir_size > 0) { if(write) { /* Scan this block for changes */ for(i = 0, needsop = 0; i < 512 / sizeof(vmd_dir_t); i++) { if(dir_buf[i].dirty) { needsop = 1; } dir_buf[i].dirty = 0; } } else needsop = 1; if(needsop) { if(!write){ file_t f = fs_open(vmdfile,O_RDONLY); fs_seek(f,dir_block*BLOCK_SIZE,SEEK_SET); fs_read(f,(uint8 *)dir_buf,BLOCK_SIZE); fs_close(f); } } dir_block--; dir_size--; dir_buf += 512 / sizeof(vmd_dir_t); /* == 16 */ } return 0; } /* Common code for both fat_read and fat_write */ static int vmdfs_fat_read(const char *vmdfile, vmd_root_t * root, uint16 * fat_buf) { uint16 fat_block, fat_size; /* Find the FAT starting block and length */ fat_block = root->fat_loc; fat_size = root->fat_size; /* We can't reliably handle VMDs with a larger FAT... */ if(fat_size > 1) { dbglog(DBG_ERROR, "vmdfs_fat_read: VMD has >1 (%d) FAT blocks\n",(int)fat_size); return -1; } file_t f = fs_open(vmdfile,O_RDONLY); fs_seek(f,fat_block*BLOCK_SIZE,SEEK_SET); fs_read(f,(uint8 *)fat_buf,BLOCK_SIZE); fs_close(f); if(!*fat_buf) { dbglog(DBG_ERROR, "vmdfs_fat_read: can't read block %d\n",(int)fat_block); return -2; } return 0; } static int vmdfs_dir_find(vmd_root_t * root, vmd_dir_t * dir, const char * fn) { int i; int dcnt; dcnt = root->dir_size * 512 / sizeof(vmd_dir_t); for(i = 0; i < dcnt; i++) { /* Not a file -> skip it */ if(dir[i].filetype == 0) continue; /* Check the filename */ if(!strncmp(fn, dir[i].filename, 12)) return i; } /* Didn't find anything */ return -1; } static int vmdfs_file_read(const char *vmdfile, uint16 * fat, vmd_dir_t * dirent, void * outbuf) { int curblk, blkleft; uint8 * out; out = (uint8 *)outbuf; /* Find the first block */ curblk = dirent->firstblk; /* And the blocks remaining */ blkleft = dirent->filesize; /* While we've got stuff remaining... */ while(blkleft > 0) { /* Make sure the FAT matches up with the directory */ if(curblk == 0xfffc || curblk == 0xfffa) { char fn[13] = {0}; memcpy(fn, dirent->filename, 12); dbglog(DBG_ERROR, "vmdfs_file_read: file '%s' ends prematurely in fat\n",fn); return -1; } /* Read the block */ file_t f = fs_open(vmdfile,O_RDONLY); fs_seek(f,curblk*BLOCK_SIZE,SEEK_SET); int rv = fs_read(f,(uint8 *)out,BLOCK_SIZE); fs_close(f); if(rv != BLOCK_SIZE) { dbglog(DBG_ERROR, "vmdfs_file_read: can't read block %d\n",curblk); return -2; } /* Scoot our counters */ curblk = fat[curblk]; blkleft--; out += 512; } /* Make sure the FAT matches up with the directory */ if(curblk != 0xfffa) { char fn[13] = {0}; memcpy(fn, dirent->filename, 12); dbglog(DBG_ERROR, "vmdfs_file_read: file '%s' is sized shorter than in the FAT\n",fn); return -3; } return 0; } static int vmdfs_mutex_lock() { return mutex_lock(&mutex); } static int vmdfs_mutex_unlock() { return mutex_unlock(&mutex); } /* ****************** Higher level functions ******************** */ /* Internal function gets everything setup for you */ static int vmdfs_setup(const char *vmdfile, vmd_root_t * root, vmd_dir_t ** dir, int * dirsize, uint16 ** fat, int * fatsize) { /* Check to make sure this is a valid device right now */ if(!FileExists(vmdfile)) { dbglog(DBG_ERROR, "vmdfs_setup: vmd file is invalid\n"); return -1; } vmdfs_mutex_lock(); /* Read its root block */ file_t f = fs_open(vmdfile,O_RDONLY); fs_seek(f,255*BLOCK_SIZE,SEEK_SET); fs_read(f,(uint8 *)root,BLOCK_SIZE); fs_close(f); if(!root) goto dead; if(dir) { /* Alloc enough space for the whole dir */ *dirsize = vmdfs_dir_blocks(root); *dir = (vmd_dir_t *)malloc(*dirsize); if(!*dir) { dbglog(DBG_ERROR, "vmdfs_setup: can't alloc %d bytes for dir\n",*dirsize); goto dead; } /* Read it */ if(vmdfs_dir_read(vmdfile, root, *dir) < 0) { free(*dir); *dir = NULL; goto dead; } } if(fat) { /* Alloc enough space for the fat */ *fatsize = vmdfs_fat_blocks(root); *fat = (uint16 *)malloc(*fatsize); if(!*fat) { dbglog(DBG_ERROR, "vmdfs_setup: can't alloc %d bytes for FAT\n",*fatsize); goto dead; } /* Read it */ if(vmdfs_fat_read(vmdfile, root, *fat) < 0) goto dead; } /* Ok, everything's cool */ return 0; dead: vmdfs_mutex_unlock(); return -1; } /* Internal function to tear everything down for you */ static void vmdfs_teardown(vmd_dir_t * dir, uint16 * fat) { if(dir) free(dir); if(fat) free(fat); vmdfs_mutex_unlock(); } int vmdfs_readdir(const char *vmdfile, vmd_dir_t ** outbuf, int * outcnt) { vmd_root_t root; vmd_dir_t *dir; int dircnt, dirsize, rv = 0; unsigned int i, j; *outbuf = NULL; *outcnt = 0; /* Init everything */ if(vmdfs_setup(vmdfile, &root, &dir, &dirsize, NULL, NULL) < 0) return -1; /* Go through and move all entries to the lowest-numbered spots. */ dircnt = 0; for(i = 0; i < dirsize / sizeof(vmd_dir_t); i++) { /* Skip blanks */ if(dir[i].filetype == 0) continue; /* Not a blank -- look for an earlier slot that's empty. If we don't find one, just leave it alone. */ for(j = 0; j < i; j++) { if(dir[j].filetype == 0) { memcpy(dir + j, dir + i, sizeof(vmd_dir_t)); dir[i].filetype = 0; break; } } /* Update the entry count */ dircnt++; } /* Resize the buffer to match the number of entries */ *outcnt = dircnt; *outbuf = (vmd_dir_t *)realloc(dir, dircnt * sizeof(vmd_dir_t)); if(!*outbuf && dircnt) { dbglog(DBG_ERROR, "vmdfs_readdir: can't realloc %d bytes for dir\n",dircnt * sizeof(vmd_dir_t)); free(dir); rv = -2; goto ex; } ex: vmdfs_teardown(NULL, NULL); return rv; } /* Shared code between read/read_dirent */ static int vmdfs_read_common(const char *vmdfile, vmd_dir_t * dirent, uint16 * fat, void ** outbuf, int * outsize) { /* Allocate the output space */ *outsize = dirent->filesize * 512; *outbuf = malloc(*outsize); if(!*outbuf) { dbglog(DBG_ERROR, "vmdfs_read: can't alloc %d bytes for reading a file\n",*outsize); return -1; } /* Ok, go ahead and read it */ if(vmdfs_file_read(vmdfile, fat, dirent, *outbuf) < 0) { free(*outbuf); *outbuf = NULL; *outsize = 0; return -1; } return 0; } int vmdfs_read(const char *vmdfile, const char * fn, void ** outbuf, int * outsize) { vmd_root_t root; vmd_dir_t * dir = NULL; uint16 * fat = NULL; int fatsize, dirsize, idx, rv = 0; *outbuf = NULL; *outsize = 0; /* Init everything */ if(vmdfs_setup(vmdfile, &root, &dir, &dirsize, &fat, &fatsize) < 0) return -1; /* Look for the file we want */ idx = vmdfs_dir_find(&root, dir, fn); if(idx < 0) { dbglog(DBG_ERROR, "vmdfs_read: can't find file '%s'\n",fn); rv = -2; goto ex; } if(vmdfs_read_common(vmdfile, dir + idx, fat, outbuf, outsize) < 0) { rv = -3; goto ex; } ex: vmdfs_teardown(dir, fat); return rv; } int vmdfs_init() { mutex_init(&mutex, MUTEX_TYPE_NORMAL); return 0; } int vmdfs_shutdown() { mutex_destroy(&mutex); return 0; } <file_sep>/include/drivers/g2_ide.h /* KallistiOS ##version## navi/ide.h (c)2002 <NAME> */ #ifndef __NAVI_IDE_H #define __NAVI_IDE_H #include <arch/types.h> /* Read n sectors from the hard disk using PIO mode */ int ide_read(uint32 linear,uint32 numsects, void *bufptr); /* Write n sectors to the hard disk using PIO mode */ int ide_write(uint32 linear,uint32 numsects, void *bufptr); /* Get the available space */ uint32 ide_num_sectors(); /* Init/Shutdown the device */ int ide_init(); void ide_shutdown(); #endif /* __NAVI_IDE_H */ <file_sep>/include/cmd_elf.h /** * \file cmd_elf.h * \brief DreamShell external binary commands * \date 2007-2014 * \author SWAT www.dc-swat.ru */ #include <sys/cdefs.h> #include <arch/types.h> /* Kernel-specific definition of a loaded ELF binary */ typedef struct cmd_elf_prog { void *data; /* Data block containing the program */ uint32 size; /* Memory image size (rounded up to page size) */ /* Elf exports */ ptr_t main; } cmd_elf_prog_t; /* Load an ELF binary and return the relevant data in an cmd_elf_prog_t structure. */ cmd_elf_prog_t *cmd_elf_load(const char *fn); /* Free a loaded ELF program */ void cmd_elf_free(cmd_elf_prog_t *prog); <file_sep>/firmware/isoldr/loader/syscalls.c /** * DreamShell ISO Loader * BIOS syscalls emulation * (c)2009-2022 SWAT <http://www.dc-swat.ru> */ #include <main.h> #include <exception.h> #include <asic.h> #include <mmu.h> #include <cdda.h> #include <maple.h> #include <arch/cache.h> #include <arch/timer.h> #include <arch/gdb.h> #ifdef DEV_TYPE_SD #include <spi.h> #endif /** * Current GD channel state */ static gd_state_t _GDS; /** * Getting GD channel state */ gd_state_t *get_GDS(void) { return &_GDS; } static void reset_GDS(gd_state_t *GDS) { GDS->cmd = GDS->status = GDS->requested = GDS->transfered = GDS->ata_status = 0; memset(&GDS->param, 0, sizeof(GDS->param)); // memset(GDS, 0, sizeof(int) * 12); GDS->lba = 150; GDS->req_count = 0; GDS->drv_stat = CD_STATUS_PAUSED; GDS->drv_media = IsoInfo->exec.type == BIN_TYPE_KOS ? CD_CDROM_XA : CD_GDROM; GDS->cdda_stat = SCD_AUDIO_STATUS_NO_INFO; GDS->cdda_track = 0; GDS->disc_change = 0; GDS->disc_num = 0; GDS->gdc.sec_size = 2048; GDS->gdc.mode = 2048; GDS->gdc.flags = 8192; if(GDS->true_async == 0 #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) && IsoInfo->use_dma && !IsoInfo->emu_async #elif defined(DEV_TYPE_SD) && IsoInfo->emu_async #endif && IsoInfo->sector_size == 2048 && IsoInfo->image_type != ISOFS_IMAGE_TYPE_CSO && IsoInfo->image_type != ISOFS_IMAGE_TYPE_ZSO ) { #if defined(DEV_TYPE_SD) /* Increase sectors count up to 1.5 if the emu async = 1 */ IsoInfo->emu_async = IsoInfo->emu_async == 1 ? 6 : (IsoInfo->emu_async << 2); #endif GDS->true_async = 1; } } /* This lock function needed for access to flashrom/bootrom */ static inline void lock_gdsys_wait(void) { /* Wait GD syscalls if they in process */ while(_GDS.status == CMD_STAT_PROCESSING) vid_waitvbl(); /* Lock GD syscalls */ while(lock_gdsys()) vid_waitvbl(); #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) /* Wait G1 DMA complete because CDDA emulation can use it */ while(g1_dma_in_progress()) vid_waitvbl(); #endif } #ifdef LOG static const char cmd_name[48][18] = { {0}, {0}, {"CHECK_LICENSE"}, {0}, {"REQ_SPI_CMD"}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {"PIOREAD"}, {"DMAREAD"}, {"GETTOC"}, {"GETTOC2"}, {"PLAY"}, {"PLAY2"}, {"PAUSE"}, {"RELEASE"}, {"INIT"}, {"DMA_ABORT"}, {"OPEN_TRAY"}, {"SEEK"}, {"DMAREAD_STREAM"}, {"NOP"}, {"REQ_MODE"}, {"SET_MODE"}, {"SCAN_CD"}, {"STOP"}, {"GETSCD"}, {"GETSES"}, {"REQ_STAT"}, {"PIOREAD_STREAM"}, {"DMAREAD_STREAM_EX"}, {"PIOREAD_STREAM_EX"}, {"GETVER"}, {0}, {0}, {0}, {0}, {0} }; static const char stat_name[8][12] = { {"FAILED"}, {"IDLE"}, {"PROCESSING"}, {"COMPLETED"}, {"STREAMING"}, {0} }; #endif /** * Params count for commands */ static uint8 cmdp[] = { 4, 4, 2, 2, 3, 3, 0, 0, 0, 0, 0, 1, 2, 4, 1, 4, 2, 0, 3, 3, 4, 2, 3, 3, 1 }; static inline int get_params_count(int cmd) { if(cmd < 16 || cmd > 40) { return 0; } return cmdp[cmd - 16]; } /** * Get TOC syscall */ static void GetTOC() { gd_state_t *GDS = get_GDS(); CDROM_TOC *toc = (CDROM_TOC*)GDS->param[1]; GDS->transfered = sizeof(CDROM_TOC); DBGF("%s: ", __func__); memcpy(toc, &IsoInfo->toc, sizeof(CDROM_TOC)); if(IsoInfo->image_type == ISOFS_IMAGE_TYPE_CDI || IsoInfo->image_type == ISOFS_IMAGE_TYPE_GDI || IsoInfo->track_lba[0] == 45150) { LOGF("Get TOC from %cDI image and prepare for session %d\n", (IsoInfo->image_type == ISOFS_IMAGE_TYPE_CDI ? 'C' : 'G'), GDS->param[0] + 1); if(GDS->param[0] == 0) { /* Session 1 */ if(IsoInfo->image_type == ISOFS_IMAGE_TYPE_GDI || IsoInfo->track_lba[0] == 45150) { toc->first = (toc->first & 0xfff0ffff) | (1 << 16); toc->last = (toc->last & 0xfff0ffff) | (2 << 16); for(int i = 2; i < 99; i++) { toc->entry[i] = (uint32)-1; } toc->leadout_sector = 0x01001A2C; } else { for(int i = 99; i > 0; i--) { if(TOC_CTRL(toc->entry[i - 1]) == 4) { toc->entry[i - 1] = (uint32)-1; } } int lt = (toc->last & 0x000f0000) >> 16; toc->last = (toc->last & 0xfff0ffff) | (--lt << 16); } } else { /* Session 2 */ if(IsoInfo->image_type == ISOFS_IMAGE_TYPE_CDI) { toc->entry[0] = (uint32)-1; for(int i = 99; i > 0; i--) { if(TOC_CTRL(toc->entry[i - 1]) == 4) { toc->first = (toc->first & 0xfff0ffff) | (i << 16); } } } else if(IsoInfo->image_type == ISOFS_IMAGE_TYPE_GDI || IsoInfo->track_lba[0] == 45150) { toc->entry[0] = (uint32)-1; toc->entry[1] = (uint32)-1; } } } else { LOGF("Custom TOC with LBA %d\n", IsoInfo->track_lba[0]); } GDS->status = CMD_STAT_COMPLETED; } /** * Get session info syscall */ static void get_session_info() { gd_state_t *GDS = get_GDS(); uint8 *buf = (uint8 *)GDS->param[2]; uint32 lba = IsoInfo->toc.leadout_sector; buf[0] = CD_STATUS_PAUSED; buf[1] = 0; buf[2] = 1; buf[3] = (lba >> 16) & 0xFF; buf[4] = (lba >> 8) & 0xFF; buf[5] = lba & 0xFF; GDS->transfered = 6; GDS->status = CMD_STAT_COMPLETED; } /* GD? */ static uint8 scd_all[100] = { 0x00, 0x15, 0x00, 0x64, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x00, 0x40, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 }; /* CD */ //static uint8 scd_all[100] = { // 0x00, 0x15, 0x00, 0x64, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, // 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, // 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, // 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x40, // 0x40, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x40, 0x00, // 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x00, // 0x00, 0x40, 0x00, 0x00 //}; //static uint8 scd_q[14] = { // 0x00, 0x15, 0x00, 0x0E, 0x41, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // 0x00, 0x96 //}; static uint8 scd_media[24] = { 0x00, 0x15, 0x00, 0x18, 0x02, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00 }; static uint8 scd_isrc[24] = { 0x00, 0x15, 0x00, 0x18, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00 }; //static uint32 scd_delay = 0; /** * Get sub channel data syscall */ static void get_scd() { gd_state_t *GDS = get_GDS(); uint8 *buf = (uint8 *)GDS->param[2]; uint32 offset = GDS->lba - 150; switch(GDS->param[0] & 0xF) { case SCD_REQ_ALL_SUBCODE: memcpy(buf, &scd_all, scd_all[SCD_DATA_SIZE_INDEX]); buf[1] = GDS->cdda_stat; GDS->transfered = scd_all[SCD_DATA_SIZE_INDEX]; break; case SCD_REQ_Q_SUBCODE: buf[0] = 0x00; // Reserved buf[1] = GDS->cdda_stat; // Audio Status buf[2] = 0x00; // DATA Length MSB buf[3] = 0x0E; // DATA Length LSB if(GDS->cdda_track) { buf[4] = 0x01; // Track flags (CTRL and ADR) buf[5] = GDS->cdda_track; // Track NO buf[6] = GDS->cdda_track; // 00: Pause area 01-99: Index number } else { buf[4] = 0x41; // Track flags (CTRL and ADR) buf[5] = GDS->data_track; // Track NO buf[6] = GDS->data_track; // 00: Pause area 01-99: Index number } buf[7] = (offset >> 16) & 0xFF; buf[8] = (offset >> 8) & 0xFF; buf[9] = (offset & 0xFF); buf[10] = 0x00; // Reserved buf[11] = (GDS->lba >> 16) & 0xFF; buf[12] = (GDS->lba >> 8) & 0xFF; buf[13] = GDS->lba & 0xFF; GDS->transfered = buf[SCD_DATA_SIZE_INDEX]; break; case SCD_REQ_MEDIA_CATALOG: memcpy(buf, &scd_media, scd_media[SCD_DATA_SIZE_INDEX]); // buf[0] = 0x00; // Reserved buf[1] = GDS->cdda_stat; // Audio Status // buf[2] = 0x00; // DATA Length MSB // buf[3] = 0x18; // DATA Length LSB // buf[4] = 0x02; // Format Code GDS->transfered = scd_media[SCD_DATA_SIZE_INDEX]; break; case SCD_REQ_ISRC: memcpy(buf, &scd_isrc, scd_isrc[SCD_DATA_SIZE_INDEX]); // buf[0] = 0x00; // Reserved buf[1] = GDS->cdda_stat; // Audio Status // buf[2] = 0x00; // DATA Length MSB // buf[3] = 0x18; // DATA Length LSB // buf[4] = 0x03; // Format Code GDS->transfered = scd_isrc[SCD_DATA_SIZE_INDEX]; break; default: break; } GDS->status = CMD_STAT_COMPLETED; } /** * Request stat syscall */ void get_stat(void) { gd_state_t *GDS = get_GDS(); #ifdef HAVE_CDDA cdda_ctx_t *cdda = get_CDDA(); *((uint32*)GDS->param[0]) = cdda->loop; #else *((uint32*)GDS->param[0]) = 0; #endif if(GDS->cdda_track) { *((uint32 *)GDS->param[1]) = GDS->cdda_track; *((uint32 *)GDS->param[2]) = 0x01 << 24 | GDS->lba; } else { *((uint32 *)GDS->param[1]) = GDS->data_track; *((uint32 *)GDS->param[2]) = 0x41 << 24 | GDS->lba; } *((uint32 *)GDS->param[3]) = 1; /* X (Subcode Q index) */ GDS->status = CMD_STAT_COMPLETED; } /** * Get GDC version syscall */ static void get_ver_str() { gd_state_t *GDS = get_GDS(); char *buf = (char *)GDS->param[0]; memcpy(buf, "GDC Version 1.10 1999-03-31", 27); buf[27] = 0x02; /* Some value from GDS */ GDS->status = CMD_STAT_COMPLETED; } #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) static void g1_ata_data_wait(gd_state_t *GDS) { GDS->ata_status = CMD_WAIT_DRQ_0; do { gdcExitToGame(); if (pre_read_xfer_done()) { break; } } while(GDS->cmd_abort == 0); GDS->ata_status = CMD_WAIT_IRQ; GDS->status = CMD_STAT_STREAMING; pre_read_xfer_end(); } #endif #ifdef _FS_ASYNC static void data_transfer_cb(size_t size) { (void)size; } void data_transfer_true_async() { gd_state_t *GDS = get_GDS(); #if defined(DEV_TYPE_SD) fs_enable_dma(IsoInfo->emu_async); #elif defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) fs_enable_dma(FS_DMA_SHARED); #endif #if 0//defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) // Simulate packet command interrupt. uint32 lba = 0; ioctl(iso_fd, FS_IOCTL_GET_LBA, &lba); g1_ata_raise_interrupt(lba); g1_ata_data_wait(GDS); #endif GDS->status = ReadSectors((uint8 *)GDS->param[2], GDS->param[0], GDS->param[1], data_transfer_cb); if(GDS->status != CMD_STAT_PROCESSING) { LOGFF("ERROR, status %d\n", GDS->status); GDS->ata_status = CMD_WAIT_INTERNAL; return; } while(1) { gdcExitToGame(); int ps = poll(iso_fd); if (ps < 0) { GDS->cmd_abort = 1; break; } else if(ps > 1) { GDS->transfered = ps; } else if(ps == 0 && pre_read_xfer_done()) { break; } } gdcExitToGame(); pre_read_xfer_end(); GDS->requested = 0; GDS->ata_status = CMD_WAIT_INTERNAL; if (GDS->cmd_abort) { abort_async(iso_fd); GDS->transfered = 0; GDS->status = CMD_STAT_IDLE; } else { GDS->transfered = GDS->param[1] * GDS->gdc.sec_size; GDS->status = CMD_STAT_COMPLETED; } GDS->drv_stat = CD_STATUS_PAUSED; #ifdef DEV_TYPE_SD dcache_purge_range(GDS->param[2], GDS->transfered); #endif } #endif /* _FS_ASYNC */ void data_transfer_emu_async() { gd_state_t *GDS = get_GDS(); uint sc, sc_size; while(GDS->param[1] > 0 && GDS->cmd_abort == 0) { if(GDS->param[1] <= (uint32)IsoInfo->emu_async) { sc = GDS->param[1]; } else { sc = IsoInfo->emu_async; } #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) if(IsoInfo->use_dma) { fs_enable_dma((GDS->param[1] - sc) > 0 ? FS_DMA_HIDDEN : FS_DMA_SHARED); } else { fs_enable_dma(FS_DMA_DISABLED); } #endif sc_size = (GDS->gdc.sec_size * sc); if(ReadSectors((uint8*)GDS->param[2], GDS->param[0], sc, NULL) == CMD_STAT_FAILED) { GDS->status = CMD_STAT_FAILED; return; } GDS->param[1] -= sc; GDS->transfered += sc_size; if(GDS->cmd != CMD_PIOREAD #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) && !IsoInfo->use_dma #endif ) { dcache_purge_range(GDS->param[2], sc_size); } if(GDS->param[1] <= 0) { GDS->status = CMD_STAT_COMPLETED; GDS->requested -= GDS->transfered; GDS->drv_stat = CD_STATUS_PAUSED; return; } GDS->param[2] += sc_size; GDS->param[0] += sc; DBGFF("%s %d %d\n", stat_name[GDS->status + 1], GDS->req_count, GDS->transfered); gdcExitToGame(); } } /** * Data transfer */ void data_transfer() { gd_state_t *GDS = get_GDS(); GDS->ata_status = CMD_WAIT_IRQ; #ifdef _FS_ASYNC /* Use true async DMA transfer (or pseudo async for SD) */ if(GDS->cmd == CMD_DMAREAD && GDS->true_async # ifdef DEV_TYPE_SD /* Doesn't use pseudo async for SD in some cases (improve the general loading speed) */ && GDS->param[1] > 1 && GDS->param[1] < 100 # endif ) { data_transfer_true_async(); return; } # ifndef DEV_TYPE_SD else { fs_enable_dma((GDS->cmd == CMD_DMAREAD && IsoInfo->use_dma) ? FS_DMA_SHARED : FS_DMA_DISABLED); } # endif #endif /* _FS_ASYNC */ /** * Read if emu async is disabled or if requested 1/100 sector(s) * * 100 sectors is additional optimization. * It's looks like the game in loading state (request big data), * so we can increase general loading speed if load it for one frame */ if(!IsoInfo->emu_async #ifdef DEV_TYPE_SD || GDS->param[1] == 1 || GDS->param[1] >= 100 #endif ) { GDS->status = ReadSectors((uint8 *)GDS->param[2], GDS->param[0], GDS->param[1], NULL); GDS->transfered = (GDS->param[1] * GDS->gdc.sec_size); GDS->ata_status = CMD_WAIT_INTERNAL; GDS->requested -= GDS->transfered; if(GDS->cmd != CMD_PIOREAD #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) && !IsoInfo->use_dma #endif ) { dcache_purge_range(GDS->param[2], GDS->param[1] * GDS->gdc.sec_size); } GDS->drv_stat = CD_STATUS_PAUSED; DBGFF("%s %d %d\n", stat_name[GDS->status + 1], GDS->req_count, GDS->transfered); return; } /* Read in PIO/DMA mode with emu async (if true async disabled or can't be used) */ data_transfer_emu_async(); } static void data_transfer_dma_stream() { gd_state_t *GDS = get_GDS(); fs_enable_dma(FS_DMA_SHARED); #if 0//defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) // Simulate packet command interrupt. uint32 lba = 0; ioctl(iso_fd, FS_IOCTL_GET_LBA, &lba); g1_ata_raise_interrupt(lba); g1_ata_data_wait(GDS); #endif GDS->status = PreReadSectors(GDS->param[0], GDS->param[1]); if(GDS->status != CMD_STAT_PROCESSING) { GDS->ata_status = CMD_WAIT_INTERNAL; GDS->drv_stat = CD_STATUS_PAUSED; return; } GDS->status = CMD_STAT_STREAMING; while(1) { gdcExitToGame(); if (pre_read_xfer_busy()) { GDS->transfered = pre_read_xfer_size(); } if(pre_read_xfer_done()) { pre_read_xfer_end(); GDS->transfered = pre_read_xfer_size(); GDS->ata_status = CMD_WAIT_INTERNAL; if(GDS->requested == 0) { GDS->status = CMD_STAT_COMPLETED; break; } } if(GDS->cmd_abort) { GDS->ata_status = CMD_WAIT_INTERNAL; GDS->status = CMD_STAT_IDLE; pre_read_xfer_abort(); break; } } GDS->drv_stat = CD_STATUS_PAUSED; } static void data_transfer_pio_stream() { gd_state_t *GDS = get_GDS(); fs_enable_dma(FS_DMA_DISABLED); GDS->status = PreReadSectors(GDS->param[0], GDS->param[1]); if(GDS->status != CMD_STAT_PROCESSING) { GDS->drv_stat = CD_STATUS_PAUSED; return; } #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) g1_ata_data_wait(GDS); #endif while(1) { if(GDS->param[2] != 0) { pre_read_xfer_start(GDS->param[2], GDS->param[1]); GDS->ata_status = CMD_WAIT_IRQ; GDS->transfered += GDS->param[1]; GDS->requested -= GDS->param[1]; GDS->param[2] = 0; if(GDS->callback != 0) { void (*callback)() = (void (*)())(GDS->callback); callback(GDS->callback_param); } } if(pre_read_xfer_done()) { pre_read_xfer_end(); if(GDS->requested == 0) { GDS->ata_status = CMD_WAIT_INTERNAL; GDS->status = CMD_STAT_COMPLETED; break; } else { GDS->ata_status = CMD_WAIT_DRQ_0; } } if(GDS->cmd_abort) { GDS->ata_status = CMD_WAIT_INTERNAL; GDS->status = CMD_STAT_IDLE; pre_read_xfer_abort(); break; } gdcExitToGame(); } GDS->drv_stat = CD_STATUS_PAUSED; } static int init_cmd() { #ifdef HAVE_EXPT if(IsoInfo->use_irq) { int old = irq_disable(); /* Injection to exception handling */ if (!exception_init(0)) { /* Use ASIC interrupts */ asic_init(); # if defined(DEV_TYPE_GD) || defined(DEV_TYPE_IDE) /* Initialize G1 DMA interrupt */ if (IsoInfo->use_dma) { g1_dma_init_irq(); } # endif # ifdef HAVE_MAPLE if(IsoInfo->emu_vmu) { maple_init_irq(); } # endif } irq_restore(old); # ifdef HAVE_GDB gdb_init(); } else { int old = irq_disable(); int rs = exception_init(0); irq_restore(old); if(!rs) { gdb_init(); } } # else } # endif /* HAVE_GDB */ #endif /* HAVE_EXPT */ if (!malloc_init(0)) { InitReader(); #ifdef HAVE_CDDA if(IsoInfo->emu_cdda) { CDDA_Init(); } #endif #ifdef HAVE_MAPLE if(IsoInfo->emu_vmu) { maple_init_vmu(IsoInfo->emu_vmu); } #endif } #ifdef DEV_TYPE_SD else { spi_init(); } #endif return CMD_STAT_COMPLETED; } static int is_transfer_cmd(int cmd) { if(cmd == CMD_PIOREAD || cmd == CMD_DMAREAD || cmd == CMD_DMAREAD_STREAM || cmd == CMD_DMAREAD_STREAM_EX || cmd == CMD_PIOREAD_STREAM || cmd == CMD_PIOREAD_STREAM_EX ) { return 1; } return 0; } /** * Request command syscall */ int gdcReqCmd(int cmd, uint32 *param) { int gd_chn = GDC_CHN_ERROR; OpenLog(); if(cmd > CMD_MAX || lock_gdsys()) { LOGFF("Busy\n"); return gd_chn; } gd_state_t *GDS = get_GDS(); if(GDS->status == CMD_STAT_IDLE) { /* I just simulate BIOS code =) */ if(GDS->req_count++ == 0) { GDS->req_count++; } GDS->cmd = cmd; GDS->status = CMD_STAT_PROCESSING; GDS->transfered = 0; GDS->ata_status = CMD_WAIT_INTERNAL; GDS->cmd_abort = 0; gd_chn = GDS->req_count; LOGFF("%d %s %d", cmd, (cmd_name[cmd] ? cmd_name[cmd] : "UNKNOWN"), gd_chn); for(int i = 0; i < get_params_count(cmd); i++) { GDS->param[i] = param[i]; LOGF(" %08lx", param[i]); } LOGF("\n"); if(is_transfer_cmd(GDS->cmd)) { #ifdef HAVE_CDDA /* Stop CDDA playback if it's used */ if(IsoInfo->emu_cdda && GDS->cdda_stat != SCD_AUDIO_STATUS_NO_INFO) { CDDA_Stop(); } #endif GDS->requested = GDS->param[1] * GDS->gdc.sec_size; if(cmd != CMD_PIOREAD && cmd != CMD_DMAREAD) { GDS->drv_stat = CD_STATUS_PAUSED; } else { GDS->drv_stat = CD_STATUS_PLAYING; } } } unlock_gdsys(); return gd_chn; } /** * Main loop */ void gdcMainLoop(void) { while(1) { gd_state_t *GDS = get_GDS(); DBGFF(NULL); if(!exception_inited()) { apply_patch_list(); } #ifdef HAVE_CDDA CDDA_MainLoop(); #endif #ifdef HAVE_SCREENSHOT if(IsoInfo->scr_hotkey && (GDS->status == CMD_STAT_IDLE || GDS->cmd == CMD_GETSCD) ) { int old = irq_disable(); do {} while (pre_read_xfer_busy() != 0); video_screenshot(); irq_restore(old); } #endif if(GDS->status == CMD_STAT_PROCESSING) { switch (GDS->cmd) { case CMD_PIOREAD: case CMD_DMAREAD: data_transfer(); break; case CMD_DMAREAD_STREAM: case CMD_DMAREAD_STREAM_EX: data_transfer_dma_stream(); break; case CMD_PIOREAD_STREAM: case CMD_PIOREAD_STREAM_EX: data_transfer_pio_stream(); break; //case CMD_GETTOC: case CMD_GETTOC2: GetTOC(); break; case CMD_INIT: GDS->status = init_cmd(); break; case CMD_GET_VERS: get_ver_str(); break; case CMD_GETSES: get_session_info(); break; case CMD_GETSCD: get_scd(); break; #ifdef HAVE_CDDA case CMD_PLAY: GDS->status = CDDA_Play(GDS->param[0], GDS->param[1], GDS->param[2]); break; case CMD_PLAY2: GDS->status = CDDA_Play2(GDS->param[0], GDS->param[1], GDS->param[2]); break; case CMD_RELEASE: GDS->status = CDDA_Release(); break; case CMD_PAUSE: GDS->status = CDDA_Pause(); break; case CMD_SEEK: GDS->status = CDDA_Seek(GDS->param[0]); break; case CMD_STOP: GDS->status = CDDA_Stop(); break; #else case CMD_PLAY: case CMD_PLAY2: case CMD_RELEASE: GDS->status = CMD_STAT_COMPLETED; GDS->drv_stat = CD_STATUS_PLAYING; GDS->cdda_stat = SCD_AUDIO_STATUS_PLAYING; break; case CMD_PAUSE: case CMD_STOP: GDS->status = CMD_STAT_COMPLETED; GDS->drv_stat = CD_STATUS_PAUSED; GDS->cdda_stat = SCD_AUDIO_STATUS_PAUSED; break; case CMD_SEEK: GDS->status = CMD_STAT_COMPLETED; break; #endif case CMD_REQ_MODE: case CMD_SET_MODE: // TODO param[0] GDS->status = CMD_STAT_COMPLETED; break; case CMD_REQ_STAT: get_stat(); break; default: LOGF("Unhandled command %d %s, force complete status\n", GDS->cmd, (cmd_name[GDS->cmd] ? cmd_name[GDS->cmd] : "UNKNOWN")); GDS->status = CMD_STAT_COMPLETED; break; } } gdcExitToGame(); } } /** * Get status of the command syscall */ int gdcGetCmdStat(int gd_chn, uint32 *status) { if(lock_gdsys()) { LOGFF("%s: Busy\n"); return CMD_STAT_BUSY; } int rv = CMD_STAT_IDLE; gd_state_t *GDS = get_GDS(); memset(status, 0, sizeof(uint32) * 4); if(gd_chn == 0) { LOGFF("WARNING: id = %d\n", gd_chn); if(GDS->status != CMD_STAT_IDLE) { rv = CMD_STAT_PROCESSING; } unlock_gdsys(); return rv; } else if(gd_chn != GDS->req_count) { LOGFF("ERROR: %d != %d\n", gd_chn, GDS->req_count); status[0] = CMD_ERR_ILLEGALREQUEST; rv = CMD_STAT_FAILED; unlock_gdsys(); return rv; } switch(GDS->status) { case CMD_STAT_PROCESSING: status[2] = GDS->transfered; status[3] = GDS->ata_status; rv = CMD_STAT_PROCESSING; break; case CMD_STAT_COMPLETED: GDS->ata_status = CMD_WAIT_INTERNAL; GDS->status = CMD_STAT_IDLE; status[2] = GDS->transfered; status[3] = GDS->ata_status; rv = CMD_STAT_COMPLETED; break; case CMD_STAT_STREAMING: status[2] = GDS->transfered; status[3] = GDS->ata_status; rv = CMD_STAT_STREAMING; break; case CMD_STAT_FAILED: status[0] = CMD_ERR_HARDWARE; rv = CMD_STAT_FAILED; break; default: break; } unlock_gdsys(); DBGFF("%d %s\n", gd_chn, stat_name[rv + 1]); return rv; } /** * Get status of the drive syscall */ int gdcGetDrvStat(uint32 *status) { #ifdef HAVE_CDDA CDDA_MainLoop(); #endif if(lock_gdsys()) { DBGFF("Busy\n"); return CMD_STAT_BUSY; } DBGFF(NULL); gd_state_t *GDS = get_GDS(); if (GDS->disc_change) { GDS->disc_change++; if (GDS->disc_change == 2) { GDS->drv_media = CD_CDDA; GDS->drv_stat = CD_STATUS_OPEN; } else if (GDS->disc_change > 30) { GDS->drv_media = IsoInfo->exec.type == BIN_TYPE_KOS ? CD_CDROM_XA : CD_GDROM; GDS->drv_stat = CD_STATUS_PAUSED; GDS->disc_change = 0; unlock_gdsys(); return 2; } else { status[0] = GDS->drv_stat; status[1] = GDS->drv_media; unlock_gdsys(); return 1; } } status[0] = GDS->drv_stat; status[1] = GDS->drv_media; unlock_gdsys(); return 0; } /** * Set/Get data type syscall */ int gdcChangeDataType(int *param) { if(lock_gdsys()) { return CMD_STAT_BUSY; } gd_state_t *GDS = get_GDS(); if(param[0] == 0) { GDS->gdc.flags = param[1]; GDS->gdc.mode = param[2]; GDS->gdc.sec_size = param[3]; } else { param[1] = GDS->gdc.flags; param[2] = GDS->gdc.mode; param[3] = GDS->gdc.sec_size; } LOGFF("%s: unknown=%d mode=%d sector_size=%d\n", (param[0] == 0 ? "SET" : "GET"), param[1], param[2], param[3]); unlock_gdsys(); return 0; } /** * Initialize syscalls * This function calls from GDC ASM after saving registers */ void gdcInitSystem(void) { OpenLog(); LOGFF(NULL); #ifdef HAVE_CDDA /* Some games re-init syscalls without CDDA stopping */ gd_state_t *GDS = get_GDS(); if(IsoInfo->emu_cdda && GDS->cdda_stat != SCD_AUDIO_STATUS_NO_INFO) { CDDA_Stop(); } #endif reset_GDS(get_GDS()); gdcMainLoop(); } /** * Reset syscall */ void gdcReset(void) { LOGFF(NULL); gd_state_t *GDS = get_GDS(); reset_GDS(GDS); unlock_gdsys(); } /** * Read abort syscall */ int gdcReadAbort(int gd_chn) { LOGFF("%d\n", gd_chn); gd_state_t *GDS = get_GDS(); if(gd_chn != GDS->req_count) { return -1; } if(GDS->cmd_abort) { return -1; } switch(GDS->cmd) { #ifdef HAVE_CDDA case CMD_PLAY: case CMD_PLAY2: case CMD_PAUSE: CDDA_Stop(); return 0; #endif case CMD_PIOREAD: case CMD_DMAREAD: case CMD_SEEK: case CMD_NOP: case CMD_SCAN_CD: case CMD_STOP: case CMD_GETSCD: case CMD_DMAREAD_STREAM: case CMD_PIOREAD_STREAM: case CMD_DMAREAD_STREAM_EX: case CMD_PIOREAD_STREAM_EX: switch(GDS->status) { case CMD_STAT_PROCESSING: case CMD_STAT_STREAMING: case CMD_STAT_BUSY: GDS->cmd_abort = 1; return 0; default: return 0; } break; default: break; } return -1; } /** * Request DMA transfer syscall. * * In general this syscall should not be blocked * but we will work out all possible options. */ int gdcReqDmaTrans(int gd_chn, int *dmabuf) { gd_state_t *GDS = get_GDS(); LOGFF("%d %08lx %d %d %d\n", gd_chn, (uint32)dmabuf[0], dmabuf[1], GDS->requested, GDS->ata_status); if(gd_chn != GDS->req_count) { LOGF("ERROR: %d != %d\n", gd_chn, GDS->req_count); return -1; } if(GDS->status != CMD_STAT_STREAMING || GDS->requested < (uint32)dmabuf[1]) { LOGF("ERROR: status = %s, remain = %d, request = %d\n", stat_name[GDS->status + 1], GDS->requested, dmabuf[1]); return -1; } GDS->requested -= dmabuf[1]; pre_read_xfer_start(dmabuf[0], dmabuf[1]); return 0; } /** * Check DMA transfer syscall */ int gdcCheckDmaTrans(int gd_chn, int *size) { gd_state_t *GDS = get_GDS(); LOGFF("%d %ld %ld %d %d\n", gd_chn, GDS->requested, pre_read_xfer_size(), GDS->ata_status, pre_read_xfer_busy()); if(gd_chn != GDS->req_count) { LOGF("ERROR: %d != %d\n", gd_chn, GDS->req_count); return -1; } if(GDS->status != CMD_STAT_STREAMING) { LOGF("ERROR: status = %s\n", stat_name[GDS->status + 1]); return -1; } if(pre_read_xfer_busy()) { *size = pre_read_xfer_size(); return 1; } *size = GDS->requested; return 0; } /** * DMA transfer end syscall */ void gdcG1DmaEnd(uint32 func, uint32 param) { #ifdef LOG if (func) { LOGFF("%08lx %08lx\n", func, param); } #endif #if defined(DEV_TYPE_GD) || defined(DEV_TYPE_IDE) ASIC_IRQ_STATUS[ASIC_MASK_NRM_INT] = ASIC_NRM_GD_DMA; #endif if(func != 0) { void (*callback)() = (void (*)())(func); callback(param); } } void gdcSetPioCallback(uint32 func, uint32 param) { LOGFF("0x%08lx %ld\n", func, param); gd_state_t *GDS = get_GDS(); GDS->callback = func; GDS->callback_param = param; } int gdcReqPioTrans(int gd_chn, int *piobuf) { gd_state_t *GDS = get_GDS(); LOGFF("%d 0x%08lx %d (%d)\n", gd_chn, (uint32)piobuf[0], piobuf[1], GDS->requested); if(gd_chn != GDS->req_count) { LOGF("ERROR: %d != %d\n", gd_chn, GDS->req_count); return -1; } if(GDS->status != CMD_STAT_STREAMING || GDS->requested < (uint32)piobuf[1]) { LOGF("ERROR: status = %s, remain = %d, request = %d\n", stat_name[GDS->status + 1], GDS->requested, piobuf[1]); return -1; } GDS->param[2] = piobuf[0]; GDS->param[1] = piobuf[1]; return 0; } int gdcCheckPioTrans(int gd_chn, int *size) { gd_state_t *GDS = get_GDS(); LOGFF("%d %ld %ld\n", gd_chn, GDS->requested, GDS->transfered); if(gd_chn != GDS->req_count) { LOGF("ERROR: %d != %d\n", gd_chn, GDS->req_count); return -1; } if(GDS->status != CMD_STAT_STREAMING) { LOGF("ERROR: status = %s\n", stat_name[GDS->status + 1]); return -1; } if (GDS->param[2]) { *size = GDS->transfered; return 1; } *size = GDS->requested; return 0; } void gdGdcChangeDisc(int disc_num) { LOGFF("%d\n", disc_num); gd_state_t *GDS = get_GDS(); GDS->disc_change = 1; GDS->disc_num = disc_num; } void gdcDummy(int gd_chn, int *arg2) { LOGFF("%d 0x%08lx 0x%08lx\n", gd_chn, arg2[0], arg2[1]); (void)gd_chn; (void)arg2; } /** * Menu syscall */ void menu_exit(void) { LOGFF(NULL); shutdown_machine(); fs_enable_dma(FS_DMA_DISABLED); if (Load_DS() > 0) { launch(NONCACHED_ADDR(APP_ADDR)); } else { launch(0xa0000000); } } int menu_check_disc(void) { LOGFF(NULL); gd_state_t *GDS = get_GDS(); return GDS->drv_media; } /** * FlashROM syscalls */ int flashrom_info(int part, uint32 *info) { DBGFF("%d 0x%08lx\n", part, info); switch(part) { case 0: /* SYSTEM */ info[0] = 0x1A000; info[1] = 0x2000; break; case 1: /* RESERVED */ info[0] = 0x18000; info[1] = 0x2000; break; case 2: /* GAME INFO? */ info[0] = 0x1C000; info[1] = 0x4000; break; case 3: /* SETTINGS */ info[0] = 0x10000; info[1] = 0x8000; break; case 4: /* BLOCK 2 */ info[0] = 0; info[1] = 0x10000; break; default: info[0] = info[1] = 0; break; } return 0; } static void safe_memcpy(void* dst, const void* src, size_t cnt) { #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) do {} while(pre_read_xfer_busy()); #endif uint8 *d = (uint8*)dst; const uint8 *s = (const uint8*)src; while (cnt--) { *d++ = *s++; } } int flashrom_read(int offset, void *buffer, int bytes) { DBGFF("0x%08lx 0x%08lx %d\n", offset, (uint32)buffer, bytes); uint8 *src = (uint8 *)(0xa0200000 + offset); safe_memcpy(buffer, src, bytes); return 0; } int flashrom_write(int offset, void * buffer, int bytes) { DBGFF("0x%08lx 0x%08lx %d\n", offset, buffer, bytes); (void)offset; (void)buffer; (void)bytes; return 0; } int flashrom_delete(int offset) { DBGFF("0x%08lx\n", offset); (void)offset; return 0; } /** * Sysinfo syscalls */ int sys_misc_init(void) { LOGFF(NULL); // It's done by BIOS at startup. return 0; } int sys_unknown(void) { LOGFF(NULL); return 0; } int sys_icon(int icon, uint8 *dest) { LOGFF("%d 0x%08lx\n", icon, dest); safe_memcpy(dest, (uint8 *)(0xa021a480 + (icon * 704)), 704); return 704; } uint8 *sys_id(void) { LOGFF(NULL); return (uint8 *)0x8c000068; } void enable_syscalls(int all) { gdc_syscall_save(); gdc_syscall_disable(); gdc_syscall_enable(); menu_syscall_save(); menu_syscall_disable(); menu_syscall_enable(); if (!all) { printf("Syscalls emulation: gdc, menu\n"); return; } printf("Syscalls emulation: all\n"); bfont_syscall_save(); bfont_syscall_disable(); bfont_syscall_enable(); flash_syscall_save(); flash_syscall_disable(); flash_syscall_enable(); sys_syscall_save(); sys_syscall_disable(); sys_syscall_enable(); } void disable_syscalls(int all) { gdc_syscall_disable(); menu_syscall_disable(); if(all) { bfont_syscall_disable(); flash_syscall_disable(); sys_syscall_disable(); } } void restore_syscalls(void) { if (IsoInfo->syscalls == 0 && loader_addr >= ISOLDR_DEFAULT_ADDR_LOW) { disable_syscalls(0); } else if(loader_addr < ISOLDR_DEFAULT_ADDR_LOW || (IsoInfo->heap >= HEAP_MODE_SPECIFY && IsoInfo->heap < ISOLDR_DEFAULT_ADDR_LOW)) { // FIXME: Restore syscalls from BIOS } } /* Patch the GDC driver in the BIOS syscalls */ void gdc_syscall_patch(void) { size_t size = bios_patch_end - bios_patch_base; uint32 second_offset = 0xf0; if(loader_addr > (GDC_SYS_ADDR + second_offset + size)) { bios_patch_handler = gdc_redir; memcpy((uint32 *) GDC_SYS_ADDR, bios_patch_base, size); memcpy((uint32 *) (GDC_SYS_ADDR + second_offset), bios_patch_base, size); size += second_offset; icache_flush_range(GDC_SYS_ADDR, size); dcache_flush_range(GDC_SYS_ADDR, size); } else { patch_memory(0x8c0010f0, (uint32)gdc_redir); } } <file_sep>/modules/mp3/libmp3/xingmp3/csbtL3.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** csbtL3.c *************************************************** layer III include to csbt.c ******************************************************************/ /*============================================================*/ /*============ Layer III =====================================*/ /*============================================================*/ void sbt_mono_L3(MPEG *m, float *sample, short *pcm, int ch) { int i; ch = 0; for (i = 0; i < 18; i++) { fdct32(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 32; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ void sbt_dual_L3(MPEG *m, float *sample, short *pcm, int ch) { int i; if (ch == 0) for (i = 0; i < 18; i++) { fdct32(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 32; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 64; } else for (i = 0; i < 18; i++) { fdct32(m,sample, m->csbt.vbuf2 + m->csbt.vb2_ptr); window_dual(m, m->csbt.vbuf2, m->csbt.vb2_ptr, pcm + 1); sample += 32; m->csbt.vb2_ptr = (m->csbt.vb2_ptr - 32) & 511; pcm += 64; } } /*------------------------------------------------------------*/ /*------------------------------------------------------------*/ /*---------------- 16 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ void sbt16_mono_L3(MPEG *m, float *sample, short *pcm, int ch) { int i; ch = 0; for (i = 0; i < 18; i++) { fdct16(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 32; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void sbt16_dual_L3(MPEG *m, float *sample, short *pcm, int ch) { int i; if (ch == 0) { for (i = 0; i < 18; i++) { fdct16(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window16_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 32; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 32; } } else { for (i = 0; i < 18; i++) { fdct16(m,sample, m->csbt.vbuf2 + m->csbt.vb2_ptr); window16_dual(m,m->csbt.vbuf2, m->csbt.vb2_ptr, pcm + 1); sample += 32; m->csbt.vb2_ptr = (m->csbt.vb2_ptr - 16) & 255; pcm += 32; } } } /*------------------------------------------------------------*/ /*---------------- 8 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ void sbt8_mono_L3(MPEG *m, float *sample, short *pcm, int ch) { int i; ch = 0; for (i = 0; i < 18; i++) { fdct8(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 32; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void sbt8_dual_L3(MPEG *m, float *sample, short *pcm, int ch) { int i; if (ch == 0) { for (i = 0; i < 18; i++) { fdct8(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window8_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 32; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 16; } } else { for (i = 0; i < 18; i++) { fdct8(m,sample, m->csbt.vbuf2 + m->csbt.vb2_ptr); window8_dual(m,m->csbt.vbuf2, m->csbt.vb2_ptr, pcm + 1); sample += 32; m->csbt.vb2_ptr = (m->csbt.vb2_ptr - 8) & 127; pcm += 16; } } } /*------------------------------------------------------------*/ /*------- 8 bit output ---------------------------------------*/ /*------------------------------------------------------------*/ void sbtB_mono_L3(MPEG *m, float *sample, unsigned char *pcm, int ch) { int i; ch = 0; for (i = 0; i < 18; i++) { fdct32(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 32; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ void sbtB_dual_L3(MPEG *m, float *sample, unsigned char *pcm, int ch) { int i; if (ch == 0) for (i = 0; i < 18; i++) { fdct32(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 32; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 64; } else for (i = 0; i < 18; i++) { fdct32(m,sample, m->csbt.vbuf2 + m->csbt.vb2_ptr); windowB_dual(m,m->csbt.vbuf2, m->csbt.vb2_ptr, pcm + 1); sample += 32; m->csbt.vb2_ptr = (m->csbt.vb2_ptr - 32) & 511; pcm += 64; } } /*------------------------------------------------------------*/ /*------------------------------------------------------------*/ /*---------------- 16 pt sbtB's -------------------------------*/ /*------------------------------------------------------------*/ void sbtB16_mono_L3(MPEG *m, float *sample, unsigned char *pcm, int ch) { int i; ch = 0; for (i = 0; i < 18; i++) { fdct16(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 32; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void sbtB16_dual_L3(MPEG *m, float *sample, unsigned char *pcm, int ch) { int i; if (ch == 0) { for (i = 0; i < 18; i++) { fdct16(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB16_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 32; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 32; } } else { for (i = 0; i < 18; i++) { fdct16(m,sample, m->csbt.vbuf2 + m->csbt.vb2_ptr); windowB16_dual(m,m->csbt.vbuf2, m->csbt.vb2_ptr, pcm + 1); sample += 32; m->csbt.vb2_ptr = (m->csbt.vb2_ptr - 16) & 255; pcm += 32; } } } /*------------------------------------------------------------*/ /*---------------- 8 pt sbtB's -------------------------------*/ /*------------------------------------------------------------*/ void sbtB8_mono_L3(MPEG *m, float *sample, unsigned char *pcm, int ch) { int i; ch = 0; for (i = 0; i < 18; i++) { fdct8(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 32; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void sbtB8_dual_L3(MPEG *m, float *sample, unsigned char *pcm, int ch) { int i; if (ch == 0) { for (i = 0; i < 18; i++) { fdct8(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB8_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 32; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 16; } } else { for (i = 0; i < 18; i++) { fdct8(m,sample, m->csbt.vbuf2 + m->csbt.vb2_ptr); windowB8_dual(m,m->csbt.vbuf2, m->csbt.vb2_ptr, pcm + 1); sample += 32; m->csbt.vb2_ptr = (m->csbt.vb2_ptr - 8) & 127; pcm += 16; } } } /*------------------------------------------------------------*/ <file_sep>/lib/SDL_gui/Font.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_Font::GUI_Font(const char *aname) : GUI_Object(aname) { } GUI_Font::~GUI_Font(void) { } GUI_Surface *GUI_Font::RenderFast(const char *s, SDL_Color fg) { /*throw*/ GUI_Exception("RenderFast not implemented"); return NULL; } GUI_Surface *GUI_Font::RenderQuality(const char *s, SDL_Color fg) { /*throw*/ GUI_Exception("RenderQuality not implemented"); return NULL; } void GUI_Font::DrawText(GUI_Surface *surface, const char *s, int x, int y) { /*throw*/ GUI_Exception("DrawText not implemented"); } SDL_Rect GUI_Font::GetTextSize(const char *s) { /*throw*/ GUI_Exception("GetTextSize not implemented"); SDL_Rect r; return r; } extern "C" { GUI_Surface *GUI_FontRenderFast(GUI_Font *font, const char *s, SDL_Color fg) { return font->RenderFast(s, fg); } GUI_Surface *GUI_FontRenderQuality(GUI_Font *font, const char *s, SDL_Color fg) { return font->RenderQuality(s, fg); } void GUI_FontDrawText(GUI_Font *font, GUI_Surface *surface, const char *s, int x, int y) { font->DrawText(surface, s, x, y); } SDL_Rect GUI_FontGetTextSize(GUI_Font *font, const char *s) { return font->GetTextSize(s); } }; <file_sep>/firmware/bootloader/Makefile # # DreamShell boot loader # (c)2011-2022 SWAT # TARGET = loader VERSION = 2.5 TARGET_NAME = DreamShell_boot_$(TARGET)_v$(VERSION) TARGET_CD = cd/1DS_BOOT.BIN TARGET_DUMMY = cd/0.0 all: rm-elf $(TARGET).elf clean: rm-elf -rm -f $(OBJS) -rm -rf ./cd rm-elf: -rm -f $(TARGET).elf $(TARGET_NAME).elf $(TARGET).bin $(TARGET_NAME).bin \ $(TARGET_CD) $(TARGET_NAME).cdi $(TARGET_DUMMY) romdisk.* include ../../sdk/Makefile.cfg FATFS = $(DS_BASE)/src/fs/fat DRIVERS = $(DS_BASE)/src/drivers UTILS = $(DS_BASE)/src/utils OBJS = src/main.o src/spiral.o src/menu.o src/descramble.o \ $(DRIVERS)/spi.o $(DRIVERS)/sd.o $(DRIVERS)/rtc.o \ $(FATFS)/utils.o $(FATFS)/option/ccsbcs.o $(FATFS)/option/syscall.o \ $(FATFS)/ff.o $(FATFS)/dc.o $(FATFS)/../fs.o \ $(UTILS)/memcpy.op $(UTILS)/memset.op KOS_CFLAGS += -I$(DS_BASE)/include -I$(DS_BASE)/include/fatfs -I./include -DVERSION="$(VERSION)" $(TARGET).bin: $(TARGET).elf $(TARGET).elf: $(OBJS) romdisk.o $(KOS_CC) $(KOS_CFLAGS) $(KOS_LDFLAGS) -o $(TARGET).elf \ $(OBJS) romdisk.o $(OBJEXTRA) -lkosext2fs -lz -lkmg $(KOS_LIBS) $(KOS_STRIP) $(TARGET).elf $(KOS_OBJCOPY) -R .stack -O binary $(TARGET).elf $(TARGET).bin %.op: %.S kos-cc $(CFLAGS) -c $< -o $@ romdisk.img: $(KOS_GENROMFS) -f romdisk.img -d romdisk -v romdisk.o: romdisk.img $(KOS_BASE)/utils/bin2o/bin2o romdisk.img romdisk romdisk.o $(TARGET_CD): $(TARGET).bin cdi: $(TARGET_CD) @mkdir -p ./cd @$(DS_SDK)/bin/scramble $(TARGET).bin $(TARGET_CD) @$(DS_SDK)/bin/mkisofs -V DreamShell -C 0,11702 -G $(DS_RES)/IP.BIN -joliet -rock -l -x .DS_Store -o $(TARGET).iso ./cd @echo Convert ISO to CDI... @-rm -f $(TARGET).cdi @$(DS_SDK)/bin/cdi4dc $(TARGET).iso $(TARGET).cdi >/dev/null @-rm -f $(TARGET).iso # If you have problems with mkisofs try data/data image: # $(DS_SDK)/bin/mkisofs -V DreamShell -G $(DS_RES)/IP.BIN -joliet -rock -l -x .DS_Store -o $(TARGET).iso ./cd # @$(DS_SDK)/bin/cdi4dc $(TARGET).iso $(TARGET).cdi -d >/dev/null release: all $(TARGET_DUMMY) cdi install @rm -f $(TARGET_NAME).bin $(TARGET_NAME).cdi @cp $(TARGET).bin $(TARGET_NAME).bin @mv $(TARGET).cdi $(TARGET_NAME).cdi install: $(TARGET).bin @$(DS_SDK)/bin/mkbios $(DS_BUILD)/firmware/bios/ds/boot_loader_devkit_nogdrom.bios $(TARGET).bin @$(DS_SDK)/bin/mkbios $(DS_BUILD)/firmware/bios/ds/boot_loader_devkit.bios $(TARGET).bin @$(DS_SDK)/bin/mkbios $(DS_BUILD)/firmware/bios/ds/boot_loader_retail_nogdrom.bios $(TARGET).bin @$(DS_SDK)/bin/mkbios $(DS_BUILD)/firmware/bios/ds/boot_loader_retail.bios $(TARGET).bin $(TARGET_DUMMY): @mkdir -p ./cd dd if=/dev/zero of=cd/0.0 bs=1024k count=500 nulldc: all cdi @echo Running... @-rm -f $(DS_BASE)/DS.cdi @cp $(TARGET).cdi $(DS_BASE)/DS.cdi @run $(DS_BASE)/emu/nullDC.exe -serial "debug.log" lxdream: all cdi @echo Running... @lxdream -p $(TARGET).cdi lxdelf: $(TARGET).elf lxdream -u -p -e $(TARGET).elf run: $(TARGET).elf $(DS_SDK)/bin/dc-tool-ip -t $(DC_LAN_IP) -x $(TARGET).elf run-serial: $(TARGET).elf $(DS_SDK)/bin/dc-tool-ser -t $(DC_SERIAL_PORT) -b $(DC_SERIAL_BAUD) -x $(TARGET).elf <file_sep>/commands/mke2fs/Makefile # DreamShell ##version## # # Copyright (C) 2014-2020 SWAT # DreamShell command Makefile # http://www.dc-swat.ru # TARGET = mke2fs OBJS = mke2fs.o DBG_LIBS = -lds all: rm-elf include ../../sdk/Makefile.loadable KOS_CFLAGS += -I$(KOS_BASE)/addons/libkosext2fs -W -std=gnu99 rm-elf: -rm -f $(TARGET) install: $(TARGET) -rm $(DS_BUILD)/cmds/$(TARGET) cp $(TARGET) $(DS_BUILD)/cmds/$(TARGET) <file_sep>/src/utils.c /**************************** * DreamShell ##version## * * utils.c * * DreamShell Utils * * Created by SWAT * * http://www.dc-swat.ru * ***************************/ #include "ds.h" #include "video.h" #include <dc/sound/sound.h> #include "drivers/aica_cmd_iface.h" #include <sys/time.h> int snd_init_firmware(const char *filename) { file_t f; size_t sz; uint8 *buff; f = fs_open(filename, O_RDONLY); if(f < 0) { ds_printf("DS_ERROR: Can't open firmware %s\n", filename); return -1; } sz = fs_total(f); ds_printf("DS_PROCESS: Loading firmware %s (%d bytes) into SPU RAM\n", filename, sz); buff = (uint8*)malloc(sz); fs_read(f, buff, sz); fs_close(f); spu_disable(); spu_memset(0, 0, AICA_RAM_START); spu_memload(0, buff, sz); /* Enable the AICA and give it a few ms to start up */ spu_enable(); timer_spin_sleep(10); /* Initialize the RAM allocator */ snd_mem_init(AICA_RAM_START); return 0; } int flashrom_get_region_only() { int start, size; uint8 region[6] = { 0 }; region[2] = *(uint8*)0x0021A002; /* Find the partition */ if(flashrom_info(FLASHROM_PT_SYSTEM, &start, &size) < 0) { dbglog(DBG_ERROR, "%s: can't find partition %d\n", __func__, FLASHROM_PT_SYSTEM); } else { /* Read the first 5 characters of that partition */ if(flashrom_read(start, region, 5) < 0) { dbglog(DBG_ERROR, "%s: can't read partition %d\n", __func__, FLASHROM_PT_SYSTEM); } } if(region[2] == 0x58 || region[2] == 0x30) { return FLASHROM_REGION_JAPAN; } else if(region[2] == 0x59 || region[2] == 0x31) { return FLASHROM_REGION_US; } else if(region[2] == 0x5A || region[2] == 0x32) { return FLASHROM_REGION_EUROPE; } else { dbglog(DBG_ERROR, "%s: Unknown region code %02x\n", __func__, region[2]); return FLASHROM_REGION_UNKNOWN; } } int is_hacked_bios() { return (*(uint16 *)0xa0000000) == 0xe6ff; } int is_custom_bios() { return (*(uint16 *)0xa0000004) == 0x4318; } int is_no_syscalls() { return (*(uint16 *)0xac000100) != 0x2f06; } uint32 gzip_get_file_size(const char *filename) { file_t fd; uint32 len; uint32 size; fd = fs_open(filename, O_RDONLY); if(fd < 0) return 0; if(fs_seek(fd, -4, SEEK_END) <= 0) { fs_close(fd); return 0; } len = fs_read(fd, &size, sizeof(size)); fs_close(fd); if(len != 4) { return 0; } return size; } void readstr( FILE *f, char *string ) { /* Loop Until End Of Line Is Reached */ do { /* Gets A String Of 255 Chars Max From f (File) */ fgets(string, 255, f); } while ( ( string[0] == '/' ) || ( string[0] == '\n' ) ); return; } int FileSize(const char *fn) { int size; file_t f = fs_open(fn, O_RDONLY); if(f == FILEHND_INVALID) { return -1; } size = fs_total(f); fs_close(f); return size; } int FileExists(const char *fn) { file_t f = fs_open(fn, O_RDONLY); if(f == FILEHND_INVALID) { return 0; } fs_close(f); return 1; } int DirExists(const char *dir) { file_t f = fs_open(dir, O_DIR | O_RDONLY); if(f == FILEHND_INVALID) { return 0; } fs_close(f); return 1; } int CopyFile(const char *src_fn, const char *dest_fn, int verbose) { size_t cnt, size, cur = 0, buf_size; file_t src_fd, dest_fd; uint8 *buff; if(verbose) { ds_printf("DS_PROCESS: Copying file: %s to %s\n", src_fn, dest_fn); } src_fd = fs_open(src_fn, O_RDONLY); if (src_fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open %s for read\n", src_fn); return 0; } dest_fd = fs_open(dest_fn, O_WRONLY | O_CREAT); if (dest_fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open %s for write\n", dest_fn); fs_close(src_fd); return 0; } size = fs_total(src_fd) / 1024; if(size >= 256) { buf_size = 32 * 1024; } else if(size < 32 && size > 8) { buf_size = 1024; } else if(size <= 8) { buf_size = 512; } else { buf_size = 16 * 1024; } buff = (uint8 *) memalign(32, buf_size); if(buff == NULL) { ds_printf("DS_ERROR: No memory: %d bytes\n", buf_size); return 0; } while ((cnt = fs_read(src_fd, buff, buf_size)) > 0) { cur += cnt; if(fs_write(dest_fd, buff, cnt) < 0) { break; } } fs_close(dest_fd); fs_close(src_fd); free(buff); return 1; } int CopyDirectory(const char *src_path, const char *dest_path, int verbose) { file_t fd = fs_open(src_path, O_RDONLY | O_DIR); if(fd != FILEHND_INVALID) { char Path[NAME_MAX], *EndPtr = Path; char PathDest[NAME_MAX], *EndDestPtr = PathDest; dirent_t *e; strcpy(Path, src_path); Path[strlen(src_path)] = '/'; EndPtr += (strlen(src_path)+1); strcpy(PathDest, dest_path); if(!DirExists(PathDest)) { if(verbose) { ds_printf("DS_PROCESS: Making directory: %s\n", PathDest); } if(fs_mkdir(PathDest)) { ds_printf("DS_ERROR: Can't make directory %s\n", PathDest); fs_close(fd); return 0; } } PathDest[strlen(dest_path)] = '/'; EndDestPtr += (strlen(dest_path)+1); while((e = fs_readdir(fd)) != NULL) { if (!strcmp(e->name, ".") || !strcmp(e->name, "..")) continue; strcpy(EndPtr, e->name); strcpy(EndDestPtr, e->name); if(e->attr == O_DIR) { if(verbose) { ds_printf("DS_PROCESS: Making directory: %s\n", PathDest); } if(!fs_mkdir(PathDest)) { CopyDirectory(Path, PathDest, verbose); } else { ds_printf("DS_ERROR: Can't make directory %s\n", PathDest); fs_close(fd); return 0; } } else { if(!CopyFile(Path, PathDest, verbose)) { fs_close(fd); return 0; } } } fs_close(fd); return 1; } return 0; } int PeriphExists(const char *name) { int p, u; maple_device_t *dev; for (p = 0; p < MAPLE_PORT_COUNT; p++) { for (u = 0; u < MAPLE_UNIT_COUNT; u++) { dev = maple_enum_dev(p, u); if (dev) { /* ds_printf("%c%c: %s (%08lx: %s)\n", 'A' + p, '0' + u, dev->info.product_name, dev->info.functions, maple_pcaps(dev->info.functions)); */ // ds_printf("Piriph: [%s] [%s] [%s]\n", // maple_pcaps(dev->info.functions), dev->info.product_name, dev->drv->name); if(!strcasecmp(maple_pcaps(dev->info.functions), name)) return 1; } } } return 0; } int hex_to_int(char c) { if(c>='0' && c <='9') { return c-'0'; } if(c>='a' && c <='f') { return 10+(c-'a'); } if(c>='A' && c <='F') { return 10+(c-'A'); } return -1; } char *strtolower(char *str) { int x; static char buf[256]; if(str == NULL) return NULL; strcpy(buf, str); for(x = 0; x < strlen(buf); x++) { if(buf[x] >= 'A' && buf[x] <= 'Z') { buf[x] += ('a'-'A'); } } return buf; } static char *splitnext(char **pos) { char *a, *d, *s; s = *pos; while (*s == ' ' || *s == '\t') s++; a = d = s; while (*s && *s != ' ' && *s != '\t') { if (*s == '"') { s++; while (*s && *s != '"') { if (*s == '\\') s++; if (*s) *(d++) = *(s++); } if (*s == '"') s++; } else { if (*s == '\\') s++; *(d++) = *(s++); } } while (*s == ' ' || *s == '\t') s++; *d = 0; *pos = s; return a; } int splitline(char **argv, int max, char *line) { char *s; int i = 0; s = line; while(*s && i < max) { argv[i] = splitnext(&s); i++; } if(!argv[0]) return(0); return i; } char *substring(const char* str, size_t begin, size_t len) { if (str == 0 || strlen(str) == 0 || strlen(str) < begin || strlen(str) < (begin+len)) return 0; return strndup(str + begin, len); } int access(const char *filename, int mode) { if(FileExists(filename) || DirExists(filename)) return 0; else return -1; } int execv(const char *file, char *const *argv) { int argc = 1, ret = CMD_OK; while(*argv[argc-1]) { argc++; } ret = CallCmdFile(file, argc, (char**)argv); return ret == CMD_OK ? 0 : -1; } int execvp(const char *file, char *const *argv) { char fn[NAME_MAX]; sprintf(fn, "%s/%s", getenv("PATH"), file); if(!FileExists(fn)) { sprintf(fn, "%s/cmds/%s", getenv("PATH"), file); } return execv(fn, argv); } int fchmod(int filedes, mode_t mode) { return 0; } int fchown(int filedes, uid_t owner, gid_t group) { return 0; } int chown(const char *path, uid_t owner, gid_t group) { return 0; } int ftruncate(int file, off_t length) { return 0; } int utimes(const char *filename, const struct timeval times[2]) { return 0; } gid_t geteuid(void) { return 1; } int gethostname(char *name, size_t len) { strncpy(name, getenv("HOST"), len); return 0; } //int sethostname(const char *name, size_t len) { // setenv("HOST", name, 1); // return 0; //} static int do_mkdir(const char *path) { struct stat st; if (fs_stat(path, &st, 0) < 0) { /* Directory does not exist. EEXIST for race condition */ if (fs_mkdir(path) != 0/* && errno != EEXIST*/) return -1; } else if (!(st.st_mode & S_IFDIR)) { errno = ENOTDIR; return -1; } return 0; } /** * mkpath - ensure all directories in path exist * Algorithm takes the pessimistic view and works top-down to ensure * each directory in path exists, rather than optimistically creating * the last element and working backwards. */ int mkpath(const char *path) { char *pp; char *sp; int status; char *copypath = strdup(path); status = 0; pp = copypath; while (status == 0 && (sp = strchr(pp, '/')) != 0) { if (sp != pp) { /* Neither root nor double slash in path */ *sp = '\0'; status = do_mkdir(copypath); *sp = '/'; } pp = sp + 1; } if (status == 0) status = do_mkdir(path); free(copypath); return (status); } /* read a pathname based on the current directory and turn it into an abs one, we don't check for validity, or really do anything except handle ..'s and .'s */ int makeabspath_wd(char *buff, char *path, char *dir, size_t size) { int numtxts; int i; char *txts[32]; /* max of 32...should be nuff */ char *rslash; numtxts = 0; /* check if path is already absolute */ if (path[0] == '/') { strncpy(buff, path, size); return 0; } /* split the path into tokens */ for (numtxts = 0; numtxts < 32;) { if ((txts[numtxts] = strsep(&path, "/")) == NULL) break; if (*txts[numtxts] != '\0') numtxts++; } /* start from the current directory */ strncpy(buff, dir, size); for (i = 0; i < numtxts; i++) { if (strcmp(txts[i], "..") == 0) { if ((rslash = strrchr(buff, '/')) != NULL) *rslash = '\0'; } else if (strcmp(txts[i], ".") == 0) { /* do nothing */ } else { if (buff[strlen(buff) - 1] != '/') strncat(buff, "/", size - 1 - strlen(buff)); strncat(buff, txts[i], size - 1 - strlen(buff)); } } /* make sure it's not empty */ if (buff[0] == '\0') { buff[0] = '/'; buff[1] = '\0'; } return 0; } // Deprecated int makeabspath(char *buff, char *path, size_t size) { //return makeabspath_wd(buff, path, cwd, size); realpath(path, buff); return 1; } const char *relativeFilePath(const char *rel, const char *file) { if(file[0] == '/') return file; char *rslash, *dir, *ret; char fn[NAME_MAX]; char buff[NAME_MAX]; if((rslash = strrchr(rel, '/')) != NULL) { strncpy(buff, file, NAME_MAX); dir = substring(rel, 0, strlen(rel) - strlen(rslash)); makeabspath_wd(fn, buff, dir, NAME_MAX); fn[strlen(fn)] = '\0'; ret = strdup(fn); //ds_printf("Directory: '%s' File: '%s' Out: '%s'", dir, rslash, ret, fn); free(dir); } else { return file; } return ret; } int relativeFilePath_wb(char *buff, const char *rel, const char *file) { if(file[0] == '/') { strncpy(buff, file, NAME_MAX); return 1; } /* char *rslash, *dir; if((rslash = strrchr(rel, '/')) != NULL) { dir = substring(rel, 0, strlen(rel) - strlen(rslash)); makeabspath_wd(buff, file, dir, NAME_MAX); ds_printf("Directory: '%s' File: '%s' Out: '%s'", dir, rel, buff); */ makeabspath_wd(buff, (char*)file, getFilePath(rel), NAME_MAX); //ds_printf("Directory: '%s' File: '%s' Out: '%s'", path, rel, buff); return 1; } char *getFilePath(const char *file) { char *rslash; if((rslash = strrchr(file, '/')) != NULL) { return substring(file, 0, strlen(file) - strlen(rslash)); } return NULL; } <file_sep>/firmware/isoldr/loader/kos/src/g2bus.c /* KallistiOS ##version## g2bus.c Copyright (C)2000-2002,2004 <NAME> */ /* This module handles low-level access to the DC's "G2" bus, which handles communication with the SPU (AICA) and the expansion port. One must be very careful with this bus, as it requires 32-bit access for most things, FIFO checking for PIO access, suspended DMA for PIO access, etc, etc... very picky =) Thanks to <NAME> and <NAME> for the info about when to lock/suspend DMA/etc. */ #include <string.h> #include <stdio.h> #include <arch/irq.h> #include <dc/g2bus.h> //CVSID("$Id: g2bus.c,v 1.5 2003/02/14 06:33:47 bardtx Exp $"); /* These two macros are based on NetBSD's DC port */ /* G2 bus cycles must not be interrupted by IRQs or G2 DMA. The following paired macros will take the necessary precautions. */ #define DMAC_CHCR3 *((vuint32 *)0xffa0003c) #define G2_LOCK(/*OLD1, */OLD2) \ do { \ /*OLD1 = irq_disable();*/ \ /* suspend any G2 DMA here... */ \ OLD2 = DMAC_CHCR3; \ DMAC_CHCR3 = OLD2 & ~1; \ while((*(vuint32 *)0xa05f688c) & 0x20) \ ; \ } while(0) #define G2_UNLOCK(/*OLD1, */OLD2) \ do { \ /* resume any G2 DMA here... */ \ DMAC_CHCR3 = OLD2; \ /*irq_restore(OLD1);*/ \ } while(0) /* Always use these functions to access G2 bus memory (includes the SPU and the expansion port, e.g., BBA) */ /* Read one byte from G2 */ uint8 g2_read_8(uint32 address) { int /*old1, */old2; uint8 out; G2_LOCK(/*old1, */old2); out = *((vuint8*)address); G2_UNLOCK(/*old1, */old2); return out; } /* Write one byte to G2 */ void g2_write_8(uint32 address, uint8 value) { int /*old1, */old2; G2_LOCK(/*old1, */old2); *((vuint8*)address) = value; G2_UNLOCK(/*old1, */old2); } /* Read one word from G2 */ uint16 g2_read_16(uint32 address) { int /*old1, */old2; uint16 out; G2_LOCK(/*old1, */old2); out = *((vuint16*)address); G2_UNLOCK(/*old1, */old2); return out; } /* Write one word to G2 */ void g2_write_16(uint32 address, uint16 value) { int /*old1, */old2; G2_LOCK(/*old1, */old2); *((vuint16*)address) = value; G2_UNLOCK(/*old1, */old2); } /* Read one dword from G2 */ uint32 g2_read_32(uint32 address) { int /*old1, */old2; uint32 out; G2_LOCK(/*old1, */old2); out = *((vuint32*)address); G2_UNLOCK(/*old1, */old2); return out; } /* Write one dword to G2 */ void g2_write_32(uint32 address, uint32 value) { int /*old1, */old2; G2_LOCK(/*old1, */old2); *((vuint32*)address) = value; G2_UNLOCK(/*old1, */old2); } /* Read a block of 8-bit values from G2 */ void g2_read_block_8(uint8 * output, uint32 address, int amt) { const vuint8 * input = (const vuint8 *)address; int /*old1, */old2; G2_LOCK(/*old1, */old2); while (amt--) { *output++ = *input++; } G2_UNLOCK(/*old1, */old2); } /* Write a block 8-bit values to G2 */ void g2_write_block_8(const uint8 * input, uint32 address, int amt) { vuint8 * output = (vuint8 *)address; int /*old1, */old2; G2_LOCK(/*old1, */old2); while (amt--) { *output++ = *input++; } G2_UNLOCK(/*old1, */old2); } /* Read a block of 16-bit values from G2 */ void g2_read_block_16(uint16 * output, uint32 address, int amt) { const vuint16 * input = (const vuint16 *)address; int /*old1, */old2; G2_LOCK(/*old1, */old2); while (amt--) { *output++ = *input++; } G2_UNLOCK(/*old1, */old2); } /* Write a block of 16-bit values to G2 */ void g2_write_block_16(const uint16 * input, uint32 address, int amt) { vuint16 * output = (vuint16 *)address; int /*old1, */old2; G2_LOCK(/*old1, */old2); while (amt--) { *output++ = *input++; } G2_UNLOCK(/*old1, */old2); } /* Read a block of 32-bit values from G2 */ void g2_read_block_32(uint32 * output, uint32 address, int amt) { const vuint32 * input = (const vuint32 *)address; int /*old1, */old2; G2_LOCK(/*old1, */old2); while (amt--) { *output++ = *input++; } G2_UNLOCK(/*old1, */old2); } /* Write a block of 32-bit values to G2 */ void g2_write_block_32(const uint32 * input, uint32 address, int amt) { vuint32 * output = (vuint32 *)address; int /*old1, */old2; G2_LOCK(/*old1, */old2); while (amt--) { *output++ = *input++; } G2_UNLOCK(/*old1, */old2); } /* When writing to the SPU RAM, this is required at least every 8 32-bit writes that you execute */ void g2_fifo_wait() { vuint32 const *g2_fifo = (vuint32*)0xa05f688c; int i; for (i=0; i<0x1800; i++) { if (!(*g2_fifo & 0x11)) break; } } <file_sep>/src/fs/fs.c /** * \file fs.c * \brief Filesystem * \date 2013-2023 * \author SWAT * \copyright http://www.dc-swat.ru */ #include "ds.h" #include "fs.h" #include "drivers/sd.h" #include "drivers/g1_ide.h" typedef struct romdisk_hdr { char magic[8]; /* Should be "-rom1fs-" */ uint32 full_size; /* Full size of the file system */ uint32 checksum; /* Checksum */ char volume_name[16]; /* Volume name (zero-terminated) */ } romdisk_hdr_t; typedef struct blockdev_devdata { uint64_t block_count; uint64_t start_block; } sd_devdata_t; typedef struct ata_devdata { uint64_t block_count; uint64_t start_block; uint64_t end_block; } ata_devdata_t; #define MAX_PARTITIONS 4 static kos_blockdev_t sd_dev[MAX_PARTITIONS]; static kos_blockdev_t g1_dev[MAX_PARTITIONS]; static uint32 ntohl_32(const void *data) { const uint8 *d = (const uint8*)data; return (d[0] << 24) | (d[1] << 16) | (d[2] << 8) | (d[3] << 0); } static int check_partition(uint8 *buf, int partition) { int pval; if(buf[0x01FE] != 0x55 || buf[0x1FF] != 0xAA) { // dbglog(DBG_DEBUG, "Device doesn't appear to have a MBR\n"); return -1; } pval = 16 * partition + 0x01BE; if(buf[pval + 4] == 0) { // dbglog(DBG_DEBUG, "Partition empty: 0x%02x\n", buf[pval + 4]); return -1; } return 0; } int InitSDCard() { dbglog(DBG_INFO, "Checking for SD card...\n"); uint8 partition_type; int part = 0, fat_part = 0; char path[8]; uint8 buf[512]; kos_blockdev_t *dev; if(sdc_init()) { scif_init(); dbglog(DBG_INFO, "\nSD card not found.\n"); return -1; } dbglog(DBG_INFO, "SD card initialized, capacity %" PRIu32 " MB\n", (uint32)(sdc_get_size() / 1024 / 1024)); // if(sdc_print_ident()) { // dbglog(DBG_INFO, "SD card read CID error\n"); // return -1; // } if(sdc_read_blocks(0, 1, buf)) { dbglog(DBG_ERROR, "Can't read MBR from SD card\n"); return -1; } for(part = 0; part < MAX_PARTITIONS; part++) { dev = &sd_dev[part]; if(!check_partition(buf, part) && !sdc_blockdev_for_partition(part, dev, &partition_type)) { if(!part) { strcpy(path, "/sd"); path[3] = '\0'; } else { sprintf(path, "sd%d", part); } /* Check to see if the MBR says that we have a Linux partition. */ if(is_ext2_partition(partition_type)) { dbglog(DBG_INFO, "Detected EXT2 filesystem on partition %d\n", part); if(fs_ext2_init()) { dbglog(DBG_INFO, "Could not initialize fs_ext2!\n"); sd_dev[part].shutdown(dev); } else { dbglog(DBG_INFO, "Mounting filesystem...\n"); if(fs_ext2_mount(path, dev, FS_EXT2_MOUNT_READWRITE)) { dbglog(DBG_INFO, "Could not mount device as ext2fs.\n"); sd_dev[part].shutdown(dev); } } } else if((fat_part = is_fat_partition(partition_type))) { dbglog(DBG_INFO, "Detected FAT%d filesystem on partition %d\n", fat_part, part); if(fs_fat_init()) { dbglog(DBG_INFO, "Could not initialize fs_fat!\n"); sd_dev[part].shutdown(dev); } else { /* Need full disk block device for FAT */ sd_dev[part].shutdown(dev); if(sdc_blockdev_for_device(dev)) { continue; } dbglog(DBG_INFO, "Mounting filesystem...\n"); if(fs_fat_mount(path, dev, 0, part)) { dbglog(DBG_INFO, "Could not mount device as fatfs.\n"); sd_dev[part].shutdown(dev); } } } else { dbglog(DBG_INFO, "Unknown filesystem: 0x%02x\n", partition_type); sd_dev[part].shutdown(dev); } } } return 0; } int InitIDE() { dbglog(DBG_INFO, "Checking for G1 ATA devices...\n"); uint8 partition_type; int part = 0, fat_part = 0; char path[8]; uint8 buf[512]; /* FIXME: G1 DMA has conflicts with other stuff like G2 DMA and so on */ int use_dma = 0; kos_blockdev_t *dev; if(g1_ata_init()) { return -1; } /* Read the MBR from the disk */ if(g1_ata_lba_mode()) { if(g1_ata_read_lba(0, 1, (uint16_t *)buf) < 0) { dbglog(DBG_ERROR, "Can't read MBR from IDE by LBA\n"); return -1; } } else { use_dma = 0; if(g1_ata_read_chs(0, 0, 1, 1, (uint16_t *)buf) < 0) { dbglog(DBG_ERROR, "Can't read MBR from IDE by CHS\n"); return -1; } } for(part = 0; part < MAX_PARTITIONS; part++) { dev = &g1_dev[part]; if(!check_partition(buf, part) && !g1_ata_blockdev_for_partition(part, use_dma, dev, &partition_type)) { if(!part) { strcpy(path, "/ide"); path[4] = '\0'; } else { sprintf(path, "/ide%d", part); path[strlen(path)] = '\0'; } /* Check to see if the MBR says that we have a EXT2 or FAT partition. */ if(is_ext2_partition(partition_type)) { dbglog(DBG_INFO, "Detected EXT2 filesystem on partition %d\n", part); if(fs_ext2_init()) { dbglog(DBG_INFO, "Could not initialize fs_ext2!\n"); g1_dev[part].shutdown(dev); } else { if (use_dma) { /* Only PIO for EXT2 */ g1_dev[part].shutdown(dev); if(g1_ata_blockdev_for_partition(part, 0, dev, &partition_type)) { continue; } } dbglog(DBG_INFO, "Mounting filesystem...\n"); if(fs_ext2_mount(path, dev, FS_EXT2_MOUNT_READWRITE)) { dbglog(DBG_INFO, "Could not mount device as ext2fs.\n"); g1_dev[part].shutdown(dev); } } } else if((fat_part = is_fat_partition(partition_type))) { dbglog(DBG_INFO, "Detected FAT%d filesystem on partition %d\n", fat_part, part); if(fs_fat_init()) { dbglog(DBG_INFO, "Could not initialize fs_fat!\n"); g1_dev[part].shutdown(dev); } else { /* Need full disk block device for FAT */ g1_dev[part].shutdown(dev); if(g1_ata_blockdev_for_device(use_dma, dev)) { continue; } dbglog(DBG_INFO, "Mounting filesystem...\n"); if(fs_fat_mount(path, dev, use_dma, part)) { dbglog(DBG_INFO, "Could not mount device as fatfs.\n"); g1_dev[part].shutdown(dev); } } } else { dbglog(DBG_INFO, "Unknown filesystem: 0x%02x\n", partition_type); g1_dev[part].shutdown(dev); } } } return 0; } int InitRomdisk() { int cnt = -1; uint32 size, addr; char path[32]; uint8 *tmpb = (uint8 *)0x00100000; dbglog(DBG_INFO, "Checking for romdisk in the bios...\n"); for(addr = 0x00100000; addr < 0x00200000; addr++) { if(tmpb[0] == 0x2d && tmpb[1] == 0x72 && tmpb[2] == 0x6f) { romdisk_hdr_t *romfs = (romdisk_hdr_t *)tmpb; if(strncmp(romfs->magic, "-rom1fs-", 8) || strncmp(romfs->volume_name, getenv("HOST"), 10)) { continue; } size = ntohl_32((const void *)&romfs->full_size); if(!size || size > 0x1F8000) { continue; } dbglog(DBG_INFO, "Detected romdisk at 0x%08lx, mounting...\n", (uint32)tmpb); if(cnt) { snprintf(path, sizeof(path), "/brd%d", cnt+1); } else { strncpy(path, "/brd", sizeof(path)); } if(fs_romdisk_mount(path, (const uint8 *)tmpb, 0) < 0) { dbglog(DBG_INFO, "Error mounting romdisk at 0x%08lx\n", (uint32)tmpb); } else { dbglog(DBG_INFO, "Romdisk mounted as %s\n", path); } cnt++; tmpb += sizeof(romdisk_hdr_t) + size; } tmpb++; } return (cnt > -1 ? 0 : -1); } int RootDeviceIsSupported(const char *name) { if(!strncmp(name, "sd", 2) || !strncmp(name, "ide", 3) || !strncmp(name, "cd", 2) || !strncmp(name, "pc", 2) || !strncmp(name, "brd", 3)) { return 1; } return 0; } static int SearchRootCheck(char *device, char *path, char *file) { char check[NAME_MAX]; if(file == NULL) { sprintf(check, "/%s%s", device, path); } else { sprintf(check, "/%s%s/%s", device, path, file); } if((file == NULL && DirExists(check)) || (file != NULL && FileExists(check))) { sprintf(check, "/%s%s", device, path); setenv("PATH", check, 1); return 1; } return 0; } int SearchRoot() { dirent_t *ent; file_t hnd; int detected = 0; hnd = fs_open("/", O_RDONLY | O_DIR); if(hnd < 0) { dbglog(DBG_ERROR, "Can't open root directory!\n"); return -1; } while ((ent = fs_readdir(hnd)) != NULL) { if(!RootDeviceIsSupported(ent->name)) { continue; } dbglog(DBG_INFO, "Checking for root directory on /%s\n", ent->name); if(SearchRootCheck(ent->name, "/DS", "/lua/startup.lua") || SearchRootCheck(ent->name, "", "/lua/startup.lua")) { detected = 1; break; } } fs_close(hnd); if (!detected) { dbglog(DBG_ERROR, "Can't find root directory.\n"); setenv("PATH", "/ram", 1); setenv("TEMP", "/ram", 1); return -1; } if(strncmp(getenv("PATH"), "/pc", 3) && DirExists("/pc")) { dbglog(DBG_INFO, "Checking for root directory on /pc\n"); if(!SearchRootCheck("pc", "", "/lua/startup.lua")) { SearchRootCheck("pc", "/DS", "/lua/startup.lua"); } } if( !strncmp(getenv("PATH"), "/sd", 3) || !strncmp(getenv("PATH"), "/ide", 4) || !strncmp(getenv("PATH"), "/pc", 3)) { setenv("TEMP", getenv("PATH"), 1); } else { setenv("TEMP", "/ram", 1); } dbglog(DBG_INFO, "Root directory is %s\n", getenv("PATH")); // dbglog(DBG_INFO, "Temp directory is %s\n", getenv("TEMP")); return 0; } <file_sep>/firmware/isoldr/loader/kos/arch/timer.h /* KallistiOS ##version## arch/timer.h Copyright(c)2000-2001,2004 <NAME> Copyright (C)2014-2023 SWAT Copyright (C)2023 <NAME> */ /** \file arch/timer.h \brief Low-level timer functionality. This file contains functions for interacting with the timer sources on the SH4. Many of these functions may interfere with thread operation or other such things, and should thus be used with caution. Basically, the only functionality that you might use in practice in here in normal programs is the gettime functions. \author <NAME> */ #ifndef __ARCH_TIMER_H #define __ARCH_TIMER_H #include <sys/cdefs.h> __BEGIN_DECLS #include <arch/types.h> #include <arch/irq.h> /* Timer sources -- we get four on the SH4 */ /** \brief SH4 Timer 0. This timer is used for thread operation, and thus is off limits if you want that to work properly. */ #define TMU0 0 /** \brief SH4 Timer 1. This timer is used for the timer_spin_sleep() function. */ #define TMU1 1 /** \brief SH4 Timer 2. This timer is used by the various gettime functions in this header. */ #define TMU2 2 /** \brief SH4 Watchdog Timer. KallistiOS does not currently support using this timer. */ #define WDT 3 /** \brief Which timer does the thread system use? */ #define TIMER_ID TMU0 /** \brief Pre-initialize a timer, but do not start it. This function sets up a timer for use, but does not start it. \param which The timer to set up (i.e, \ref TMU0). \param speed The number of ticks per second. \param interrupts Set to 1 to receive interrupts when the timer ticks. \retval 0 On success. */ int timer_prime(int which, uint32 speed, int interrupts); /** \brief Pre-initialize a timer for CDDA; set values but don't start it. This function sets up a timer for use, but does not start it. \param which The timer to set up (i.e, \ref TMU0). \param count The number of ticks per loop. \param interrupts Set to 1 to receive interrupts when the timer ticks. \retval 0 On success. */ int timer_prime_cdda(int which, uint32 count, int interrupts); /** \brief Pre-initialize a timer as do it the BIOS; set values but don't start it. This function sets up a timer for use, but does not start it. \param which The timer to set up (i.e, \ref TMU0). \retval 0 On success. */ int timer_prime_bios(int which); /** \brief Start a timer. This function starts a timer that has been initialized with timer_prime(), starting raising interrupts if applicable. \param which The timer to start (i.e, \ref TMU0). \retval 0 On success. */ int timer_start(int which); /** \brief Stop a timer. This function stops a timer that was started with timer_start(), and as a result stops interrupts coming in from the timer. \param which The timer to stop (i.e, \ref TMU0). \retval 0 On success. */ int timer_stop(int which); /** \brief Obtain the count of a timer. This function simply returns the count of the timer. \param which The timer to inspect (i.e, \ref TMU0). \return The timer's count. */ uint32 timer_count(int which); /** \brief Clear the underflow bit of a timer. This function clears the underflow bit of a timer if it was set. \param which The timer to inspect (i.e, \ref TMU0). \retval 0 If the underflow bit was clear (prior to calling). \retval 1 If the underflow bit was set (prior to calling). */ int timer_clear(int which); /** \brief Spin-loop sleep function. This function is meant as a very accurate delay function, even if threading and interrupts are disabled. It uses \ref TMU1 to sleep. \param ms The number of milliseconds to sleep. */ void timer_spin_sleep(int ms); /* Spin-loop kernel sleep func: uses the first timer in the SH-4 to very accurately delay even when interrupts are disabled */ void timer_spin_sleep_bios(int ms); /** \brief Enable high-priority timer interrupts. This function enables interrupts on the specified timer. \param which The timer to enable interrupts on (i.e, \ref TMU0). */ void timer_enable_ints(int which); /** \brief Disable timer interrupts. This function disables interrupts on the specified timer. \param which The timer to disable interrupts on (i.e, \ref TMU0). */ void timer_disable_ints(int which); /** \brief Check whether interrupts are enabled on a timer. This function checks whether or not interrupts are enabled on the specified timer. \param which The timer to inspect (i.e, \ref TMU0). \retval 0 If interrupts are disabled on the timer. \retval 1 If interrupts are enabled on the timer. */ int timer_ints_enabled(int which); /* \cond */ /* Init function */ int timer_init(); /* Shutdown */ void timer_shutdown(); /* \endcond */ /** \defgroup perf_counters Performance Counters The performance counter API exposes the SH4's hardware profiling registers, which consist of two different sets of independently operable 64-bit counters. */ /** \brief SH4 Performance Counter. \ingroup perf_counters This counter is used by the ns_gettime function in this header. */ #define PRFC0 0 /** \brief SH4 Performance Counter. \ingroup perf_counters A counter that is not used by KOS. */ #define PRFC1 1 /** \brief CPU Cycles Count Type. \ingroup perf_counters Count cycles. At 5 ns increments, a 48-bit cycle counter can run continuously for 16.33 days. */ #define PMCR_COUNT_CPU_CYCLES 0 /** \brief Ratio Cycles Count Type. \ingroup perf_counters CPU/bus ratio mode where cycles (where T = C x B / 24 and T is time, C is count, and B is time of one bus cycle). */ #define PMCR_COUNT_RATIO_CYCLES 1 /** \defgroup perf_counters_modes Performance Counter Modes This is the list of modes that are allowed to be passed into the perf_cntr_start() function, representing different things you want to count. \ingroup perf_counters @{ */ /* MODE DEFINITION VALUE MEASURMENT TYPE & NOTES */ #define PMCR_INIT_NO_MODE 0x00 /**< \brief None; Just here to be complete */ #define PMCR_OPERAND_READ_ACCESS_MODE 0x01 /**< \brief Quantity; With cache */ #define PMCR_OPERAND_WRITE_ACCESS_MODE 0x02 /**< \brief Quantity; With cache */ #define PMCR_UTLB_MISS_MODE 0x03 /**< \brief Quantity */ #define PMCR_OPERAND_CACHE_READ_MISS_MODE 0x04 /**< \brief Quantity */ #define PMCR_OPERAND_CACHE_WRITE_MISS_MODE 0x05 /**< \brief Quantity */ #define PMCR_INSTRUCTION_FETCH_MODE 0x06 /**< \brief Quantity; With cache */ #define PMCR_INSTRUCTION_TLB_MISS_MODE 0x07 /**< \brief Quantity */ #define PMCR_INSTRUCTION_CACHE_MISS_MODE 0x08 /**< \brief Quantity */ #define PMCR_ALL_OPERAND_ACCESS_MODE 0x09 /**< \brief Quantity */ #define PMCR_ALL_INSTRUCTION_FETCH_MODE 0x0a /**< \brief Quantity */ #define PMCR_ON_CHIP_RAM_OPERAND_ACCESS_MODE 0x0b /**< \brief Quantity */ /* No 0x0c */ #define PMCR_ON_CHIP_IO_ACCESS_MODE 0x0d /**< \brief Quantity */ #define PMCR_OPERAND_ACCESS_MODE 0x0e /**< \brief Quantity; With cache, counts both reads and writes */ #define PMCR_OPERAND_CACHE_MISS_MODE 0x0f /**< \brief Quantity */ #define PMCR_BRANCH_ISSUED_MODE 0x10 /**< \brief Quantity; Not the same as branch taken! */ #define PMCR_BRANCH_TAKEN_MODE 0x11 /**< \brief Quantity */ #define PMCR_SUBROUTINE_ISSUED_MODE 0x12 /**< \brief Quantity; Issued a BSR, BSRF, JSR, JSR/N */ #define PMCR_INSTRUCTION_ISSUED_MODE 0x13 /**< \brief Quantity */ #define PMCR_PARALLEL_INSTRUCTION_ISSUED_MODE 0x14 /**< \brief Quantity */ #define PMCR_FPU_INSTRUCTION_ISSUED_MODE 0x15 /**< \brief Quantity */ #define PMCR_INTERRUPT_COUNTER_MODE 0x16 /**< \brief Quantity */ #define PMCR_NMI_COUNTER_MODE 0x17 /**< \brief Quantity */ #define PMCR_TRAPA_INSTRUCTION_COUNTER_MODE 0x18 /**< \brief Quantity */ #define PMCR_UBC_A_MATCH_MODE 0x19 /**< \brief Quantity */ #define PMCR_UBC_B_MATCH_MODE 0x1a /**< \brief Quantity */ /* No 0x1b-0x20 */ #define PMCR_INSTRUCTION_CACHE_FILL_MODE 0x21 /**< \brief Cycles */ #define PMCR_OPERAND_CACHE_FILL_MODE 0x22 /**< \brief Cycles */ #define PMCR_ELAPSED_TIME_MODE 0x23 /**< \brief Cycles; For 200MHz CPU: 5ns per count in 1 cycle = 1 count mode, or around 417.715ps per count (increments by 12) in CPU/bus ratio mode */ #define PMCR_PIPELINE_FREEZE_BY_ICACHE_MISS_MODE 0x24 /**< \brief Cycles */ #define PMCR_PIPELINE_FREEZE_BY_DCACHE_MISS_MODE 0x25 /**< \brief Cycles */ /* No 0x26 */ #define PMCR_PIPELINE_FREEZE_BY_BRANCH_MODE 0x27 /**< \brief Cycles */ #define PMCR_PIPELINE_FREEZE_BY_CPU_REGISTER_MODE 0x28 /**< \brief Cycles */ #define PMCR_PIPELINE_FREEZE_BY_FPU_MODE 0x29 /**< \brief Cycles */ /** @} */ /** \brief Get a performance counter's settings. \ingroup perf_counters This function returns a performance counter's settings. \param which The performance counter (i.e, \ref PRFC0 or PRFC1). \retval 0 On success. */ uint16 perf_cntr_get_config(int which); /** \brief Start a performance counter. \ingroup perf_counters This function starts a performance counter \param which The counter to start (i.e, \ref PRFC0 or PRFC1). \param mode Use one of the 33 modes listed above. \param count_type PMCR_COUNT_CPU_CYCLES or PMCR_COUNT_RATIO_CYCLES. \retval 0 On success. */ int perf_cntr_start(int which, int mode, int count_type); /** \brief Stop a performance counter. \ingroup perf_counters This function stops a performance counter that was started with perf_cntr_start(). Stopping a counter retains its count. To clear the count use perf_cntr_clear(). \param which The counter to stop (i.e, \ref PRFC0 or PRFC1). \retval 0 On success. */ int perf_cntr_stop(int which); /** \brief Clear a performance counter. \ingroup perf_counters This function clears a performance counter. It resets its count to zero. This function stops the counter before clearing it because you cant clear a running counter. \param which The counter to clear (i.e, \ref PRFC0 or PRFC1). \retval 0 On success. */ int perf_cntr_clear(int which); /** \brief Obtain the count of a performance counter. \ingroup perf_counters This function simply returns the count of the counter. \param which The counter to read (i.e, \ref PRFC0 or PRFC1). \return The counter's count. */ uint64 perf_cntr_count(int which); /** \brief Enable the nanosecond timer. \ingroup perf_counters This function enables the performance counter used for the timer_ns_gettime64() function. This is on by default. The function uses \ref PRFC0 to do the work. */ void timer_ns_enable(); /** \brief Disable the nanosecond timer. \ingroup perf_counters This function disables the performance counter used for the timer_ns_gettime64() function. Generally, you will not want to do this, unless you have some need to use the counter \ref PRFC0 for something else. */ void timer_ns_disable(); /** \brief Get the current uptime of the system (in nanoseconds). \ingroup perf_counters This function retrieves the number of nanoseconds since KOS was started. \return The number of nanoseconds since KOS started. */ uint64 timer_ns_gettime64(); __END_DECLS #endif /* __ARCH_TIMER_H */ <file_sep>/firmware/isoldr/loader/fs/net/fs.c /** * DreamShell ISO Loader * Net file system * (c)2011-2016 SWAT <http://www.dc-swat.ru> */ #include "main.h" #include <kos/net.h> #include <net/net.h> //#define O_RDONLY 0 //#define O_WRONLY 1 //#define O_RDWR 2 #if !_FS_READONLY #define SC_WRITE "DD02" #define SC_UNLINK "DC08" #define SC_STAT "DC13" #endif #define SC_READ "DC03" #define SC_OPEN "DC04" #define SC_CLOSE "DC05" #define SC_LSEEK "DC11" /* #define SC_EXIT "DC00" #define SC_DIROPEN "DC16" #define SC_DIRCLOSE "DC17" #define SC_DIRREAD "DC18" #define SC_CDFSREAD "DC19" */ int sl_mode = SLMODE_NONE; static uint32 serial_hi = 0; // This code is common to read, write, lseek, and dirread. static int sc_rw_common(int fd, const uint8 * buffer, int amt, const char * code) { pkt_3i_t * rsp; // Send out the request rsp = (pkt_3i_t *)net_tx_build(); memcpy(rsp->tag, code, 4); rsp->value0 = htonl(fd); rsp->value1 = htonl((uint32)buffer); rsp->value2 = htonl(amt); rsp->value3 = htonl(serial_hi++); net_resp_complete(sizeof(pkt_3i_t)); // Wait for completion net_loop(); return net_rpc_ret; } // This code is common to open, stat, and unlink. static int sc_os_common(const char * fn, uint32 val1, uint32 val2, const char * tag) { pkt_2is_t * rsp; // Send out the request rsp = (pkt_2is_t *)net_tx_build(); memcpy(rsp->tag, tag, 4); rsp->value0 = htonl(val1); rsp->value1 = htonl(val2); strcpy(rsp->data, fn); net_resp_complete(sizeof(pkt_2is_t) + strlen(fn) + 1); // Wait for completion // DBG("Wait for completion"); net_loop(); return net_rpc_ret; } // This code is shared by close and dirclose. static int sc_close_common(int fd, const char * tag) { pkt_i_t * rsp; // Send out the request rsp = (pkt_i_t *)net_tx_build(); memcpy(rsp->tag, tag, 4); rsp->value0 = htonl(fd); net_resp_complete(sizeof(pkt_i_t)); // Wait for completion net_loop(); return net_rpc_ret; } int fs_init() { if(net_init() < 0) { printf("No network devices detected!"); return 0; } printf("Network initialized"); sl_mode = SLMODE_IMME; nif->if_stop(nif); return 1; } long int lseek(int fd, long int offset, int whence) { nif->if_start(nif); long int rv = sc_rw_common(fd, (uint8 *)offset, whence, SC_LSEEK); nif->if_stop(nif); return rv; } int open(const char *path, int mode) { nif->if_start(nif); int fd = sc_os_common(path, mode, 0, SC_OPEN); nif->if_stop(nif); return fd; } int close(int fd) { nif->if_start(nif); int rv = sc_close_common(fd, SC_CLOSE); nif->if_stop(nif); return rv; } int read(int fd, void *buf, unsigned int nbyte) { nif->if_start(nif); int br = sc_rw_common(fd, buf, nbyte, SC_READ); nif->if_stop(nif); return br; } #if !_FS_READONLY int write(int fd, void *buf, unsigned int nbyte) { nif->if_start(nif); int bw = sc_rw_common(fd, buf, nbyte, SC_WRITE); nif->if_stop(nif); return bw; } int unlink(const char *fn) { return sc_os_common(fn, 0, 0, SC_UNLINK); } int stat(const char *fn, uint8 *buffer) { return sc_os_common(fn, (ptr_t)buffer, 60, SC_STAT); } #endif /* static void sc_exit() { printf("sc_exit called\n"); exec_exit(); } static int sc_diropen(const char * dirname) { pkt_s_t * rsp; // Send out the request rsp = (pkt_s_t *)net_tx_build(); memcpy(rsp->tag, SC_DIROPEN, 4); strcpy(rsp->data, dirname); net_resp_complete(sizeof(pkt_s_t) + strlen(dirname) + 1); // Wait for completion net_loop(); return net_rpc_ret; } static int sc_dirclose(int fd) { return sc_close_common(fd, SC_DIRCLOSE); } static uint8 dirent_buffer[256+11]; static uint32 sc_dirread(int fd) { int rv = sc_rw_common(fd, dirent_buffer, 256+11, SC_DIRREAD); if (rv > 0) return (ptr_t)dirent_buffer; else return 0; } static int sc_invalid() { printf("sc_invalid called\n"); return -1; } typedef int (*sc_t)(uint32 param1, uint32 param2, uint32 param3); #define DECL(X) (sc_t)X static sc_t syscalls[] = { DECL(sc_read), DECL(sc_write), DECL(sc_open), DECL(sc_close), DECL(sc_invalid), // creat DECL(sc_invalid), // link DECL(sc_unlink), DECL(sc_invalid), // chdir DECL(sc_invalid), // chmod DECL(sc_lseek), DECL(sc_invalid), // fstat DECL(sc_invalid), // time DECL(sc_stat), DECL(sc_invalid), // utime DECL(sc_invalid), // assign_wrkmem DECL(sc_exit), DECL(sc_diropen), DECL(sc_dirclose), DECL(sc_dirread), DECL(sc_invalid) // gethostinfo }; int syscall(int scidx, uint32 param1, uint32 param2, uint32 param3) { int rv; if (scidx < 0 || scidx > (sizeof(syscalls)/sizeof(syscalls[0]))) return -1; // printf("syscall(%d)\n", scidx); sl_mode = SLMODE_IMME; nif->if_start(nif); rv = syscalls[scidx](param1, param2, param3); nif->if_stop(nif); sl_mode = SLMODE_COOP; return rv; } */ <file_sep>/modules/xvid/module.c /* DreamShell ##version## module.c - xvid module Copyright (C)2011-2014 SWAT */ #include "ds.h" #include "xvid.h" DEFAULT_MODULE_EXPORTS(xvid); <file_sep>/sdk/toolchain/Makefile # Dreamcast toolchain makefile by <NAME> # adapted from Stalin's build script version 0.3 # and modified for DreamShell by SWAT and YevDev # # Interesting parameters: # erase=0|1 Erase build directories on the fly to save space # thread_model=posix|single|kos Set gcc threading model # verbose=0|1 Display # makejobs=-jn Set the number of jobs for calls to make to n # # Interesting targets (you can 'make' any of these): # all: patch build # patch: patch-gcc patch-newlib # build: build-sh4 build-arm # build-sh4: build-sh4-binutils build-sh4-gcc # build-arm: build-arm-binutils build-arm-gcc # build-sh4-gcc: build-sh4-gcc-pass1 build-sh4-newlib build-sh4-gcc-pass2 # build-arm-gcc: build-arm-gcc-pass1 # build-sh4-newlib: build-sh4-newlib-only fixup-sh4-newlib # build-arm-newlib: build-arm-newlib-only fixup-arm-newlib # gdb # insight # # macOS build intruction: # $ brew install gcc # $ export PATH=/usr/local/Cellar/gcc/X.X.X/bin:$PATH # $ sudo make <target> CC=gcc-X CXX=g++-X CPP=cpp-X LD=g++-X # where X - gcc version, for instance: # $ export PATH=/usr/local/Cellar/gcc/8.1.0/bin:$PATH # $ sudo make all CC=gcc-8 CXX=g++-8 CPP=cpp-8 LD=g++-8 # # User configuration sh_target=sh-elf arm_target=arm-eabi sh_prefix := /opt/toolchains/dc/$(sh_target) arm_prefix := /opt/toolchains/dc/$(arm_target) # kos_root: KOS Git root (contains kos/ and kos-ports/) kos_root=/usr/local/dc/kos # kos_base: equivalent of KOS_BASE (contains include/ and kernel/) kos_base=/usr/local/dc/kos/kos binutils_ver=2.34 gcc_ver=9.3.0 newlib_ver=3.3.0 gdb_ver=9.2 insight_ver=6.8-1a # With GCC 4.x versions, the patches provide a kos thread model, so you should # use it. With 3.4.6, you probably want posix here. If you really don't want # threading support for C++ (or Objective C/Objective C++), you can set this to # single (why you would is beyond me, though). thread_model=kos erase=1 verbose=1 # Set this value to -jn where n is the number of jobs you want to run with make. # If you only want one job, just set this to nothing (i.e, "makejobs="). # Tracking down problems with multiple make jobs is much more difficult than # with just one running at a time. So, if you run into trouble, then you should # clear this variable and try again with just one job running. makejobs=-j2 # Set the languages to build for pass 2 of building gcc for sh-elf. The default # here is to build C, C++, Objective C, and Objective C++. You may want to take # out the latter two if you're not worried about them and/or you're short on # hard drive space. pass2_languages=c,c++,objc,obj-c++ # Change this if you don't have Bash installed in /bin SHELL = /bin/bash # GCC compiles fine with clang, but only if we use libstdc++ instead of libc++. UNAME_S := $(shell uname -s) ifeq ($(UNAME_S),Darwin) ifneq ($(shell $(CXX) --version | grep clang),) CXX := "$(CXX) -stdlib=libstdc++ -fbracket-depth=2048" endif endif # Catch all... ifeq ($(CXX),) CXX := g++ endif # Makefile variables install=$(prefix)/bin pwd := $(shell pwd) patches := $(pwd)/patches logdir := $(pwd)/logs PATH := $(sh_prefix)/bin:$(arm_prefix)/bin:$(PATH) binutils_dir=binutils-$(binutils_ver) gcc_dir=gcc-$(gcc_ver) newlib_dir=newlib-$(newlib_ver) all: patch build # ---- patch {{{ binutils_patches := $(wildcard $(patches)/binutils-$(binutils_ver)*.diff) gcc_patches := $(wildcard $(patches)/gcc-$(gcc_ver)*.diff) newlib_patches := $(wildcard $(patches)/newlib-$(newlib_ver)*.diff) patch_targets=patch-binutils patch-gcc patch-newlib patch: $(patch_targets) patch-binutils: $(binutils_patches) patch-gcc: $(gcc_patches) patch-newlib: $(newlib_patches) $(newlib_patches): patch -d $(newlib_dir) -p1 < $@ $(binutils_patches): patch -d $(binutils_dir) -p1 < $@ $(gcc_patches): patch -d $(gcc_dir) -p1 < $@ # ---- }}} # ---- build {{{ build: build-sh4 build-arm build-sh4: build-sh4-binutils build-sh4-gcc build-arm: build-arm-binutils build-arm-gcc build-sh4-gcc: build-sh4-gcc-pass1 build-sh4-newlib build-sh4-gcc-pass2 build-arm-gcc: build-arm-gcc-pass1 build-arm-newlib $(clean_arm_hack) build-sh4-newlib: build-sh4-newlib-only fixup-sh4-newlib build-arm-newlib: build-arm-newlib-only fixup-arm-newlib # Ensure that, no matter where we enter, prefix and target are set correctly. build_sh4_targets=build-sh4-binutils build-sh4-gcc build-sh4-gcc-pass1 build-sh4-newlib build-sh4-newlib-only build-sh4-gcc-pass2 build_arm_targets=build-arm-binutils build-arm-gcc build-arm-gcc-pass1 build-arm-newlib build-arm-newlib-only $(build_sh4_targets): prefix = $(sh_prefix) $(build_sh4_targets): target = $(sh_target) $(build_sh4_targets): extra_configure_args = --with-multilib-list=m4-single-only --with-endian=little --with-cpu=m4-single-only $(build_arm_targets): prefix = $(arm_prefix) $(build_arm_targets): target = $(arm_target) $(build_arm_targets): extra_configure_args = --with-arch=armv4 # To avoid code repetition, we use the same commands for both # architectures. But we can't create a single target called # build-binutils for both sh4 and arm, because phony targets # can't be run multiple times. So we create multiple targets. build_binutils = build-sh4-binutils build-arm-binutils build_gcc_pass1 = build-sh4-gcc-pass1 build-arm-gcc-pass1 build_newlib_sh4 = build-sh4-newlib-only build_gcc_pass2 = build-sh4-gcc-pass2 build_newlib_arm = build-arm-newlib-only # Here we use the essentially same code for multiple targets, # differing only by the current state of the variables below. $(build_binutils): build = build-binutils-$(target)-$(binutils_ver) $(build_binutils): src_dir = binutils-$(binutils_ver) $(build_binutils): log = $(logdir)/$(build).log $(build_binutils): logdir @echo "+++ Building $(src_dir) to $(build)..." -mkdir -p $(build) > $(log) cd $(build); ../$(src_dir)/configure --target=$(target) --prefix=$(prefix) --disable-werror CXX=$(CXX) $(to_log) make $(makejobs) -C $(build) DESTDIR=$(DESTDIR) $(to_log) make -C $(build) install DESTDIR=$(DESTDIR) $(to_log) $(clean_up) $(build_gcc_pass1) $(build_gcc_pass2): build = build-gcc-$(target)-$(gcc_ver) $(build_gcc_pass1) $(build_gcc_pass2): src_dir = gcc-$(gcc_ver) $(build_gcc_pass1): log = $(logdir)/$(build)-pass1.log $(build_gcc_pass1): logdir @echo "+++ Building $(src_dir) to $(build) (pass 1)..." -mkdir -p $(build) > $(log) cd $(build); ../$(src_dir)/configure --target=$(target) --prefix=$(prefix) --without-headers --with-newlib --enable-languages=c --disable-libssp --disable-tls $(extra_configure_args) CXX=$(CXX) $(to_log) make $(makejobs) -C $(build) DESTDIR=$(DESTDIR) $(to_log) make -C $(build) install DESTDIR=$(DESTDIR) $(to_log) $(build_newlib_sh4) $(build_newlib_arm): build = build-newlib-$(target)-$(newlib_ver) $(build_newlib_sh4) $(build_newlib_arm): src_dir = newlib-$(newlib_ver) $(build_newlib_sh4) $(build_newlib_arm): log = $(logdir)/$(build).log $(build_newlib_sh4) $(build_newlib_arm): logdir @echo "+++ Building $(src_dir) to $(build)..." -mkdir -p $(build) > $(log) cd $(build); ../$(src_dir)/configure --target=$(target) --prefix=$(prefix) $(extra_configure_args) $(to_log) make $(makejobs) -C $(build) DESTDIR=$(DESTDIR) $(to_log) make -C $(build) install DESTDIR=$(DESTDIR) $(to_log) $(clean_up) fixup-sh4-newlib: newlib_inc=$(DESTDIR)$(sh_prefix)/$(sh_target)/include fixup-sh4-newlib: $(build_newlib_sh4) @echo "+++ Fixing up sh4 newlib includes..." # KOS pthread.h is modified # to define _POSIX_THREADS # pthreads to kthreads mapping # so KOS includes are available as kos/file.h # kos/thread.h requires arch/arch.h # arch/arch.h requires dc/video.h cp $(kos_base)/include/pthread.h $(newlib_inc) cp $(kos_base)/include/sys/_pthread.h $(newlib_inc)/sys cp $(kos_base)/include/sys/sched.h $(newlib_inc)/sys ln -nsf $(kos_base)/include/kos $(newlib_inc) ln -nsf $(kos_base)/kernel/arch/dreamcast/include/arch $(newlib_inc) ln -nsf $(kos_base)/kernel/arch/dreamcast/include/dc $(newlib_inc) fixup-arm-newlib: newlib_inc=$(DESTDIR)$(arm_prefix)/$(arm_target)/include fixup-arm-newlib: $(build_newlib_arm) @echo "+++ Fixing up arm newlib includes..." $(build_gcc_pass2): log = $(logdir)/$(build)-pass2.log $(build_gcc_pass2): logdir @echo "+++ Building $(src_dir) to $(build) (pass 2)..." -mkdir -p $(build) > $(log) cd $(build); ../$(src_dir)/configure --target=$(target) --prefix=$(prefix) --with-newlib --disable-libssp --disable-tls \ --enable-threads=$(thread_model) --enable-languages=$(pass2_languages) $(extra_configure_args) CXX=$(CXX) $(to_log) make $(makejobs) -C $(build) DESTDIR=$(DESTDIR) $(to_log) make -C $(build) install DESTDIR=$(DESTDIR) $(to_log) $(clean_up) # ---- }}}} # GDB building gdb-$(gdb_ver).tar.bz2: @echo "+++ Downloading GDB..." wget -c ftp://ftp.gnu.org/gnu/gdb/gdb-$(gdb_ver).tar.bz2 unpack_gdb: gdb-$(gdb_ver).tar.bz2 unpack_gdb_stamp unpack_gdb_stamp: @echo "+++ Unpacking GDB..." rm -f $@ rm -rf gdb-$(gdb_ver) tar jxf gdb-$(gdb_ver).tar.bz2 touch $@ build_gdb: log = $(logdir)/gdb-$(gdb_ver).log build_gdb: logdir build_gdb: unpack_gdb build_gdb_stamp build_gdb_stamp: @echo "+++ Building GDB..." rm -f $@ > $(log) rm -rf build-gdb-$(gdb_ver) mkdir build-gdb-$(gdb_ver) cd build-gdb-$(gdb_ver); ../gdb-$(gdb_ver)/configure \ --prefix=$(sh_prefix) \ --target=$(sh_target) \ --disable-werror $(to_log) make $(makejobs) -C build-gdb-$(gdb_ver) $(to_log) touch $@ install_gdb: log = $(logdir)/gdb-$(gdb_ver).log install_gdb: logdir install_gdb: build_gdb install_gdb_stamp install_gdb_stamp: @echo "+++ Installing GDB..." rm -f $@ make -C build-gdb-$(gdb_ver) install DESTDIR=$(DESTDIR) $(to_log) touch $@ gdb: install_gdb # INSIGHT building insight-$(insight_ver).tar.bz2: @echo "+++ Downloading INSIGHT..." wget -c ftp://sourceware.org/pub/insight/releases/insight-$(insight_ver).tar.bz2 unpack_insight: insight-$(insight_ver).tar.bz2 unpack_insight_stamp unpack_insight_stamp: @echo "+++ Unpacking INSIGHT..." rm -f $@ rm -rf insight-$(insight_ver) tar jxf insight-$(insight_ver).tar.bz2 touch $@ build_insight: log = $(logdir)/insight-$(insight_ver).log build_insight: logdir build_insight: unpack_insight build_insight_stamp build_insight_stamp: @echo "+++ Building INSIGHT..." rm -f $@ > $(log) rm -rf build-insight-$(insight_ver) mkdir build-insight-$(insight_ver) cd build-insight-$(insight_ver); ../insight-$(insight_ver)/configure \ --prefix=$(sh_prefix) \ --target=$(sh_target) \ --disable-werror $(to_log) make $(makejobs) -C build-insight-$(insight_ver) $(to_log) touch $@ install_insight: log = $(logdir)/insight-$(insight_ver).log install_insight: logdir install_insight: build_insight install_insight_stamp install_insight_stamp: @echo "+++ Installing INSIGHT..." rm -f $@ make -C build-insight-$(insight_ver) install DESTDIR=$(DESTDIR) $(to_log) touch $@ insight: install_insight # ---- support {{{ clean: -rm -rf build-newlib-$(sh_target)-$(newlib_ver) -rm -rf build-newlib-$(arm_target)-$(newlib_ver) -rm -rf build-gcc-$(sh_target)-$(gcc_ver) -rm -rf build-gcc-$(arm_target)-$(gcc_ver) -rm -rf build-binutils-$(sh_target)-$(binutils_ver) -rm -rf build-binutils-$(arm_target)-$(binutils_ver) -rm -rf build-gdb-$(gdb_ver) install_gdb_stamp build_gdb_stamp -rm -rf build-insight-$(gdb_ver) install_insight_stamp build_insight_stamp logdir: @mkdir -p $(logdir) # If erase=1, erase build directories on the fly. ifeq (1,$(erase)) define clean_up @echo "+++ Cleaning up $(build)..." -rm -rf $(build) endef # Hack to clean up ARM gcc pass 1 define clean_arm_hack @echo "+++ Cleaning up build-gcc-$(arm_target)-$(gcc_ver)..." -rm -rf build-gcc-$(arm_target)-$(gcc_ver) endef endif # If verbose=1, display output to screen as well as log files ifeq (1,$(verbose)) to_log = 2>&1 | tee -a $(log) && [ $$PIPESTATUS -eq 0 ] else to_log = >> $(log) 2>&1 endif # ---- }}} # ---- phony targets {{{ .PHONY: $(patch_targets) .PHONY: $(newlib_patches) $(binutils_patches) $(gcc_patches) $(kos_patches) .PHONY: all build patch build-sh4 build-arm $(build_sh4_targets) $(build_arm_targets) clean .PHONY: build-binutils build-newlib build-gcc-pass1 build-gcc-pass2 fixup-sh4-newlib .PHONY: gdb install_gdb build_gdb unpack_gdb .PHONY: insight install_insight build_insight unpack_insight # ---- }}}} # vim:tw=0:fdm=marker:fdc=2:fdl=1 <file_sep>/modules/isofs/ciso.c /** * Copyright (c) 2011-2014 by SWAT <<EMAIL>> www.dc-swat.ru * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <kos.h> #include "minilzo/minilzo.h" #include "zlib/zlib.h" #include "isofs/ciso.h" #include "console.h" //#define DEBUG 1 #define isCompressed(block) ((block & 0x80000000) == 0) #define getPosition(block, align) ((block & 0x7FFFFFFF) << align) static int check_cso_image(file_t fd) { uint32 magic = 0; fs_seek(fd, 0, SEEK_SET); fs_read(fd, &magic, sizeof(magic)); if(magic != CISO_MAGIC_CISO && magic != CISO_MAGIC_ZISO) { return -1; } return 0; } CISO_header_t *ciso_open(file_t fd) { if(check_cso_image(fd) < 0) { return NULL; } int ret; uint32 *magic; CISO_header_t *hdr; hdr = (CISO_header_t*)malloc(sizeof(CISO_header_t)); if(hdr == NULL) { return NULL; } memset_sh4(hdr, 0, sizeof(CISO_header_t)); hdr->magic[0] = '\0'; fs_seek(fd, 0, SEEK_SET); ret = fs_read(fd, hdr, sizeof(CISO_header_t)); if(ret != sizeof(CISO_header_t)) { free(hdr); return NULL; } magic = (uint32*)hdr->magic; #ifdef DEBUG dbglog(DBG_DEBUG, "Magic: %c%c%c%c\n", hdr->magic[0], hdr->magic[1], hdr->magic[2], hdr->magic[3]); dbglog(DBG_DEBUG, "Hdr size: %lu\n", hdr->header_size); dbglog(DBG_DEBUG, "Total bytes: %llu\n", hdr->total_bytes); dbglog(DBG_DEBUG, "Block size: %lu\n", hdr->block_size); dbglog(DBG_DEBUG, "Version: %02x\n", hdr->ver); dbglog(DBG_DEBUG, "Align: %d\n", 1 << hdr->align); #endif if(*magic == CISO_MAGIC_CISO) { ; } else if(*magic == CISO_MAGIC_ZISO) { if(lzo_init() != LZO_E_OK) { ds_printf("DS_ERROR: lzo_init() failed\n"); free(hdr); hdr = NULL; } } else { free(hdr); hdr = NULL; } return hdr; } int ciso_close(CISO_header_t *hdr) { if(hdr != NULL) { free(hdr); return 0; } return -1; } int ciso_get_blocks(CISO_header_t *hdr, file_t fd, uint *blocks, uint32 sector, uint32 cnt) { #ifdef DEBUG dbglog(DBG_DEBUG, "%s: fd=%d seek=%lu\n", __func__, fd, sizeof(CISO_header_t) + (sector * sizeof(uint))); #endif int r = 0; //uint len = (uint)(hdr->total_bytes / hdr->block_size) + 1; fs_seek(fd, sizeof(CISO_header_t) + (sector * sizeof(uint)), SEEK_SET); r = fs_read(fd, blocks, sizeof(uint) * cnt); #ifdef DEBUG int i; for(i = 0; i < cnt; i++) dbglog(DBG_DEBUG, " blocks[%d]=%08u\n", i, blocks[i]); #endif return r; } static int ciso_read_sector(CISO_header_t *hdr, file_t fd, uint8 *buff, uint8 *buffc, uint32 sector) { uint32 *magic, dlen; uint blocks[2], start, len; z_stream zstream; zstream.zalloc = Z_NULL; zstream.zfree = Z_NULL; zstream.opaque = Z_NULL; #ifdef DEBUG dbglog(DBG_DEBUG, "%s: fd=%d sector=%ld\n", __func__, fd, sector); #endif ciso_get_blocks(hdr, fd, blocks, sector, 2); start = getPosition(blocks[0], hdr->align); len = getPosition(blocks[1], hdr->align) - start; #ifdef DEBUG dbglog(DBG_DEBUG, "%s: fd=%d start=%d len=%d\n", __func__, fd, start, len); #endif fs_seek(fd, start, SEEK_SET); zstream.avail_in = fs_read(fd, buffc, len); if(len == zstream.avail_in && isCompressed(blocks[0])) { magic = (uint32*)hdr->magic; switch(*magic) { case CISO_MAGIC_CISO: #ifdef DEBUG dbglog(DBG_DEBUG, "%s: decompress zlib\n", __func__); #endif if(inflateInit2(&zstream, -15) != Z_OK) { ds_printf("DS_ERROR: zlib init error: %s\n", zstream.msg ? zstream.msg : "unknown"); return -1; } zstream.next_out = buff; zstream.avail_out = hdr->block_size; zstream.next_in = buffc; if(inflate(&zstream, Z_FULL_FLUSH) != Z_STREAM_END) { ds_printf("DS_ERROR: zlib inflate error: %s\n", zstream.msg ? zstream.msg : "unknown"); return -1; } inflateEnd(&zstream); break; case CISO_MAGIC_ZISO: #ifdef DEBUG dbglog(DBG_DEBUG, "%s: decompress lzo\n", __func__); #endif if(lzo1x_decompress(buffc, len, buff, &dlen, NULL) != LZO_E_OK) { ds_printf("DS_ERROR: lzo decompress error\n", __func__); return -1; } if(dlen != hdr->block_size) { return -1; } break; default: memcpy_sh4(buff, buffc, hdr->block_size); break; } } else if(len == zstream.avail_in) { memcpy_sh4(buff, buffc, hdr->block_size); } else { return -1; } return 0; } int ciso_read_sectors(CISO_header_t *hdr, file_t fd, uint8 *buff, uint32 start, uint32 count) { uint8 *buffc; buffc = (uint8*) malloc(hdr->block_size); if(buffc == NULL) { return -1; } while(count--) { if(ciso_read_sector(hdr, fd, buff, buffc, start++)) { return -1; } buff += hdr->block_size; } free(buffc); return 0; } <file_sep>/modules/Makefile # # DreamShell modules Makefile # Copyright (C) 2009-2023 SWAT # http://www.dc-swat.ru # _SUBDIRS = minilzo isofs isoldr ppp bflash dreameye \ bzip2 zip ini opkg sqlite3 vkb \ luaTask luaSocket tolua tolua++ \ luaDS luaKOS luaSDL luaGUI luaMXML luaSQL luaSTD \ SDL_net http httpd telnetd mongoose gumbo \ adx s3m mp3 ogg xvid ffmpeg bitcoin openssl ftpd all: $(patsubst %, _dir_%, $(_SUBDIRS)) $(patsubst %, _dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _dir_%, %, $@) clean: $(patsubst %, _clean_dir_%, $(_SUBDIRS)) $(patsubst %, _clean_dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _clean_dir_%, %, $@) clean install: $(patsubst %, _install_dir_%, $(_SUBDIRS)) $(patsubst %, _install_dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _install_dir_%, %, $@) install <file_sep>/firmware/isoldr/loader/kos/stdio.h /** * DreamShell ISO Loader * Generic stdio-style functions * (c)2009-2014 SWAT <http://www.dc-swat.ru> */ #ifndef __STDIO_H #define __STDIO_H #include <sys/cdefs.h> #include <stddef.h> #include <stdarg.h> /* Flags which can be passed to number () */ #define N_ZEROPAD 1 /* pad with zero */ #define N_SIGN 2 /* unsigned/signed long */ #define N_PLUS 4 /* show plus */ #define N_SPACE 8 /* space if plus */ #define N_LEFT 16 /* left justified */ #define N_SPECIAL 32 /* 0x */ #define N_LARGE 64 /* use 'ABCDEF' instead of 'abcdef' */ char *printf_number(char *str, long num, int32 base, int32 size, int32 precision, int32 type); int vsnprintf(char *buf, int size, const char *fmt, va_list args); int snprintf(char *buf, int size, const char *fmt, ...); int vsprintf(char *, const char *, va_list); int sprintf(char *, const char *, ...); int printf(const char *, ...); #endif /* __STDIO_H */ <file_sep>/modules/vkb/Makefile # # Virtual keyboard module for DreamShell # Copyright (C) 2014 SWAT # http://www.dc-swat.ru # TARGET_NAME = vkb OBJS = module.o $(TARGET_NAME).o DBG_LIBS = -lds EXPORTS_FILE = exports.txt VER_MAJOR = 1 VER_MINOR = 3 VER_MICRO = 1 all: rm-elf include ../../sdk/Makefile.loadable rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/firmware/isoldr/loader/kos/src/conio.c /* KallistiOS ##version## conio.c (c)2002 <NAME> Adapted from Kosh, (c)2000 <NAME>, (c)2014 SWAT */ #include "main.h" /* some defines */ #define CONIO_NUM_ROWS 7 #define CONIO_NUM_COLS 48 /* our cursor */ typedef struct { int row, col; } conio_cursor_t; /* the cursor */ static conio_cursor_t conio_cursor; /* the virtual screen */ static char conio_virtscr[CONIO_NUM_ROWS][CONIO_NUM_COLS]; void draw_virtscr() { int row, col, y = 1, x = 1; for (row = 0; row <= conio_cursor.row; row++) { for (col = 0; col < CONIO_NUM_COLS; col++) { bfont_draw(vram_s + (x*12) + ((y*24+4) * 640), vid_pixel(224,224,224), vid_pixel(0,0,0), conio_virtscr[row][col]); x++; } x = 1; y++; } } /* scroll everything up a line */ void conio_scroll() { int i; memcpy(conio_virtscr, conio_virtscr[1], (CONIO_NUM_ROWS - 1) * CONIO_NUM_COLS); for (i = 0; i < CONIO_NUM_COLS; i++) conio_virtscr[CONIO_NUM_ROWS - 1][i] = ' '; conio_cursor.row--; } /* put a character at the cursor and move the cursor */ void conio_putch(int ch) { switch (ch) { case '\r': conio_cursor.col = 0; for (int col = 0; col < CONIO_NUM_COLS; col++) conio_virtscr[conio_cursor.row][col] = ' '; break; case '\n': conio_cursor.row++; conio_cursor.col = 0; if (conio_cursor.row >= CONIO_NUM_ROWS) conio_scroll(); break; default: conio_virtscr[conio_cursor.row][conio_cursor.col++] = ch; if(conio_cursor.col >= CONIO_NUM_COLS) conio_putch('\n'); } } /* put a string of characters */ void conio_putstr(char *str) { while (*str != '\0') { conio_putch(*str++); } } /* a printfish function */ int conio_printf(const char *fmt, ...) { char buff[128]; va_list args; int i; va_start(args, fmt); i = vsnprintf(buff, sizeof(buff), fmt, args); conio_putstr(buff); va_end(args); #ifdef LOG WriteLog(buff); #endif if(IsoInfo->video_mode > 0) { draw_virtscr(); } return i; } /* clear the screen */ void conio_clear() { int row, col; for (row = 0; row < CONIO_NUM_ROWS; row++) for (col = 0; col < CONIO_NUM_COLS; col++) conio_virtscr[row][col] = ' '; } <file_sep>/modules/OpenGL/module.c /* DreamShell ##version## module.c - OpenGL module Copyright (C)2009-2014 SWAT */ #include "ds.h" DEFAULT_MODULE_EXPORTS(opengl); <file_sep>/include/drivers/dreameye.h /** * \file dreameye.h * \brief Dreameye driver extension * \date 2015 * \author SWAT www.dc-swat.ru */ #ifndef __DS_DREAMEYE_H #define __DS_DREAMEYE_H #include <sys/cdefs.h> __BEGIN_DECLS #include <arch/types.h> #include <dc/maple.h> #include <dc/maple/dreameye.h> /** \brief Dreameye status structure. This structure contains information about the status of the Camera device and can be fetched with maple_dev_status(). You should not change any of this information, it should all be considered read-only. */ typedef struct dreameye_state_ext { /** \brief The number of images on the device. */ int image_count; /** \brief Is the image_count field valid? */ int image_count_valid; /** \brief The number of transfer operations required for the selected image. */ int transfer_count; /** \brief Is an image transferring now? */ int img_transferring; /** \brief Storage for image data. */ uint8 *img_buf; /** \brief The size of the image in bytes. */ int img_size; /** \brief The image number currently being transferred. */ uint8 img_number; /** \brief The value from/to subsystems. */ int value; } dreameye_state_ext_t; /** \brief Read/write CMOS Image Sensor registers. */ #define DREAMEYE_COND_REG_CIS 0x00 /** \brief Read/write Image Signal Processor registers. */ #define DREAMEYE_COND_REG_ISP 0x10 /** \brief Read/write JangGu Compression Engine registers. */ #define DREAMEYE_COND_REG_JANGGU 0x20 /** \brief Read/write JPEG Compression Engine registers. */ #define DREAMEYE_COND_REG_JPEG 0x21 // Supported by Dreameye??? /** * Really clock frequency request for each subsystem, * but Dreameye response only for maple bus (use 0x90 as argument too) */ #define DREAMEYE_COND_MAPLE_BITRATE 0x90 #define DREAMEYE_GETCOND_RESOLUTION 0x91 #define DREAMEYE_GETCOND_COMPRESS_FMT 0x92 #define DREAMEYE_COND_FLASH_TOTAL 0x94 #define DREAMEYE_COND_FLASH_REMAIN 0x96 #define DREAMEYE_DATA_IMAGE 0x00 #define DREAMEYE_DATA_PROGRAM 0xC1 #define DREAMEYE_IMAGE_SIZE_QSIF 0x00 #define DREAMEYE_IMAGE_SIZE_QCIF 0x01 #define DREAMEYE_IMAGE_SIZE_SIF 0x02 #define DREAMEYE_IMAGE_SIZE_CIF 0x03 #define DREAMEYE_IMAGE_SIZE_VGA 0x04 // Only this supported by Dreameye??? #define DREAMEYE_IMAGE_SIZE_SVGA 0x05 /** \brief Transfer an image from the Dreameye. This function fetches a single image from the specified Dreameye device. This function will block, and can take a little while to execute. You must use the first subdevice of the MAPLE_FUNC_CONTROLLER root device of the Dreameye as the dev parameter. \param dev The device to get an image from. \param image The image number to download. \param data A pointer to a buffer to store things in. This will be allocated by the function and you are responsible for freeing the data when you are done. \param img_sz A pointer to storage for the size of the image, in bytes. \retval MAPLE_EOK On success. \retval MAPLE_EFAIL On error. */ int dreameye_get_video_frame(maple_device_t *dev, uint8 image, uint8 **data, int *img_sz); /** \brief Get params from any subsystem * TODO */ int dreameye_get_param(maple_device_t *dev, uint8 param, uint8 arg, uint16 *value); /** \brief Set params for any subsystem * TODO */ int dreameye_set_param(maple_device_t *dev, uint8 param, uint8 arg, uint16 value); __END_DECLS #endif /* __DS_DREAMEYE_H */ <file_sep>/applications/filemanager/lua/main.lua ------------------------------------------- -- -- -- @name: File Manager -- -- @version: 0.6.5 -- -- @author: SWAT -- -- @url: http://www.dc-swat.ru -- -- -- ------------------------------------------- --if not FileManager then FileManager = { app = nil, font = nil, title = nil, prev_title = nil, modules = {}, ffmpeg = { ext = { ".mpg", ".m1v", ".m2v", ".sfd", ".pss", "mpeg", ".avi", ".mkv", ".m4v", ".flv", ".f4v", ".wmv", "m2ts", ".mpv", ".mp4", ".3gp", ".4xm", ".mov", ".mgp" } }, mgr = { top = { id = 0, widget = nil, focus = true, ent = { name = nil, size = -1, time = 0, attr = 1, index = -1 } }, bottom = { id = 1, widget = nil, focus = true, ent = { name = nil, size = -1, time = 0, attr = 1, index = -1 } }, dual = true, bg = { normal = nil, focus = nil }, item = { normal = nil, selected = nil } }, modal = { widget = nil, label = nil, input = nil, ok = nil, cancel = nil, visible = true, func = nil, mode = "prompt" } } function FileManager:ext_supported(tbl, ext) for i = 1, table.getn(tbl) do if tbl[i] == ext then return true; end end return false; end function FileManager:ShowModal(mode, label, func, input) if self.modal.visible then self:HideModal(); end --print("FileManager: " .. label .. "\n"); if mode == "alert" then GUI.LabelSetText(self.modal.label, label); if self.modal.mode ~= "alert" then GUI.WidgetSetEnabled(self.modal.cancel, 0); GUI.WidgetSetPosition(self.modal.ok, 145, 116); end if self.modal.mode == "prompt" then GUI.ContainerRemove(self.modal.widget, self.modal.input); end elseif mode == "confirm" then if self.modal.mode == "prompt" then GUI.ContainerRemove(self.modal.widget, self.modal.input); end GUI.LabelSetText(self.modal.label, label); GUI.WidgetSetPosition(self.modal.ok, 110, 116); GUI.WidgetSetEnabled(self.modal.cancel, 1); elseif mode == "prompt" then if self.modal.mode ~= "prompt" then GUI.ContainerAdd(self.modal.widget, self.modal.input); end GUI.LabelSetText(self.modal.label, label); GUI.TextEntrySetText(self.modal.input, input); if self.modal.mode == "alert" then GUI.WidgetSetPosition(self.modal.ok, 110, 116); GUI.WidgetSetEnabled(self.modal.cancel, 1); end else return false; end GUI.ContainerSetEnabled(self.mgr.top.widget, 0); GUI.ContainerSetEnabled(self.mgr.bottom.widget, 0); GUI.ContainerAdd(self.app.body, self.modal.widget); GUI.WidgetMarkChanged(self.modal.widget); self.modal.func = func; self.modal.visible = true; self.modal.mode = mode; return true; end function FileManager:HideModal() if self.modal.visible then GUI.ContainerRemove(self.app.body, self.modal.widget); GUI.ContainerSetEnabled(self.mgr.top.widget, 1); GUI.ContainerSetEnabled(self.mgr.bottom.widget, 1); self.modal.visible = false; self.modal.func = nil; end end function FileManager:ModalClick(s) if s and self.modal.visible and self.modal.func then if self.modal.func == "delete" then self:toolbarDelete(); elseif self.modal.func == "mount_iso" then self:toolbarMountISO(); elseif self.modal.func == "copy" then self:toolbarCopy(); elseif self.modal.func == "rename" then self:toolbarRename(); elseif self.modal.func == "exec" then self:openFile(); elseif self.modal.func == "archive" then self:toolbarArchive(); else return self:ShowModal("alert", "Unknown command", nil); end end self:HideModal(); end function FileManager:showConsole() ShowConsole(); end function FileManager:hideConsole() Sleep(1000); HideConsole(); end function FileManager:execConsole(cmd) self:showConsole(); os.execute(cmd); self:hideConsole(); end function FileManager:toolbarCopy() local f = self:getFile(); local mgr = self:getUnfocusedManager(); local to = GUI.FileManagerGetPath(mgr.widget); if not self.modal.visible then return self:ShowModal("confirm", "Copy '" .. f.name .. "' to '" .. to .. "'?", "copy"); else self:HideModal(); end if to ~= "/" then to = to .. "/" .. f.name; else to = to .. f.name; end if f.attr ~= 0 or f.size > 8192*1024 then self:execConsole("cp " .. f.file .. " " .. to .. " 1") else if os.execute("cp " .. f.file .. " " .. to) ~= DS.CMD_OK then self:showConsole(); return; end GUI.FileManagerScan(mgr.widget); end end function FileManager:toolbarRename() local f = self:getFile(); if not self.modal.visible then return self:ShowModal("prompt", "Enter new name:", "rename", f.name); else self:HideModal(); end local dst = f.path .. "/" .. GUI.TextEntryGetText(self.modal.input); if os.execute("rename " .. f.file .. " " .. dst) ~= DS.CMD_OK then self:showConsole(); return; end local mgr = self:getFocusedManager(); GUI.FileManagerScan(mgr.widget); end function FileManager:toolbarDelete() local f = self:getFile(); if not self.modal.visible then return self:ShowModal("confirm", 'Delete "' .. f.name .. '"?', "delete"); else self:HideModal(); end if os.execute("rm " .. f.file) ~= DS.CMD_OK then self:showConsole(); return false; end local mgr = self:getFocusedManager(); GUI.FileManagerScan(mgr.widget); end function FileManager:toolbarArchive() local f = self:getFile(); local ext = string.lower(string.sub(f.name, -4)); local file = f.file; local name = f.name; local mgr = self:getUnfocusedManager(); local dst = GUI.FileManagerGetPath(mgr.widget); local msg = "Uknown"; local cmd = ""; if ext == ".gz" then msg = "Extract "; cmd = "gzip -d " .. file .. " " .. dst .. string.sub(name, 1, -4); elseif ext == "bz2" then if not DS.GetCmdByName("bzip2") then if not self:loadModule("bzip2") then self:showConsole(); return; end end msg = "Extract "; cmd = "bzip2 -d " .. file .. " " .. dst .. string.sub(name, 1, -5); elseif ext == "zip" then if not DS.GetCmdByName("zip") then if not self:loadModule("zip") then self:showConsole(); return; end end msg = "Extract "; cmd = "unzip -e -o " .. file .. " -d " .. dst; else msg = "Compress "; cmd = "gzip -9 " .. file .. " " .. dst .. name .. ".gz"; end if not self.modal.visible then return self:ShowModal("confirm", msg .. '"' .. name .. '"?', "archive"); else self:HideModal(); end self:execConsole(cmd) GUI.FileManagerScan(mgr.widget); end function FileManager:toolbarModeSwitch() if self.mgr.dual then GUI.ContainerRemove(self.app.body, self.mgr.bottom.widget); GUI.FileManagerResize(self.mgr.top.widget, 610, 445); GUI.FileManagerSetScrollbar(self.mgr.top.widget, nil, self:getResource("sb-back-big", DS.LIST_ITEM_GUI_SURFACE)); self.mgr.dual = false; else GUI.FileManagerResize(self.mgr.top.widget, 610, 220); GUI.FileManagerSetScrollbar(self.mgr.top.widget, nil, self:getResource("sb-back", DS.LIST_ITEM_GUI_SURFACE)); GUI.ContainerAdd(self.app.body, self.mgr.bottom.widget); GUI.WidgetMarkChanged(self.app.body); self.mgr.dual = true; end end function FileManager:toolbarMountISO() local f = self:getFile(); if not self.modal.visible then return self:ShowModal("confirm", 'Mount selected ISO as VFS?', "mount_iso"); else self:HideModal(); end if not DS.GetCmdByName("isofs") then if not self:loadModule("minilzo") or not self:loadModule("isofs") then self:showConsole(); return; end end if os.execute("isofs -m -f " .. f.file .. " -d /iso") ~= DS.CMD_OK then self:showConsole(); end end function FileManager:loadModule(name) local file = os.getenv("PATH") .. "/modules/" .. name .. ".klf"; local m = OpenModule(file); if m ~= nil then table.insert(self.modules, m); return true; end return false; end function FileManager:unloadModules() if table.getn(self.modules) > 0 then for i = 1, table.getn(self.modules) do if self.modules[i] ~= nil then CloseModule(self.modules[i]); end table.remove(self.modules, i); end end end function FileManager:openApp(name, args, unload_fm) self:Shutdown(); -- Unload user modules? CloseApp(self.app.name, unload_fm); OpenApp(name, args); end function FileManager:openFile() local f = self:getFile(); local ext = string.lower(string.sub(f.name, -4)); local file = f.file; local name = f.name; if ext == ".bin" or ext == ".elf" then if not self.modal.visible then return self:ShowModal("confirm", 'Execute "' .. name .. '" ?', "exec"); else self:HideModal(); end local flag = "-b"; if ext == ".elf" then flag = "-e"; end self:execConsole("exec "..flag.." -f " .. file); elseif ext == ".txt" then if not self.modal.visible then return self:ShowModal("confirm", 'Cat file "' .. name .. '" to console?', "exec"); else self:HideModal(); end self:showConsole(); os.execute("cat " .. file); elseif ext == ".klf" then if not self.modal.visible then return self:ShowModal("confirm", 'Load module "' .. name .. '" ?', "exec"); else self:HideModal(); end --if DS.GetModuleByFileName(file) then return file end self:execConsole("module -o -f " .. file) elseif ext == ".lua" then if not self.modal.visible then return self:ShowModal("confirm", 'Run lua script "' .. name .. '" ?', "exec"); else self:HideModal(); end self:execConsole("lua " .. file) elseif ext == ".dsc" then if not self.modal.visible then return self:ShowModal("confirm", 'Run cmd script "' .. name .. '" ?', "exec"); else self:HideModal(); end self:execConsole("dsc " .. file) elseif ext == ".xml" then if not self.modal.visible then return self:ShowModal("confirm", 'Add application "' .. name .. '" ?', "exec"); else self:HideModal(); end self:execConsole("app -a -f " .. file) elseif ext == ".dsr" or ext == ".img" then if not self.modal.visible then return self:ShowModal("confirm", 'Mount romdisk image "' .. name .. '" ?', "exec"); else self:HideModal(); end self:execConsole("romdisk -m " .. file) elseif ext == ".mp1" or ext == ".mp2" or ext == ".mp3" then if not self.modal.visible then return self:ShowModal("confirm", 'Play file "' .. name .. '" ?', "exec"); else self:HideModal(); end if not DS.GetCmdByName("mpg123") then if not self:loadModule("mpg123") then self:showConsole(); return file; end end if os.execute("mpg123 -p -f " .. file) ~= DS.CMD_OK then self:showConsole(); end elseif ext == ".ogg" then if not self.modal.visible then return self:ShowModal("confirm", 'Play file "' .. name .. '" ?', "exec"); else self:HideModal(); end if not DS.GetCmdByName("oggvorbis") then if not self:loadModule("oggvorbis") then self:showConsole(); return file; end end if os.execute("oggvorbis -p -f " .. file) ~= DS.CMD_OK then self:showConsole(); end elseif ext == ".adx" or ext == ".s3m" then local mod = string.sub(ext, -3); if not self.modal.visible then return self:ShowModal("confirm", 'Play file "' .. name .. '" ?', "exec"); else self:HideModal(); end if not DS.GetCmdByName(mod) then if not self:loadModule(mod) then self:showConsole(); return file; end end if os.execute(mod .. " -p -f " .. file) ~= DS.CMD_OK then self:showConsole(); end elseif self:ext_supported(self.ffmpeg.ext, ext) then if not self.modal.visible then return self:ShowModal("confirm", 'Play file "' .. name .. '" ?', "exec"); else self:HideModal(); end if not DS.GetCmdByName("ffplay") then if not self:loadModule("bzip2") or not self:loadModule("mpg123") or not self:loadModule("oggvorbis") or not self:loadModule("ffmpeg") then self:showConsole(); return file; end end if os.execute("ffplay -p -f " .. file) ~= DS.CMD_OK then self:showConsole(); end elseif ext == ".opk" then if not self.modal.visible then return self:ShowModal("confirm", 'Install "' .. name .. '" package?', "exec"); else self:HideModal(); end if not DS.GetCmdByName("opkg") then if not self:loadModule("minilzo") or not self:loadModule("opkg") then self:showConsole(); return file; end end self:execConsole("opkg -i -f " .. file); else local app = DS.GetAppByExtension(ext); if app ~= nil then if not self.modal.visible then return self:ShowModal("confirm", 'Open file in ' .. app.name .. ' app?', "exec"); else self:HideModal(); end self:openApp(app.name, file, 0); -- Unload filemanager? return file; end local mgr = self:getFocusedManager(); local bt = GUI.FileManagerGetItem(mgr.widget, mgr.ent.index); GUI.ButtonSetNormalImage(bt, self.mgr.item.normal); mgr.ent = {name = nil, size = 0, time = 0, attr = 0, index = -1}; end return file; end function FileManager:focusManager(mgr) mgr.focus = true; GUI.PanelSetBackground(mgr.widget, self.mgr.bg.focus); if mgr.id == self.mgr.top.id then self.mgr.bottom.focus = false; GUI.PanelSetBackground(self.mgr.bottom.widget, self.mgr.bg.normal); elseif mgr.id == self.mgr.bottom.id then self.mgr.top.focus = false; GUI.PanelSetBackground(self.mgr.top.widget, self.mgr.bg.normal); end end function FileManager:getFocusedManager() if self.mgr.top.focus then return self.mgr.top; elseif self.mgr.bottom.focus then return self.mgr.bottom; end end function FileManager:getUnfocusedManager() if not self.mgr.top.focus then return self.mgr.top; elseif not self.mgr.bottom.focus then return self.mgr.bottom; end end function FileManager:getFile() local mgr = self:getFocusedManager(); --local path = ""; --if mgr ~= nil then local path = GUI.FileManagerGetPath(mgr.widget); --end return {file = path .. "/" .. mgr.ent.name, name = mgr.ent.name, path = path, attr = mgr.ent.attr, size = mgr.ent.size}; end function FileManagerItemClickTop(ent) FileManager:ItemClick(ent, FileManager.mgr.top); end function FileManagerItemContextClickTop(ent) FileManager:ItemContextClick(ent, FileManager.mgr.top); end function FileManagerItemClickBottom(ent) FileManager:ItemClick(ent, FileManager.mgr.bottom); end function FileManagerItemContextClickBottom(ent) FileManager:ItemContextClick(ent, FileManager.mgr.bottom); end function FileManager:ItemClick(ent, mgr) self:focusManager(mgr); if ent.attr == 0 then if not mgr.ent or (mgr.ent.index ~= ent.index and mgr.ent.name ~= ent.name) then local bt; if mgr.ent.index > -1 then bt = GUI.FileManagerGetItem(mgr.widget, mgr.ent.index); GUI.ButtonSetNormalImage(bt, self.mgr.item.normal); end bt = GUI.FileManagerGetItem(mgr.widget, ent.index); GUI.ButtonSetNormalImage(bt, self.mgr.item.selected); mgr.ent = ent; else self:openFile(); end else GUI.FileManagerChangeDir(mgr.widget, ent.name, ent.size); mgr.ent = {name = nil, size = 0, time = 0, attr = 0, index = -1}; local d = GUI.FileManagerGetPath(mgr.widget); if d ~= "/" then self:tooltip(d); else self:tooltip(nil); end end end function FileManager:ItemContextClick(ent, mgr) self:focusManager(mgr); if ent.attr ~= 0 then if not mgr.ent or (mgr.ent.index ~= ent.index and mgr.ent.name ~= ent.name) then local bt; if mgr.ent.index > -1 then bt = GUI.FileManagerGetItem(mgr.widget, mgr.ent.index); GUI.ButtonSetNormalImage(bt, self.mgr.item.normal); end bt = GUI.FileManagerGetItem(mgr.widget, ent.index); GUI.ButtonSetNormalImage(bt, self.mgr.item.selected); mgr.ent = ent; else GUI.FileManagerChangeDir(mgr.widget, ent.name, ent.size); mgr.ent = {name = nil, size = 0, time = 0, attr = 0, index = -1}; local d = GUI.FileManagerGetPath(mgr.widget); if d ~= "/" then self:tooltip(d); else self:tooltip(nil); end end end end function FileManagerItemMouseover(ent) if ent.attr == 0 then FileManager.prev_title = string.format("File size: %d KB", (ent.size / 1024)); FileManager:tooltip(FileManager.prev_title); else if FileManager.prev_title ~= nil then FileManager.prev_title = nil; FileManager:tooltip(nil); end end end function FileManager:showError(str) print(str .. "\n"); self:ShowModal("alert", str, nil); return false; end function FileManager:tooltip(msg) if msg then GUI.LabelSetText(self.title, msg); else local mgr = self:getFocusedManager(); local path = GUI.FileManagerGetPath(mgr.widget); if path == "/" then GUI.LabelSetText(self.title, self.app.name .. " v" .. self.app.ver); else GUI.LabelSetText(self.title, path); end end end function FileManager:getResource(name, type) local r = DS.listGetItemByName(self.app.resources, name); if r ~= nil then if type == DS.LIST_ITEM_GUI_FONT then return GUI.AnyToFont(r.data); elseif type == DS.LIST_ITEM_GUI_SURFACE then return GUI.AnyToSurface(r.data); else self:showError("FileManager: Uknown resource type - " .. type); return nil; end end self:showError("FileManager: Can't find resource - " .. name); return nil; end function FileManager:getElement(name) local r = DS.listGetItemByName(self.app.elements, name); if r ~= nil then return GUI.AnyToWidget(r.data); end self:showError("FileManager: Can't find element - " .. name); return nil; end function FileManager:Initialize() if self.app == nil then self.app = DS.GetAppById(THIS_APP_ID); if self.app ~= nil then self.font = self:getResource("arial", DS.LIST_ITEM_GUI_FONT); if not self.font then return false; end self.mgr.bg.normal = self:getResource("white-bg", DS.LIST_ITEM_GUI_SURFACE); if not self.mgr.bg.normal then return false; end self.mgr.bg.focus = self:getResource("blue-bg", DS.LIST_ITEM_GUI_SURFACE); if not self.mgr.bg.focus then return false; end self.title = self:getElement("title"); if not self.title then return false; end self.mgr.top.widget = self:getElement("filemgr-top"); if not self.mgr.top.widget then return false; end self.mgr.bottom.widget = self:getElement("filemgr-bottom"); if not self.mgr.bottom.widget then return false; end self.mgr.item.normal = self:getResource("item-normal", DS.LIST_ITEM_GUI_SURFACE); if not self.mgr.item.normal then return false; end self.mgr.item.selected = self:getResource("item-selected", DS.LIST_ITEM_GUI_SURFACE); if not self.mgr.item.selected then return false; end self.modal.widget = self:getElement("modal-win"); if not self.modal.widget then return false; end self.modal.label = self:getElement("modal-label"); if not self.modal.label then return false; end self.modal.input = self:getElement("modal-input"); if not self.modal.input then return false; end self.modal.ok = self:getElement("modal-ok"); if not self.modal.ok then return false; end self.modal.cancel = self:getElement("modal-cancel"); if not self.modal.cancel then return false; end self:HideModal(); self:focusManager(self.mgr.top); self:toolbarModeSwitch(); self:tooltip(nil); end end end function FileManager:Shutdown() self:unloadModules(); end --end <file_sep>/firmware/isoldr/loader/kos/src/controller.c /* This file is part of the libdream Dreamcast function library. Please see libdream.c for further details. controller.c (C)2000 <NAME> */ #include <dc/maple.h> #include <dc/controller.h> /* Ported from KallistiOS (Dreamcast OS) for libdream by <NAME> */ /* get the complete condition structure for controller on port and fill in cond with it, ret -1 on error */ int cont_get_cond(uint8 addr, cont_cond_t *cond) { maple_frame_t frame; uint32 param[1]; param[0] = MAPLE_FUNC_CONTROLLER; do { if (maple_docmd_block(MAPLE_COMMAND_GETCOND, addr, 1, param, &frame) == -1) return -1; } while (frame.cmd == MAPLE_RESPONSE_AGAIN); /* response comes as func, data. */ if (frame.cmd == MAPLE_RESPONSE_DATATRF && (frame.datalen - 1) == sizeof(cont_cond_t) / 4 && *((uint32 *) frame.data) == MAPLE_FUNC_CONTROLLER) { memcpy(cond, frame.data + 4, (frame.datalen - 1) * 4); } else { return -1; } return 0; } <file_sep>/lib/SDL_Console/include/internal.h /* SDL_console: An easy to use drop-down console based on the SDL library Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WHITOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library Generla Public License along with this library; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA <NAME> <EMAIL> */ #ifndef _internal_h_ #define _internal_h_ #include <ds.h> #define PRINT_ERROR ds_printf("DS_ERROR: %s\n", X) Uint32 DT_GetPixel(SDL_Surface *surface, int x, int y); void DT_PutPixel(SDL_Surface *surface, int x, int y, Uint32 pixel); #endif /* _internal_h_ */ <file_sep>/README.md DreamShell ========== The Dreamshell is the operating system for the Sega Dreamcast based on the KallistiOS kernel. It has a dynamic loadable modular system and interface for creating applications with XML UI and both C/C++ and Lua script on. You can see examples in ready-made applications and modules, drivers for various devices, formats and interfaces. Examples for audio and video decoding, compression, packaging, binding, network, emulation, scripts and more. From hardcore low-level assembler to high-level applications. There are also large subproject is the ISO Loader, which contains emulation of BIOS system calls, CDDA playback and VMU, also it can hooking interrupts for various SDKs and more. ## Build ### Setup environment ##### Packages ```console sudo apt-get install -y genisoimage squashfs-tools sudo apt-get install -y libpng-dev libjpeg-dev liblzo2-dev liblua5.2-dev cd /tmp && git clone https://github.com/LuaDist/tolua.git && cd tolua mkdir build && cd ./build cmake ../ && make && sudo make install ``` ##### Code ```console sudo mkdir -p /usr/local/dc/kos sudo chown -R $(id -u):$(id -g) /usr/local/dc cd /usr/local/dc/kos git clone https://github.com/KallistiOS/kos-ports.git git clone https://github.com/KallistiOS/KallistiOS.git kos && cd kos git clone https://github.com/DC-SWAT/DreamShell.git ds git checkout `cat ds/sdk/doc/KallistiOS.txt` cp ds/sdk/toolchain/environ.sh environ.sh ``` ##### Toolchain ```console sudo mkdir -p /opt/toolchains/dc sudo chown -R $(id -u):$(id -g) /opt/toolchains/dc cd /usr/local/dc/kos/kos/utils/dc-chain cp config.mk.testing.sample config.mk make && cd ../../ ``` ##### SDK ```console cd /usr/local/dc/kos/kos source ./environ.sh make && cd ../kos-ports && ./utils/build-all.sh cd ./lib && rm -f libfreetype.a liboggvorbisplay.a libogg.a libvorbis.a && cd ../../kos/ds cd ./sdk/bin/src && make && make install && cd ../../../ ln -nsf `which tolua` sdk/bin/tolua ln -nsf `which mkisofs` sdk/bin/mkisofs ln -nsf `which mksquashfs` sdk/bin/mksquashfs ``` ### Use environment ##### for each new terminal type: ```console cd /usr/local/dc/kos/kos/ds && source ../environ.sh ``` ### Build code ##### Core and libraries ```console make ``` ##### Modules, applications and commands ```console cd ./modules && make && make install && cd ../ cd ./commands && make && make install && cd ../ cd ./applications && make && make install && cd ../ ``` ##### Firmwares ```console cd ./firmware/bootloader && make && make release && cd ../../ cd ./firmware/isoldr && make && make install && cd ../../../ ``` ##### Full build (modules, apps etc) ```console make build ``` ##### Make release package ```console make release ``` ### Running - dc-tool-ip: `make run` - dc-tool-serial: `make run-serial` - lxdream emulator: `make lxdream` - nulldc emulator: `make nulldc` - make cdi image: `make cdi` ## Links - Website: http://www.dc-swat.ru/ - Forum: http://www.dc-swat.ru/forum/ - Donate: http://www.dc-swat.ru/page/donate/ <file_sep>/firmware/isoldr/loader/include/mmu.h /** * DreamShell ISO Loader * SH4 MMU * (c)2015-2016 SWAT <http://www.dc-swat.ru> */ #ifndef __MMU_H__ #define __MMU_H__ int mmu_enabled(void); void mmu_disable(void); void mmu_restore(void); /** * MMU safe memory copy */ void mmu_memcpy(void *dest, const void *src, size_t count); #endif <file_sep>/firmware/aica/codec/play_wav.c /* Copyright (C) 2006 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <assert.h> #include <stdio.h> #include "AT91SAM7S64.h" #include "play_wav.h" #include "dac.h" #include "ff.h" #include "profile.h" void wav_init(unsigned char *buffer, unsigned int buffer_size) { } int wav_process(FIL *wavfile) { int writeable_buffer; WORD bytes_read; //puts("reading"); if ((writeable_buffer = dac_get_writeable_buffer()) != -1) { PROFILE_START("f_read"); f_read(wavfile, (BYTE *)dac_buffer[writeable_buffer], DAC_BUFFER_MAX_SIZE*2, &bytes_read); PROFILE_END(); if (bytes_read != DAC_BUFFER_MAX_SIZE*2) { dac_buffer_size[writeable_buffer] = 0; return -1; } else { dac_buffer_size[writeable_buffer] = DAC_BUFFER_MAX_SIZE; } } dac_fill_dma(); return 0; } <file_sep>/applications/iso_loader/modules/module.c /* DreamShell ##version## module.c - ISO Loader app module Copyright (C) 2011 Superdefault Copyright (C) 2011-2023 SWAT */ #include <ds.h> #include <isoldr.h> #include <vmu.h> #include <stdbool.h> #include <kos/md5.h> #include "app_utils.h" DEFAULT_MODULE_EXPORTS(app_iso_loader); #define SCREENSHOT_HOTKEY (CONT_START | CONT_A | CONT_B) static struct { App_t *app; isoldr_info_t *isoldr; char filename[NAME_MAX]; uint8 md5[16]; uint8 boot_sector[2048]; int image_type; int sector_size; bool have_args; GUI_Widget *pages; GUI_Widget *filebrowser; int current_item; int current_item_dir; GUI_Surface *item_norm; GUI_Surface *item_focus; GUI_Surface *item_selected; GUI_Widget *extensions; GUI_Widget *link; GUI_Widget *settings; GUI_Widget *games; GUI_Widget *btn_run; GUI_Widget *run_pane; GUI_Widget *preset; GUI_Widget *dma; GUI_Widget *cdda; GUI_Widget *cdda_mode[5]; GUI_Widget *irq; GUI_Widget *low; GUI_Widget *heap[20]; GUI_Widget *heap_memory_text; GUI_Widget *fastboot; GUI_Widget *async[10]; GUI_Widget *async_label; GUI_Widget *vmu; GUI_Widget *vmu_number; GUI_Widget *vmu_create; GUI_Widget *screenshot; GUI_Widget *device; GUI_Widget *os_chk[4]; GUI_Widget *options_switch[4]; GUI_Widget *boot_mode_chk[3]; GUI_Widget *memory_chk[16]; GUI_Widget *memory_text; int current_dev; GUI_Widget *btn_dev[APP_DEVICE_COUNT]; GUI_Surface *btn_dev_norm[APP_DEVICE_COUNT]; GUI_Surface *btn_dev_over[APP_DEVICE_COUNT]; GUI_Surface *default_cover; GUI_Surface *current_cover; GUI_Widget *cover_widget; GUI_Widget *title; GUI_Widget *options_panel; GUI_Widget *icosizebtn[5]; GUI_Widget *wlnkico; GUI_Surface *slnkico; GUI_Surface *stdico; GUI_Widget *linktext; GUI_Widget *btn_hidetext; GUI_Widget *save_link_btn; GUI_Widget *save_link_txt; GUI_Widget *rotate180; GUI_Widget *wpa[2]; GUI_Widget *wpv[2]; uint32_t pa[2]; uint32_t pv[2]; } self; void isoLoader_DefaultPreset(); int isoLoader_LoadPreset(); int isoLoader_SavePreset(); void isoLoader_ResizeUI(); void isoLoader_toggleMemory(GUI_Widget *widget); void isoLoader_toggleBootMode(GUI_Widget *widget); void isoLoader_toggleIconSize(GUI_Widget *widget); static void setico(int size, int force); static int canUseTrueAsyncDMA(void) { return (self.sector_size == 2048 && (self.current_dev == APP_DEVICE_IDE || self.current_dev == APP_DEVICE_CD) && (self.image_type == ISOFS_IMAGE_TYPE_ISO || self.image_type == ISOFS_IMAGE_TYPE_GDI)); } static char *relativeFilename(char *filename) { static char filepath[NAME_MAX]; char path[NAME_MAX]; int len; if (strchr(self.filename, '/')) { len = strlen(strchr(self.filename, '/')); } else { len = strlen(self.filename); } memset(filepath, 0, sizeof(filepath)); memset(path, 0, sizeof(path)); strncpy(path, self.filename, strlen(self.filename) - len); snprintf(filepath, NAME_MAX, "%s/%s/%s", GUI_FileManagerGetPath(self.filebrowser), path, filename); return filepath; } void isoLoader_Rotate_Image(GUI_Widget *widget) { (void)widget; setico(GUI_SurfaceGetWidth(self.slnkico), 1); } void isoLoader_ShowPage(GUI_Widget *widget) { GUI_WidgetSetEnabled(self.link, 1); GUI_WidgetSetEnabled(self.extensions, 1); GUI_WidgetSetEnabled(self.settings, 1); GUI_WidgetSetEnabled(self.games, 1); if (widget == self.games) { GUI_CardStackShowIndex(self.pages, 0); GUI_WidgetSetEnabled(self.games, 0); } else if(widget == self.settings) { GUI_CardStackShowIndex(self.pages, 1); GUI_WidgetSetEnabled(self.settings, 0); } else if(widget == self.extensions) { GUI_CardStackShowIndex(self.pages, 2); GUI_WidgetSetEnabled(self.extensions, 0); } else if(widget == self.link) { GUI_CardStackShowIndex(self.pages, 3); GUI_WidgetSetEnabled(self.link, 0); } GUI_WidgetMarkChanged(self.run_pane); } void isoLoader_ShowSettings(GUI_Widget *widget) { ScreenFadeOut(); thd_sleep(200); isoLoader_ShowPage(widget); ScreenFadeIn(); } void isoLoader_ShowExtensions(GUI_Widget *widget) { ScreenFadeOut(); thd_sleep(200); isoLoader_ShowPage(widget); ScreenFadeIn(); } void isoLoader_ShowGames(GUI_Widget *widget) { ScreenFadeOut(); thd_sleep(200); isoLoader_SavePreset(); isoLoader_ShowPage(widget); ScreenFadeIn(); } static void check_link_file(void) { char save_file[NAME_MAX]; snprintf(save_file, NAME_MAX, "%s/apps/main/scripts/%s.dsc", getenv("PATH"), GUI_TextEntryGetText(self.linktext)); if(FileExists(save_file)) { GUI_LabelSetText(self.save_link_txt, "rewrite shortcut"); } else { GUI_LabelSetText(self.save_link_txt, "create shortcut"); } GUI_WidgetMarkChanged(self.save_link_btn); } void isoLoader_ShowLink(GUI_Widget *widget) { ScreenFadeOut(); thd_sleep(200); GUI_WidgetSetState(self.rotate180, 0); GUI_WidgetSetState(self.btn_hidetext, 0); isoLoader_toggleIconSize(self.icosizebtn[0]); setico(48, 1); ipbin_meta_t *ipbin = (ipbin_meta_t *)self.boot_sector; ipbin->title[sizeof(ipbin->title)-1] = '\0'; GUI_TextEntrySetText(self.linktext, trim_spaces2(ipbin->title)); check_link_file(); isoLoader_ShowPage(widget); ScreenFadeIn(); } /* Set the active volume in the menu */ static void highliteDevice() { int dev = getDeviceType(GUI_FileManagerGetPath(self.filebrowser)); if(dev > -1 && dev != self.current_dev) { if(self.current_dev > -1) { GUI_ButtonSetNormalImage(self.btn_dev[self.current_dev], self.btn_dev_norm[self.current_dev]); } GUI_ButtonSetNormalImage(self.btn_dev[dev], self.btn_dev_over[dev]); self.current_dev = dev; UpdateActiveMouseCursor(); } } static void get_md5_hash(const char *mountpoint) { file_t fd; fd = fs_iso_first_file(mountpoint); if(fd != FILEHND_INVALID) { if(fs_ioctl(fd, ISOFS_IOCTL_GET_BOOT_SECTOR_DATA, (int) self.boot_sector) < 0) { memset(self.md5, 0, sizeof(self.md5)); memset(self.boot_sector, 0, sizeof(self.boot_sector)); } else { kos_md5(self.boot_sector, sizeof(self.boot_sector), self.md5); } /* Also get image type and sector size */ if(fs_ioctl(fd, ISOFS_IOCTL_GET_IMAGE_TYPE, (int) &self.image_type) < 0) { ds_printf("%s: Can't get image type\n", lib_get_name()); } if(fs_ioctl(fd, ISOFS_IOCTL_GET_DATA_TRACK_SECTOR_SIZE, (int) &self.sector_size) < 0) { ds_printf("%s: Can't get sector size\n", lib_get_name()); } fs_close(fd); } } /* Try to get cover image from ISO */ static void showCover() { GUI_Surface *s; char path[NAME_MAX]; char noext[128]; ipbin_meta_t *ipbin; char use_cover = 0; memset(noext, 0, sizeof(noext)); strncpy(noext, (!strchr(self.filename, '/')) ? self.filename : (strchr(self.filename, '/')+1), sizeof(noext)); strcpy(noext, strtok(noext, ".")); snprintf(path, NAME_MAX, "%s/apps/iso_loader/covers/%s.png", getenv("PATH"), noext); if (FileExists(path)) { use_cover = 1; } else { snprintf(path, NAME_MAX, "%s/apps/iso_loader/covers/%s.jpg", getenv("PATH"), noext); if (FileExists(path)) { use_cover = 1; } } /* Check for jpeg cover */ if(use_cover) { s = GUI_SurfaceLoad(path); snprintf(path, NAME_MAX, "%s/%s", GUI_FileManagerGetPath(self.filebrowser), self.filename); if(!fs_iso_mount("/isocover", path)) { get_md5_hash("/isocover"); fs_iso_unmount("/isocover"); ipbin = (ipbin_meta_t *)self.boot_sector; trim_spaces(ipbin->title, noext, sizeof(ipbin->title)); } GUI_LabelSetText(self.title, noext); if(s != NULL) { GUI_PanelSetBackground(self.cover_widget, s); GUI_ObjectDecRef((GUI_Object *) s); self.current_cover = s; } } else { snprintf(path, NAME_MAX, "%s/%s", GUI_FileManagerGetPath(self.filebrowser), self.filename); /* Try to mount ISO and get 0GDTEXT.PVR */ if(!fs_iso_mount("/isocover", path)) { get_md5_hash("/isocover"); ipbin_meta_t *ipbin = (ipbin_meta_t *)self.boot_sector; trim_spaces(ipbin->title, noext, sizeof(ipbin->title)); if(FileExists("/isocover/0GDTEX.PVR")) { s = GUI_SurfaceLoad("/isocover/0GDTEX.PVR"); fs_iso_unmount("/isocover"); GUI_LabelSetText(self.title, noext); if(s != NULL) { GUI_PanelSetBackground(self.cover_widget, s); GUI_ObjectDecRef((GUI_Object *) s); self.current_cover = s; } else { goto check_default; } } else { fs_iso_unmount("/isocover"); GUI_LabelSetText(self.title, noext); goto check_default; } } else { goto check_default; } } vmu_draw_string(noext); return; check_default: if(self.current_cover != self.default_cover) { GUI_PanelSetBackground(self.cover_widget, self.default_cover); self.current_cover = self.default_cover; } vmu_draw_string(noext); } void isoLoader_MakeShortcut(GUI_Widget *widget) { (void)widget; FILE *fd; char *env = getenv("PATH"); char save_file[NAME_MAX]; char cmd[512]; const char *tmpval; int i; snprintf(save_file, NAME_MAX, "%s/apps/main/scripts/%s.dsc", env, GUI_TextEntryGetText(self.linktext)); fd = fopen(save_file, "w"); if(!fd) { ds_printf("DS_ERROR: Can't save shortcut\n"); return; } fprintf(fd, "module -o -f %s/modules/minilzo.klf\n", env); fprintf(fd, "module -o -f %s/modules/isofs.klf\n", env); fprintf(fd, "module -o -f %s/modules/isoldr.klf\n", env); strcpy(cmd, "isoldr"); strcat(cmd, GUI_WidgetGetState(self.fastboot) ? " -s 1":" -i" ); if(GUI_WidgetGetState(self.dma)) { strcat(cmd, " -a"); } if(GUI_WidgetGetState(self.irq)) { strcat(cmd, " -q"); } if(GUI_WidgetGetState(self.low)) { strcat(cmd, " -l"); } for(i = 0; i < sizeof(self.async) >> 2; i++) { if(GUI_WidgetGetState(self.async[i])) { if(i) { char async[8]; int val = atoi(GUI_LabelGetText(GUI_ButtonGetCaption(self.async[i]))); snprintf(async, sizeof(async), " -e %d", val); strcat(cmd, async); } break; } } tmpval = GUI_TextEntryGetText(self.device); if(strncmp(tmpval, "auto", 4) != 0) { strcat(cmd, " -d "); strcat(cmd, tmpval); } for(i = 0; self.memory_chk[i]; i++) { if(GUI_WidgetGetState(self.memory_chk[i])) { tmpval = GUI_ObjectGetName((GUI_Object *)self.memory_chk[i]); if(strlen(tmpval) < 8) { char text[24]; memset(text, 0, sizeof(text)); strncpy(text, tmpval, 10); tmpval = strncat(text, GUI_TextEntryGetText(self.memory_text), 10); } strcat(cmd, " -x "); strcat(cmd, tmpval); break; } } char fpath[NAME_MAX]; sprintf(fpath, "%s/%s", GUI_FileManagerGetPath(self.filebrowser), self.filename); strcat(cmd, " -f "); strcat(cmd, fix_spaces(fpath)); for(i = 0; i < sizeof(self.boot_mode_chk) >> 2; i++) { if(i && GUI_WidgetGetState(self.boot_mode_chk[i])) { char boot_mode[3]; sprintf(boot_mode, "%d", i); strcat(cmd, " -j "); strcat(cmd, boot_mode); break; } } for(i = 0; i < sizeof(self.os_chk) >> 2; i++) { if(i && GUI_WidgetGetState(self.os_chk[i])) { char os[3]; sprintf(os, "%d", i); strcat(cmd, " -o "); strcat(cmd, os); break; } } char patchstr[18]; for(i = 0; i < sizeof(self.pa) >> 2; ++i) { if(self.pa[i] & 0xffffff) { sprintf(patchstr," --pa%d 0x%s", i + 1, GUI_TextEntryGetText(self.wpa[i])); strcat(cmd, patchstr); sprintf(patchstr," --pv%d 0x%s", i + 1, GUI_TextEntryGetText(self.wpv[i])); strcat(cmd, patchstr); } } for(i = 0; i < sizeof(self.cdda_mode) >> 2; i++) { if(i && GUI_WidgetGetState(self.cdda_mode[i])) { char cdda_mode[3]; sprintf(cdda_mode, "%d", i); strcat(cmd, " -g "); strcat(cmd, cdda_mode); break; } } for(int i = 0; i < sizeof(self.heap) >> 2; i++) { if(self.heap[i] && GUI_WidgetGetState(self.heap[i])) { if (i <= HEAP_MODE_MAPLE) { char mode[12]; sprintf(mode, " -h %d", i); strcat(cmd, mode); break; } else { char *addr = (char* )GUI_ObjectGetName((GUI_Object *)self.heap[i]); if(strlen(addr) < 8) { char text[24]; memset(text, 0, sizeof(text)); strncpy(text, addr, 10); addr = strncat(text, GUI_TextEntryGetText(self.heap_memory_text), 10); } strcat(cmd, " -h "); strcat(cmd, addr); } break; } } if(GUI_WidgetGetState(self.vmu)) { char number[12]; sprintf(number, " -v %d", atoi(GUI_TextEntryGetText(self.vmu_number))); strcat(cmd, number); } if(GUI_WidgetGetState(self.screenshot)) { char hotkey[24]; sprintf(hotkey, " -k 0x%lx", (uint32)SCREENSHOT_HOTKEY); strcat(cmd, hotkey); } fprintf(fd, "%s\n", cmd); fprintf(fd, "console --show\n"); fclose(fd); snprintf(save_file, NAME_MAX, "%s/apps/main/images/%s.png", env, GUI_TextEntryGetText(self.linktext)); GUI_SurfaceSavePNG(self.slnkico, save_file); isoLoader_ShowGames(self.settings); } static void setico(int size, int force) { GUI_Surface *image, *s; int cursize = GUI_SurfaceGetWidth(self.slnkico); if(size == cursize && !force) { return; } if(self.current_cover == self.default_cover) { s = self.stdico; } else { s = self.current_cover; } SDL_Surface *sdls = GUI_SurfaceGet(s); if(GUI_WidgetGetState(self.rotate180)) { sdls = rotateSurface90Degrees(sdls, 2); } double scaling = (double) size / (double) GUI_SurfaceGetWidth(s); image = GUI_SurfaceFrom("ico-surface", zoomSurface(sdls, scaling, scaling, 1)); GUI_PictureSetImage(self.wlnkico, image); if(self.slnkico) { GUI_ObjectDecRef((GUI_Object *) self.slnkico); } self.slnkico = image; GUI_WidgetMarkChanged(self.pages); GUI_WidgetMarkChanged(self.run_pane); } void isoLoader_toggleIconSize(GUI_Widget *widget) { int i, size = 48; for(i=0; i<5; i++) { GUI_WidgetSetState(self.icosizebtn[i], 0); } GUI_WidgetSetState(widget, 1); char *name = (char *) GUI_ObjectGetName((GUI_Object *)widget); switch(name[1]) { case '2': size = 128; break; case '4': size = 64; break; case '5': size = 256; break; case '6': size = 96; break; case '8': default: size = 48; } setico(size, 0); } void isoLoader_toggleLinkName(GUI_Widget *widget) { char curtext[33]; snprintf(curtext, 33, "%s", GUI_TextEntryGetText(widget)); int state = !(curtext[0] != '_'); if(strlen(curtext) < 3) { ipbin_meta_t *ipbin = (ipbin_meta_t *)self.boot_sector; ipbin->title[sizeof(ipbin->title)-1] = '\0'; GUI_TextEntrySetText(self.linktext, trim_spaces2(ipbin->title)); } GUI_WidgetSetState(self.btn_hidetext, state); check_link_file(); } void isoLoader_toggleHideName(GUI_Widget *widget) { int state = GUI_WidgetGetState(widget); char *curtext = (char *)GUI_TextEntryGetText(self.linktext); char text[NAME_MAX]; if(state && curtext[0] != '_') { snprintf(text, NAME_MAX, "_%s", curtext); GUI_TextEntrySetText(self.linktext, text); } else if(!state && curtext[0] == '_') { snprintf(text, NAME_MAX, "%s", &curtext[1]); GUI_TextEntrySetText(self.linktext, text); } check_link_file(); } void isoLoader_toggleOptions(GUI_Widget *widget) { for(int i = 0; i < sizeof(self.options_switch) >> 2; i++) { if(widget != self.options_switch[i]) { GUI_WidgetSetState(self.options_switch[i], 0); } else if(GUI_WidgetGetState(widget)) { GUI_CardStackShowIndex(self.options_panel, i); } else { GUI_WidgetSetState(widget, 1); } } GUI_WidgetMarkChanged(self.run_pane); } void isoLoader_togglePatchAddr(GUI_Widget *widget) { const char *name = GUI_ObjectGetName((GUI_Object *)widget); const char *text = GUI_TextEntryGetText(widget); uint32_t temp = strtoul(text, NULL, 16); if( (strlen(text) != 8) || (name[1] == 'a' && (!(temp & 0xffffff) || ((temp >> 24 != 0x0c) && (temp >> 24 != 0x8c) && (temp >> 24 != 0xac)))) || (name[1] == 'v' && !temp)) { GUI_TextEntrySetText(widget, (name[1] == 'a') ? "0c000000" : "00000000"); } else { switch(name[1]) { case 'a': self.pa[name[2]-'1'] = strtoul(text, NULL, 16); break; case 'v': self.pv[name[2]-'1'] = strtoul(text, NULL, 16); break; } } } /* Switch to the selected volume */ void isoLoader_SwitchVolume(void *dir) { GUI_FileManagerSetPath(self.filebrowser, (char *)dir); highliteDevice(); } void isoLoader_toggleOS(GUI_Widget *widget) { for(int i = 0; i < sizeof(self.os_chk) >> 2; i++) { if(widget != self.os_chk[i]) { GUI_WidgetSetState(self.os_chk[i], 0); } } } void isoLoader_toggleAsync(GUI_Widget *widget) { for(int i = 0; i < sizeof(self.async) >> 2; i++) { if(widget != self.async[i]) { GUI_WidgetSetState(self.async[i], 0); } else { GUI_WidgetSetState(self.async[i], 1); } } } void isoLoader_toggleDMA(GUI_Widget *widget) { if (GUI_WidgetGetState(widget) && canUseTrueAsyncDMA()) { if (!strncmp(GUI_LabelGetText(self.async_label), "none", 4)) { GUI_LabelSetText(self.async_label, "true"); } if (!GUI_WidgetGetState(self.async[0])) { isoLoader_toggleAsync(self.async[0]); } else { GUI_WidgetMarkChanged(self.async[0]); } } else { if (!strncmp(GUI_LabelGetText(self.async_label), "true", 4)) { GUI_LabelSetText(self.async_label, "none"); } if (GUI_WidgetGetState(self.async[0])) { isoLoader_toggleAsync(self.async[8]); } else { GUI_WidgetMarkChanged(self.async[0]); } } } void isoLoader_toggleCDDA(GUI_Widget *widget) { for(int i = 0; i < sizeof(self.cdda_mode) >> 2; i++) { if(widget != self.cdda_mode[i]) { GUI_WidgetSetState(self.cdda_mode[i], 0); } else { GUI_WidgetSetState(widget, 1); } } if (self.cdda == widget) { if (GUI_WidgetGetState(widget)) { isoLoader_toggleCDDA(self.cdda_mode[CDDA_MODE_DMA_TMU2]); } else { isoLoader_toggleCDDA(self.cdda_mode[CDDA_MODE_DISABLED]); } } else if(self.cdda_mode[CDDA_MODE_DISABLED] == widget) { GUI_WidgetSetState(self.cdda, GUI_WidgetGetState(widget) ? 0 : 1); } else if (!GUI_WidgetGetState(self.cdda)) { GUI_WidgetSetState(self.cdda, 1); } } void isoLoader_toggleHeap(GUI_Widget *widget) { for(int i = 0; i < sizeof(self.heap) >> 2; i++) { if (!self.heap[i]) { break; } if(widget != self.heap[i]) { GUI_WidgetSetState(self.heap[i], 0); } else { GUI_WidgetSetState(widget, 1); } } } void isoLoader_toggleMemory(GUI_Widget *widget) { int i; for(i = 0; self.memory_chk[i]; i++) { if(widget != self.memory_chk[i]) { GUI_WidgetSetState(self.memory_chk[i], 0); } } if(!strncmp(GUI_ObjectGetName((GUI_Object *) widget), "memory-text", 12)) { GUI_WidgetSetState(self.memory_chk[i-1], 1); } if(GUI_WidgetGetState(self.memory_chk[2]) && GUI_WidgetGetState(self.boot_mode_chk[BOOT_MODE_IPBIN])) { GUI_WidgetSetState(self.boot_mode_chk[BOOT_MODE_IPBIN], 0); GUI_WidgetSetState(self.boot_mode_chk[BOOT_MODE_IPBIN_TRUNC], 1); } else if(GUI_WidgetGetState(self.memory_chk[3]) && (GUI_WidgetGetState(self.boot_mode_chk[BOOT_MODE_IPBIN]) || GUI_WidgetGetState(self.boot_mode_chk[BOOT_MODE_IPBIN_TRUNC]))) { GUI_WidgetSetState(self.boot_mode_chk[BOOT_MODE_IPBIN], 0); GUI_WidgetSetState(self.boot_mode_chk[BOOT_MODE_IPBIN_TRUNC], 0); GUI_WidgetSetState(self.boot_mode_chk[BOOT_MODE_DIRECT], 1); } } void isoLoader_toggleBootMode(GUI_Widget *widget) { for(int i = 0; i < sizeof(self.boot_mode_chk) >> 2; i++) { if(widget != self.boot_mode_chk[i]) { GUI_WidgetSetState(self.boot_mode_chk[i], 0); } } } void isoLoader_toggleExtension(GUI_Widget *widget) { if (GUI_WidgetGetState(widget)) { GUI_WidgetSetState(self.irq, 1); if (widget == self.vmu_create) { GUI_WidgetSetState(self.vmu, 1); } } } void isoLoader_Run(GUI_Widget *widget) { char filepath[NAME_MAX]; const char *tmpval; uint32 addr = ISOLDR_DEFAULT_ADDR_LOW; (void)widget; memset(filepath, 0, NAME_MAX); snprintf(filepath, NAME_MAX, "%s/%s", GUI_FileManagerGetPath(self.filebrowser), self.filename); ScreenFadeOut(); thd_sleep(400); if(GUI_CardStackGetIndex(self.pages) != 0) { isoLoader_SavePreset(); } self.isoldr = isoldr_get_info(filepath, 0); if(self.isoldr == NULL) { ShowConsole(); ScreenFadeIn(); return; } for(int i = 0; i < sizeof(self.async) >> 2; ++i) { if (GUI_WidgetGetState(self.async[i])) { if (i) { self.isoldr->emu_async = atoi(GUI_LabelGetText(GUI_ButtonGetCaption(self.async[i]))); } else { self.isoldr->emu_async = 0; } break; } } if(GUI_WidgetGetState(self.irq)) { self.isoldr->use_irq = 1; } if(GUI_WidgetGetState(self.low)) { self.isoldr->syscalls = 1; } for(int i = 0; i < sizeof(self.cdda_mode) >> 2; i++) { if(GUI_WidgetGetState(self.cdda_mode[i])) { self.isoldr->emu_cdda = i; break; } } for(int i = 0; i < sizeof(self.heap) >> 2; i++) { if(GUI_WidgetGetState(self.heap[i])) { if (i <= HEAP_MODE_MAPLE) { self.isoldr->heap = i; } else { tmpval = GUI_ObjectGetName((GUI_Object *)self.heap[i]); if(strlen(tmpval) < 8) { char text[24]; memset(text, 0, sizeof(text)); strncpy(text, tmpval, 10); tmpval = strncat(text, GUI_TextEntryGetText(self.heap_memory_text), 10); } self.isoldr->heap = strtoul(tmpval, NULL, 16); } break; } } if(GUI_WidgetGetState(self.dma)) { self.isoldr->use_dma = 1; } if(GUI_WidgetGetState(self.fastboot)) { self.isoldr->fast_boot = 1; } tmpval = GUI_TextEntryGetText(self.device); if(strncmp(tmpval, "auto", 4) != 0) { strncpy(self.isoldr->fs_dev, tmpval, sizeof(self.isoldr->fs_dev)); } if(self.current_cover && self.current_cover != self.default_cover && !self.isoldr->fast_boot) { SDL_Surface *surf = GUI_SurfaceGet(self.current_cover); if(surf) { self.isoldr->gdtex = (uint32)surf->pixels; } } for(int i = 0; i < sizeof(self.os_chk) >> 2; i++) { if(i && GUI_WidgetGetState(self.os_chk[i])) { self.isoldr->exec.type = i; break; } } for(int i = 0; i < sizeof(self.boot_mode_chk) >> 2; i++) { if(i && GUI_WidgetGetState(self.boot_mode_chk[i])) { self.isoldr->boot_mode = i; break; } } for(int i = 0; self.memory_chk[i]; i++) { if(GUI_WidgetGetState(self.memory_chk[i])) { tmpval = GUI_ObjectGetName((GUI_Object *)self.memory_chk[i]); if(strlen(tmpval) < 8) { char text[24]; memset(text, 0, sizeof(text)); strncpy(text, tmpval, 10); tmpval = strncat(text, GUI_TextEntryGetText(self.memory_text), 10); } addr = strtoul(tmpval, NULL, 16); break; } } for(int i = 0; i < sizeof(self.isoldr->patch_addr) >> 2; ++i) { if(self.pa[i] & 0xffffff) { self.isoldr->patch_addr[i] = self.pa[i]; self.isoldr->patch_value[i] = self.pv[i]; } } if(GUI_WidgetGetState(self.vmu)) { self.isoldr->emu_vmu = atoi(GUI_TextEntryGetText(self.vmu_number)); } if(GUI_WidgetGetState(self.vmu_create)) { snprintf(filepath, sizeof(filepath), "%s/apps/%s/resources/empty_vmu.vmd", getenv("PATH"), lib_get_name() + 4); char fn[32]; snprintf(fn, sizeof(fn), "vmu%03ld.vmd", self.isoldr->emu_vmu); CopyFile(filepath, relativeFilename(fn), 0); } if(GUI_WidgetGetState(self.screenshot)) { self.isoldr->scr_hotkey = SCREENSHOT_HOTKEY; } isoldr_exec(self.isoldr, addr); /* If we there, then something wrong... */ ShowConsole(); ScreenFadeIn(); free(self.isoldr); } static void selectFile(char *name, int index) { GUI_Widget *w; GUI_WidgetSetEnabled(self.btn_run, 1); w = GUI_FileManagerGetItem(self.filebrowser, index); GUI_ButtonSetNormalImage(w, self.item_selected); GUI_ButtonSetHighlightImage(w, self.item_selected); GUI_ButtonSetPressedImage(w, self.item_selected); if(self.current_item > -1) { w = GUI_FileManagerGetItem(self.filebrowser, self.current_item); GUI_ButtonSetNormalImage(w, self.item_norm); GUI_ButtonSetHighlightImage(w, self.item_focus); GUI_ButtonSetPressedImage(w, self.item_focus); } self.current_item = index; strncpy(self.filename, name, NAME_MAX); highliteDevice(); showCover(); isoLoader_LoadPreset(); if (GUI_WidgetGetFlags(self.settings) & WIDGET_DISABLED) { GUI_WidgetSetEnabled(self.settings, 1); GUI_WidgetSetEnabled(self.link, 1); GUI_WidgetSetEnabled(self.extensions, 1); } } static void changeDir(dirent_t *ent) { self.current_item = -1; self.current_item_dir = -1; memset(self.filename, 0, NAME_MAX); GUI_FileManagerChangeDir(self.filebrowser, ent->name, ent->size); highliteDevice(); GUI_WidgetSetEnabled(self.btn_run, 0); } void isoLoader_ItemClick(dirent_fm_t *fm_ent) { if(!fm_ent) { return; } dirent_t *ent = &fm_ent->ent; if(ent->attr == O_DIR && self.current_item_dir != fm_ent->index) { char filepath[NAME_MAX]; memset(filepath, 0, NAME_MAX); snprintf(filepath, NAME_MAX, "%s/%s", GUI_FileManagerGetPath(self.filebrowser), ent->name); file_t fd = fs_open(filepath, O_RDONLY | O_DIR); if(fd != FILEHND_INVALID) { int total_count = 0; int dir_count = 0; dirent_t *dent; while ((dent = fs_readdir(fd)) != NULL) { if(++total_count > 100) { break; } if(dent->name[0] == '.') { continue; } if(dent->attr == O_DIR && ++dir_count > 1) { break; } int len = strlen(dent->name); if(len > 4 && strncasecmp(dent->name + len - 4, ".gdi", 4) == 0) { fs_close(fd); memset(filepath, 0, NAME_MAX); snprintf(filepath, NAME_MAX, "%s/%s", ent->name, dent->name); selectFile(filepath, fm_ent->index); self.current_item_dir = fm_ent->index; return; } } fs_close(fd); } changeDir(ent); } else if(self.current_item == fm_ent->index) { isoLoader_Run(NULL); } else if(IsFileSupportedByApp(self.app, ent->name)) { selectFile(ent->name, fm_ent->index); } } void isoLoader_ItemContextClick(dirent_fm_t *fm_ent) { if (self.current_item != fm_ent->index) { dirent_t *ent = &fm_ent->ent; if(ent->attr == O_DIR) { changeDir(ent); } else { isoLoader_ItemClick(fm_ent); } } else { isoLoader_ShowSettings(self.settings); } } void isoLoader_DefaultPreset() { if(canUseTrueAsyncDMA() && !GUI_WidgetGetState(self.dma)) { GUI_WidgetSetState(self.dma, 1); isoLoader_toggleDMA(self.dma); } else if(!canUseTrueAsyncDMA() && GUI_WidgetGetState(self.dma)) { GUI_WidgetSetState(self.dma, 0); isoLoader_toggleDMA(self.dma); isoLoader_toggleAsync(self.async[8]); } GUI_TextEntrySetText(self.device, "auto"); GUI_WidgetSetState(self.preset, 0); GUI_WidgetSetState(self.cdda, 0); isoLoader_toggleCDDA(self.cdda); GUI_WidgetSetState(self.irq, 0); GUI_WidgetSetState(self.low, 0); GUI_WidgetSetState(self.vmu, 0); GUI_WidgetSetState(self.screenshot, 0); GUI_WidgetSetState(self.os_chk[BIN_TYPE_AUTO], 1); isoLoader_toggleOS(self.os_chk[BIN_TYPE_AUTO]); GUI_WidgetSetState(self.memory_chk[0], 1); isoLoader_toggleMemory(self.memory_chk[0]); GUI_WidgetSetState(self.boot_mode_chk[BOOT_MODE_DIRECT], 1); isoLoader_toggleBootMode(self.boot_mode_chk[BOOT_MODE_DIRECT]); /* * Enable CDDA if present on IDE/GD */ if (self.filename[0] != 0 && canUseTrueAsyncDMA()) { int have_cdda = 0; char filepath[NAME_MAX]; char path[NAME_MAX]; int len = 0; const int min_size = 5 * 1024 * 1024; if (strchr(self.filename, '/')) { len = strlen(strchr(self.filename, '/')); } else { len = strlen(self.filename); } memset(filepath, 0, sizeof(filepath)); memset(path, 0, sizeof(path)); strncpy(path, self.filename, strlen(self.filename) - len); snprintf(filepath, NAME_MAX, "%s/%s/track05.raw", GUI_FileManagerGetPath(self.filebrowser), path); if (FileSize(filepath) > min_size) { have_cdda = 1; } else { int len = strlen(filepath); filepath[len - 3] = 'w'; filepath[len - 1] = 'v'; if (FileSize(filepath) > min_size) { have_cdda = 1; } } if (have_cdda) { GUI_WidgetSetState(self.irq, 1); GUI_WidgetSetState(self.cdda, 1); isoLoader_toggleCDDA(self.cdda); } } } int isoLoader_SavePreset() { if (!GUI_WidgetGetState(self.preset)) { return 0; } char *filename, *memory = NULL; file_t fd; ipbin_meta_t *ipbin = (ipbin_meta_t *)self.boot_sector; char text[32]; char result[1024]; int async = 0, type = 0, mode = 0; uint32 heap = HEAP_MODE_AUTO; int cdda_mode = CDDA_MODE_DISABLED; if (!self.filename[0]) { return 0; } filename = makePresetFilename(GUI_FileManagerGetPath(self.filebrowser), self.md5); fd = fs_open(filename, O_CREAT | O_TRUNC | O_WRONLY); if(fd == FILEHND_INVALID) { return -1; } for(int i = 1; i < sizeof(self.async) >> 2; i++) { if(GUI_WidgetGetState(self.async[i])) { async = atoi(GUI_LabelGetText(GUI_ButtonGetCaption(self.async[i]))); break; } } for(int i = 0; i < sizeof(self.os_chk) >> 2; i++) { if(GUI_WidgetGetState(self.os_chk[i])) { type = i; break; } } for(int i = 0; i < sizeof(self.boot_mode_chk) >> 2; i++) { if(GUI_WidgetGetState(self.boot_mode_chk[i])) { mode = i; break; } } for(int i = 0; i < sizeof(self.heap) >> 2; i++) { if(self.heap[i] && GUI_WidgetGetState(self.heap[i])) { if (i <= HEAP_MODE_MAPLE) { heap = i; } else { char *tmpval = (char* )GUI_ObjectGetName((GUI_Object *)self.heap[i]); if(strlen(tmpval) < 8) { char text[24]; memset(text, 0, sizeof(text)); strncpy(text, tmpval, 10); tmpval = strncat(text, GUI_TextEntryGetText(self.heap_memory_text), 10); } heap = strtoul(tmpval, NULL, 16); } break; } } for(int i = 0; i < sizeof(self.cdda_mode) >> 2; i++) { if(GUI_WidgetGetState(self.cdda_mode[i])) { cdda_mode = i; break; } } for(int i = 0; self.memory_chk[i]; i++) { if(GUI_WidgetGetState(self.memory_chk[i])) { memory = (char* )GUI_ObjectGetName((GUI_Object *)self.memory_chk[i]); if(strlen(memory) < 8) { memset(text, 0, sizeof(text)); strncpy(text, memory, 10); memory = strncat(text, GUI_TextEntryGetText(self.memory_text), 10); } break; } } trim_spaces(ipbin->title, text, sizeof(ipbin->title)); memset(result, 0, sizeof(result)); int vmu_num = 0; if (GUI_WidgetGetState(self.vmu)) { vmu_num = atoi(GUI_TextEntryGetText(self.vmu_number)); } snprintf(result, sizeof(result), "title = %s\ndevice = %s\ndma = %d\nasync = %d\ncdda = %d\n" "irq = %d\nlow = %d\nheap = %08lx\nfastboot = %d\ntype = %d\nmode = %d\nmemory = %s\n" "vmu = %d\nscrhotkey = %lx\n" "pa1 = %08lx\npv1 = %08lx\npa2 = %08lx\npv2 = %08lx\n", text, GUI_TextEntryGetText(self.device), GUI_WidgetGetState(self.dma), async, cdda_mode, GUI_WidgetGetState(self.irq), GUI_WidgetGetState(self.low), heap, GUI_WidgetGetState(self.fastboot), type, mode, memory, vmu_num, (uint32)(GUI_WidgetGetState(self.screenshot) ? SCREENSHOT_HOTKEY : 0), self.pa[0], self.pv[0], self.pa[1], self.pv[1]); fs_write(fd, result, strlen(result)); fs_close(fd); return 0; } int isoLoader_LoadPreset() { if (!self.filename[0]) { isoLoader_DefaultPreset(); return -1; } char *filename = makePresetFilename(GUI_FileManagerGetPath(self.filebrowser), self.md5); if (FileSize(filename) < 5) { isoLoader_DefaultPreset(); return -1; } int use_dma = 0, emu_async = 16, emu_cdda = 0, use_irq = 0; int fastboot = 0, low = 0, emu_vmu = 0, scr_hotkey = 0; int boot_mode = BOOT_MODE_DIRECT; int bin_type = BIN_TYPE_AUTO; uint32 heap = HEAP_MODE_AUTO; char title[32] = ""; char device[8] = ""; char memory[12] = "0x8c000100"; char heap_memory[12] = ""; char patch_a[2][10]; char patch_v[2][10]; int i, len; char *name; memset(patch_a, 0, 2 * 10); memset(patch_v, 0, 2 * 10); isoldr_conf options[] = { { "dma", CONF_INT, (void *) &use_dma }, { "cdda", CONF_INT, (void *) &emu_cdda }, { "irq", CONF_INT, (void *) &use_irq }, { "low", CONF_INT, (void *) &low }, { "vmu", CONF_INT, (void *) &emu_vmu }, { "scrhotkey",CONF_INT, (void *) &scr_hotkey }, { "heap", CONF_STR, (void *) &heap_memory}, { "memory", CONF_STR, (void *) memory }, { "async", CONF_INT, (void *) &emu_async }, { "mode", CONF_INT, (void *) &boot_mode }, { "type", CONF_INT, (void *) &bin_type }, { "title", CONF_STR, (void *) title }, { "device", CONF_STR, (void *) device }, { "fastboot", CONF_INT, (void *) &fastboot }, { "pa1", CONF_STR, (void *) patch_a[0] }, { "pv1", CONF_STR, (void *) patch_v[0] }, { "pa2", CONF_STR, (void *) patch_a[1] }, { "pv2", CONF_STR, (void *) patch_v[1] }, { NULL, CONF_END, NULL } }; if (conf_parse(options, filename)) { ds_printf("DS_ERROR: Can't parse preset\n"); isoLoader_DefaultPreset(); return -1; } GUI_WidgetSetState(self.dma, use_dma); isoLoader_toggleDMA(self.dma); if (emu_async == 0) { GUI_WidgetSetState(self.async[0], 1); isoLoader_toggleAsync(self.async[0]); } else { for(int i = 1; i < sizeof(self.async) >> 2; i++) { int val = atoi(GUI_LabelGetText(GUI_ButtonGetCaption(self.async[i]))); if(emu_async == val) { GUI_WidgetSetState(self.async[i], 1); isoLoader_toggleAsync(self.async[i]); break; } } } GUI_WidgetSetState(self.cdda, emu_cdda ? 1 : 0); isoLoader_toggleCDDA(self.cdda_mode[emu_cdda]); GUI_WidgetSetState(self.fastboot, fastboot); GUI_WidgetSetState(self.irq, use_irq); GUI_WidgetSetState(self.vmu, emu_vmu ? 1 : 0); GUI_WidgetSetState(self.screenshot, scr_hotkey ? 1 : 0); if (emu_vmu) { char num[8]; sprintf(num, "%03d", emu_vmu); GUI_TextEntrySetText(self.vmu_number, num); } heap = strtoul(heap_memory, NULL, 16); if (heap <= HEAP_MODE_MAPLE) { GUI_WidgetSetState(self.heap[heap], 1); isoLoader_toggleHeap(self.heap[heap]); } else { for (int i = HEAP_MODE_MAPLE; i < sizeof(self.heap) >> 2; i++) { if (!self.heap[i]) { break; } name = (char *)GUI_ObjectGetName((GUI_Object *)self.heap[i]); len = strlen(name); if (!strncmp(name, heap_memory, sizeof(heap_memory)) || len < 8) { GUI_WidgetSetState(self.heap[i], 1); isoLoader_toggleHeap(self.heap[i]); if (len < 8) { GUI_TextEntrySetText(self.heap_memory_text, &heap_memory[4]); } break; } } } GUI_WidgetSetState(self.os_chk[bin_type], 1); isoLoader_toggleOS(self.os_chk[bin_type]); GUI_WidgetSetState(self.boot_mode_chk[boot_mode], 1); isoLoader_toggleBootMode(self.boot_mode_chk[boot_mode]); if (strlen(title) > 0) { GUI_LabelSetText(self.title, title); vmu_draw_string(title); } if (strlen(device) > 0) { GUI_TextEntrySetText(self.device, device); } else { GUI_TextEntrySetText(self.device, "auto"); } for (i = 0; self.memory_chk[i]; i++) { name = (char *)GUI_ObjectGetName((GUI_Object *)self.memory_chk[i]); len = strlen(name); if (!strncmp(name, memory, sizeof(memory)) || len < 8) { GUI_WidgetSetState(self.memory_chk[i], 1); isoLoader_toggleMemory(self.memory_chk[i]); if (len < 8) { GUI_TextEntrySetText(self.memory_text, &memory[4]); } break; } } for(int i = 0; i < sizeof(self.wpa) >> 2; ++i) { if (patch_a[i][1] != '0' && strlen(patch_a[i]) == 8 && strlen(patch_v[i]) ) { self.pa[i] = strtoul(patch_a[i], NULL, 16); self.pv[i] = strtoul(patch_v[i], NULL, 16); GUI_TextEntrySetText(self.wpa[i], patch_a[i]); GUI_TextEntrySetText(self.wpv[i], patch_v[i]); } else { self.pa[i] = 0; self.pv[i] = 0; } } return 0; } void isoLoader_Init(App_t *app) { GUI_Widget *w, *b; GUI_Callback *cb; if(app != NULL) { memset(&self, 0, sizeof(self)); self.app = app; self.current_dev = -1; self.current_item = -1; self.current_item_dir = -1; self.sector_size = 2048; self.btn_dev[APP_DEVICE_CD] = APP_GET_WIDGET("btn_cd"); self.btn_dev[APP_DEVICE_SD] = APP_GET_WIDGET("btn_sd"); self.btn_dev[APP_DEVICE_IDE] = APP_GET_WIDGET("btn_hdd"); self.btn_dev[APP_DEVICE_PC] = APP_GET_WIDGET("btn_pc"); self.item_norm = APP_GET_SURFACE("item-normal"); self.item_focus = APP_GET_SURFACE("item-focus"); self.item_selected = APP_GET_SURFACE("item-selected"); self.btn_dev_norm[APP_DEVICE_CD] = APP_GET_SURFACE("btn_cd_norm"); self.btn_dev_over[APP_DEVICE_CD] = APP_GET_SURFACE("btn_cd_over"); self.btn_dev_norm[APP_DEVICE_SD] = APP_GET_SURFACE("btn_sd_norm"); self.btn_dev_over[APP_DEVICE_SD] = APP_GET_SURFACE("btn_sd_over"); self.btn_dev_norm[APP_DEVICE_IDE] = APP_GET_SURFACE("btn_hdd_norm"); self.btn_dev_over[APP_DEVICE_IDE] = APP_GET_SURFACE("btn_hdd_over"); self.btn_dev_norm[APP_DEVICE_PC] = APP_GET_SURFACE("btn_pc_norm"); self.btn_dev_over[APP_DEVICE_PC] = APP_GET_SURFACE("btn_pc_over"); self.default_cover = self.current_cover = APP_GET_SURFACE("cover"); self.pages = APP_GET_WIDGET("pages"); self.settings = APP_GET_WIDGET("settings"); self.games = APP_GET_WIDGET("games"); self.link = APP_GET_WIDGET("link"); self.extensions = APP_GET_WIDGET("extensions"); self.filebrowser = APP_GET_WIDGET("file_browser"); self.cover_widget = APP_GET_WIDGET("cover_image"); self.title = APP_GET_WIDGET("game_title"); self.btn_run = APP_GET_WIDGET("run_iso"); self.run_pane = APP_GET_WIDGET("run-panel"); self.preset = APP_GET_WIDGET("preset-checkbox"); self.dma = APP_GET_WIDGET("dma-checkbox"); self.cdda = APP_GET_WIDGET("cdda-checkbox"); self.irq = APP_GET_WIDGET("irq-checkbox"); self.low = APP_GET_WIDGET("low-checkbox"); self.fastboot = APP_GET_WIDGET("fastboot-checkbox"); self.vmu = APP_GET_WIDGET("vmu-checkbox"); self.vmu_number = APP_GET_WIDGET("vmu-number"); self.vmu_create = APP_GET_WIDGET("vmu-create-checkbox"); self.screenshot = APP_GET_WIDGET("screenshot-checkbox"); self.options_panel = APP_GET_WIDGET("options-panel"); self.wpa[0] = APP_GET_WIDGET("pa1-text"); self.wpa[1] = APP_GET_WIDGET("pa2-text"); self.wpv[0] = APP_GET_WIDGET("pv1-text"); self.wpv[1] = APP_GET_WIDGET("pv2-text"); self.icosizebtn[0] = APP_GET_WIDGET("48x48"); self.icosizebtn[1] = APP_GET_WIDGET("64x64"); self.icosizebtn[2] = APP_GET_WIDGET("96x96"); self.icosizebtn[3] = APP_GET_WIDGET("128x128"); self.icosizebtn[4] = APP_GET_WIDGET("256x256"); self.rotate180 = APP_GET_WIDGET("rotate-link"); self.linktext = APP_GET_WIDGET("link-text"); self.btn_hidetext = APP_GET_WIDGET("hide-name"); self.save_link_btn = APP_GET_WIDGET("save-link-btn"); self.save_link_txt = APP_GET_WIDGET("save-link-txt"); self.wlnkico = APP_GET_WIDGET("link-icon"); self.stdico = APP_GET_SURFACE("stdico"); self.slnkico = GUI_SurfaceFrom("ico-surface", GUI_SurfaceGet(self.stdico)); w = APP_GET_WIDGET("async-panel"); self.async[0] = GUI_ContainerGetChild(w, 1); int sz = (sizeof(self.async) >> 2) - 1; for(int i = 0; i < sz; i++) { b = GUI_ContainerGetChild(w, i + 2); int val = atoi( GUI_LabelGetText( GUI_ButtonGetCaption(b) ) ); self.async[(val - 1) < sz ? val : sz] = b; } self.async_label = APP_GET_WIDGET("async-label"); self.device = APP_GET_WIDGET("device"); w = APP_GET_WIDGET("switch-panel"); for(int i = 0; i < (sizeof(self.options_switch) >> 2); i++) { self.options_switch[i] = GUI_ContainerGetChild(w, i); } w = APP_GET_WIDGET("boot-mode-panel"); for(int i = 0; i < (sizeof(self.boot_mode_chk) >> 2); i++) { self.boot_mode_chk[i] = GUI_ContainerGetChild(w, i); } w = APP_GET_WIDGET("heap-memory-panel"); for(int i = 0, j = 0; i <= GUI_ContainerGetCount(w); i++) { b = GUI_ContainerGetChild(w, i); if(GUI_WidgetGetType(b) == WIDGET_TYPE_BUTTON) { self.heap[j++] = b; if(j == sizeof(self.heap) / 4) break; } } w = APP_GET_WIDGET("cdda-mode-panel"); for(int i = 0; i < (sizeof(self.cdda_mode) >> 2); i++) { self.cdda_mode[i] = GUI_ContainerGetChild(w, i); } w = APP_GET_WIDGET("os-panel"); for(int i = 0; i < (sizeof(self.os_chk) >> 2); i++) { self.os_chk[i] = GUI_ContainerGetChild(w, i + 1); } w = APP_GET_WIDGET("boot-memory-panel"); for(int i = 0, j = 0; i < GUI_ContainerGetCount(w); i++) { b = GUI_ContainerGetChild(w, i); if(GUI_WidgetGetType(b) == WIDGET_TYPE_BUTTON) { self.memory_chk[j++] = b; if(j == sizeof(self.memory_chk) / 4) break; } } self.memory_text = APP_GET_WIDGET("boot-memory-text"); self.heap_memory_text = APP_GET_WIDGET("heap-memory-text"); if(!is_custom_bios()/*DirExists("/cd")*/) { cb = GUI_CallbackCreate((GUI_CallbackFunction *)isoLoader_SwitchVolume, NULL, "/cd"); if(cb) { GUI_ButtonSetClick(self.btn_dev[APP_DEVICE_CD], cb); GUI_ObjectDecRef((GUI_Object *) cb); } GUI_WidgetSetEnabled(self.btn_dev[APP_DEVICE_CD], 1); } if(DirExists("/sd")) { cb = GUI_CallbackCreate((GUI_CallbackFunction *)isoLoader_SwitchVolume, NULL, "/sd"); if(cb) { GUI_ButtonSetClick(self.btn_dev[APP_DEVICE_SD], cb); GUI_ObjectDecRef((GUI_Object *) cb); } GUI_WidgetSetEnabled(self.btn_dev[APP_DEVICE_SD], 1); } if(DirExists("/ide")) { cb = GUI_CallbackCreate((GUI_CallbackFunction *)isoLoader_SwitchVolume, NULL, "/ide"); if(cb) { GUI_ButtonSetClick(self.btn_dev[APP_DEVICE_IDE], cb); GUI_ObjectDecRef((GUI_Object *) cb); } GUI_WidgetSetEnabled(self.btn_dev[APP_DEVICE_IDE], 1); } if(DirExists("/pc")) { cb = GUI_CallbackCreate((GUI_CallbackFunction *)isoLoader_SwitchVolume, NULL, "/pc"); if(cb) { GUI_ButtonSetClick(self.btn_dev[APP_DEVICE_PC], cb); GUI_ObjectDecRef((GUI_Object *) cb); } GUI_WidgetSetEnabled(self.btn_dev[APP_DEVICE_PC], 1); } /* Checking for arguments from a executor */ if(app->args != NULL) { char *name = getFilePath(app->args); if(name) { GUI_FileManagerSetPath(self.filebrowser, name); free(name); } self.have_args = true; } else { self.have_args = false; } isoLoader_DefaultPreset(); w = APP_GET_WIDGET("version"); if(w) { char vers[32]; snprintf(vers, sizeof(vers), "v%s", app->ver); GUI_LabelSetText(w, vers); } isoLoader_ResizeUI(); } else { ds_printf("DS_ERROR: %s: Attempting to call %s is not by the app initiate.\n", lib_get_name(), __func__); } } void isoLoader_ResizeUI() { SDL_Surface *screen = GetScreen(); GUI_Widget *filemanager_bg = APP_GET_WIDGET("filemanager_bg"); GUI_Widget *cover_bg = APP_GET_WIDGET("cover_bg"); GUI_Widget *title_panel = APP_GET_WIDGET("title_panel"); int screen_width = GetScreenWidth(); SDL_Rect filemanager_bg_rect = GUI_WidgetGetArea(filemanager_bg); SDL_Rect cover_bg_rect = GUI_WidgetGetArea(cover_bg); SDL_Rect title_rect = GUI_WidgetGetArea(title_panel); const int gap = 19; int filemanager_bg_width = screen_width - cover_bg_rect.w - gap * 3; int filemanager_bg_height = filemanager_bg_rect.h; GUI_Surface *fm_bg = GUI_SurfaceCreate("fm_bg", screen->flags, filemanager_bg_width, filemanager_bg_height, screen->format->BitsPerPixel, screen->format->Rmask, screen->format->Gmask, screen->format->Bmask, screen->format->Amask); GUI_SurfaceFill(fm_bg, NULL, GUI_SurfaceMapRGB(fm_bg, 255, 255, 255)); SDL_Rect grayRect; grayRect.x = 6; grayRect.y = 6; grayRect.w = filemanager_bg_width - grayRect.x * 2; grayRect.h = filemanager_bg_height - grayRect.y * 2; GUI_SurfaceFill(fm_bg, &grayRect, GUI_SurfaceMapRGB(fm_bg, 0xCC, 0xE4, 0xF0)); GUI_PanelSetBackground(filemanager_bg, fm_bg); GUI_ObjectDecRef((GUI_Object *) fm_bg); int delta_x = filemanager_bg_width + gap * 2 - cover_bg_rect.x; GUI_WidgetSetPosition(cover_bg, cover_bg_rect.x + delta_x, cover_bg_rect.y); GUI_WidgetSetPosition(title_panel, title_rect.x + delta_x, title_rect.y); GUI_WidgetSetSize(filemanager_bg, filemanager_bg_width, filemanager_bg_height); GUI_FileManagerResize(self.filebrowser, filemanager_bg_width - grayRect.x * 2, filemanager_bg_height - grayRect.y * 2); } void isoLoader_Shutdown(App_t *app) { (void)app; if(self.isoldr) { free(self.isoldr); } } void isoLoader_Exit(GUI_Widget *widget) { (void)widget; App_t *app = NULL; if(self.have_args == true) { app = GetAppByName("File Manager"); if(!app || !(app->state & APP_STATE_LOADED)) { app = NULL; } } if(!app) { app = GetAppByName("Main"); } OpenApp(app, NULL); } <file_sep>/lib/SDL_gui/AbstractTable.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_AbstractTable::GUI_AbstractTable(const char *aname, int x, int y, int w, int h) : GUI_Container(aname, x, y, w, h) { SetTransparent(1); } GUI_AbstractTable::~GUI_AbstractTable() { } void GUI_AbstractTable::Update(int force) { if (parent == 0) return; if (force) { if (flags & WIDGET_TRANSPARENT) { SDL_Rect r = area; r.x = x_offset; r.y = y_offset; Erase(&r); } int row, column; int x, y, w, h; y = 0; for (row=0; row<GetRowCount(); row++) { x = 0; h = GetRowSize(row); for (column=0; column<GetColumnCount(); column++) { w = GetColumnSize(column); if (x>=0 && x<area.w && y>=0 && y<area.h) { SDL_Rect r; r.x = x; r.y = y; r.w = w; r.h = h; DrawCell(column, row, &r); } x += w; } y += h; } } } int GUI_AbstractTable::Event(const SDL_Event *event, int xoffset, int yoffset) { return GUI_Widget::Event(event, xoffset, yoffset); } int GUI_AbstractTable::GetRowCount(void) { return 16; } int GUI_AbstractTable::GetRowSize(int row) { return area.h/16; } int GUI_AbstractTable::GetColumnCount(void) { return 16; } int GUI_AbstractTable::GetColumnSize(int column) { return area.w/16; } void GUI_AbstractTable::DrawCell(int column, int row, const SDL_Rect *dr) { SDL_Color c; c.r = column * 16; c.g = row * 16; c.b = 0; c.unused = 0; Fill(dr, c); } <file_sep>/include/network/telnet.h /** * \file telnet.h * \brief Telnet server * \date 2007-2014 * \author SWAT www.dc-swat.ru */ #ifndef _DS_TELNET_H #define _DS_TELNET_H #ifdef USE_LWIP #include "lwip.h" #include "sockets.h" #else #include <kos/net.h> #include <sys/socket.h> #endif /* telnetd server */ int telnetd_init(int port); void telnetd_shutdown(); #endif /* _DS_TELNET_H */<file_sep>/src/irq/exceptions.c /** * \file exceptions.c * \brief Exception handling for DreamShell based on dcplaya code * \date 2004-2015 * \author SWAT www.dc-swat.ru */ #include "ds.h" #include <arch/irq.h> #include "setjmp.h" #include "drivers/asic.h" /* * This is the table where context is saved when an exception occure * After the exception is handled, context will be restored and * an RTE instruction will be issued to come back to the user code. * Modifying the content of the table BEFORE returning from the handler * of an exception let us do interesting tricks :) * * 0x00 .. 0x3c : Registers R0 to R15 * 0x40 : SPC (return adress of RTE) * 0x58 : SSR (saved SR, restituted after RTE) * */ #define EXPT_GUARD_STACK_COUNT 4 static expt_quard_stack_t expt_stack[EXPT_GUARD_STACK_COUNT]; static kthread_key_t expt_key; static int expt_inited = 0; /* This is the list of exceptions code we want to handle */ static struct { int code; const char *name; } exceptions_code[] = { {EXC_DATA_ADDRESS_READ, "EXC_DATA_ADDRESS_READ"}, // 0x00e0 /* Data address (read) */ {EXC_DATA_ADDRESS_WRITE,"EXC_DATA_ADDRESS_WRITE"}, // 0x0100 /* Data address (write) */ {EXC_USER_BREAK_PRE, "EXC_USER_BREAK_PRE"}, // 0x01e0 /* User break before instruction */ {EXC_ILLEGAL_INSTR, "EXC_ILLEGAL_INSTR"}, // 0x0180 /* Illegal instruction */ {EXC_GENERAL_FPU, "EXC_GENERAL_FPU"}, // 0x0800 /* General FPU exception */ {EXC_SLOT_FPU, "EXC_SLOT_FPU"}, // 0x0820 /* Slot FPU exception */ {0, NULL} }; static void guard_irq_handler(irq_t source, irq_context_t *context) { dbglog(DBG_INFO, "\n=============== CATCHING EXCEPTION ===============\n"); irq_context_t *irq_ctx = irq_get_context(); if (source == EXC_FPU) { /* Display user friendly informations */ export_sym_t * symb; symb = export_lookup_by_addr(irq_ctx->pc); if (symb) { dbglog(DBG_INFO, "FPU EXCEPTION PC = %s + 0x%08x (0x%08x)\n", symb->name, ((int)irq_ctx->pc) - ((int)symb->ptr), (int)irq_ctx->pc); } /* skip the offending FPU instruction */ int *ptr = (int *)&irq_ctx->r[0x40/4]; *ptr += 4; return; } /* Display user friendly informations */ export_sym_t * symb; int i; uint32 *stk = (uint32 *)irq_ctx->r[15]; for (i = 15; i >= 0; i--) { if((stk[i] < 0x8c000000) || (stk[i] > 0x8d000000) || !(symb = export_lookup_by_addr(stk[i])) || ((int)stk[i] - ((int)symb->ptr) > 0x800)) { dbglog(DBG_INFO, "STACK#%2d = 0x%08x\n", i, (int)stk[i]); } else { dbglog(DBG_INFO, "STACK#%2d = 0x%08x (%s + 0x%08x)\n", i, (int)stk[i], symb->name, (int)stk[i] - ((int)symb->ptr)); } } symb = export_lookup_by_addr(irq_ctx->pc); if (symb && (int)stk[i] - ((int)symb->ptr) < 0x800) { dbglog(DBG_INFO, " PC = %s + 0x%08x (0x%08x)\n", symb->name, ((int)irq_ctx->pc) - ((int)symb->ptr), (int)irq_ctx->pc); } else { dbglog(DBG_INFO, " PC = 0x%08x\n", (int)irq_ctx->pc); } symb = export_lookup_by_addr(irq_ctx->pr); if (symb && (int)stk[i] - ((int)symb->ptr) < 0x800) { dbglog(DBG_INFO, " PR = %s + 0x%08x (0x%08x)\n", symb->name, ((int)irq_ctx->pr) - ((int)symb->ptr), (int)irq_ctx->pr); } else { dbglog(DBG_INFO, " PR = 0x%08x\n", (int)irq_ctx->pr); } uint32 *regs = irq_ctx->r; dbglog(DBG_INFO, " R0-R3 = %08lx %08lx %08lx %08lx\n", regs[0], regs[1], regs[2], regs[3]); dbglog(DBG_INFO, " R4-R7 = %08lx %08lx %08lx %08lx\n", regs[4], regs[5], regs[6], regs[7]); dbglog(DBG_INFO, " R8-R11 = %08lx %08lx %08lx %08lx\n", regs[8], regs[9], regs[10], regs[11]); dbglog(DBG_INFO, " R12-R15 = %08lx %08lx %08lx %08lx\n", regs[12], regs[13], regs[14], regs[15]); //arch_stk_trace_at(regs[14], 0); for (i = 0; exceptions_code[i].code; i++) { if (exceptions_code[i].code == source) { dbglog(DBG_INFO, " EVENT = %s (0x%08x)\n", exceptions_code[i].name, (int)source); break; } } expt_quard_stack_t *s = NULL; s = (expt_quard_stack_t *) kthread_getspecific(expt_key); if (s && s->pos >= 0) { // Simulate a call to longjmp by directly changing stored // context of the exception irq_ctx->pc = (uint32)longjmp; irq_ctx->r[4] = (uint32)s->jump[s->pos]; irq_ctx->r[5] = (uint32)(void *) -1; } else { //malloc_stats(); //texture_memstats(); /* not handled --> panic !! */ //irq_dump_regs(0, source); dbgio_set_dev_fb(); vid_clear(0, 0, 0); ConsoleInformation *con = GetConsole(); for(i = 16; i > 0; i--) { dbglog(DBG_INFO, "%s\n", con->ConsoleLines[i]); } dbglog(DBG_ERROR, "Unhandled Exception. Reboot after 10 seconds."); //panic("Unhandled IRQ/Exception"); timer_spin_sleep(10000); arch_reboot(); // asic_sys_reset(); } } void expt_print_place(char *file, int line, const char *func) { dbglog(DBG_INFO, " PLACE = %s:%d %s\n" "================" " END OF EXCEPTION " "================\n\n", file, line, func); } static expt_quard_stack_t *expt_get_free_stack() { int i; for(i = 0; i < EXPT_GUARD_STACK_COUNT; i++) { if(expt_stack[i].type == 0) { expt_stack[i].type = i + 1; return &expt_stack[i]; } } return NULL; } expt_quard_stack_t *expt_get_stack() { expt_quard_stack_t *s = NULL; s = (expt_quard_stack_t *) kthread_getspecific(expt_key); if(s == NULL) { s = expt_get_free_stack(); if(s == NULL) { s = (expt_quard_stack_t *) malloc(sizeof(expt_quard_stack_t)); if(s == NULL) { EXPT_GUARD_THROW; } memset_sh4(s, 0, sizeof(expt_quard_stack_t)); s->type = -1; } s->pos = -1; kthread_setspecific(expt_key, (void *)s); } return s; } static void expt_key_free(void *p) { expt_quard_stack_t *s = (expt_quard_stack_t *)p; if(s->type < 0) { free(p); // TODO check thread magic correct } else { memset_sh4(s, 0, sizeof(expt_quard_stack_t)); } } int expt_init() { if(kthread_key_create(&expt_key, &expt_key_free)) { printf("Error in creating exception key for tls\n"); return -1; } int i; for(i = 0; i < EXPT_GUARD_STACK_COUNT; i++) { memset_sh4(&expt_stack[i], 0, sizeof(expt_quard_stack_t)); } // TODO : save old values for (i = 0; exceptions_code[i].code; i++) irq_set_handler(exceptions_code[i].code, guard_irq_handler); expt_inited = 1; return 0; } void expt_shutdown() { if(!expt_inited) { return; } int i; // for(i = 0; i < EXPT_GUARD_STACK_COUNT; i++) { // memset_sh4(&expt_stack[i], 0, sizeof(expt_quard_stack_t)); // } for (i = 0; exceptions_code[i].code; i++) irq_set_handler(exceptions_code[i].code, 0); kthread_key_delete(expt_key); } <file_sep>/lib/SDL_Console/src/internal.c /* SDL_console: An easy to use drop-down console based on the SDL library Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WHITOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library Generla Public License along with this library; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA <NAME> <EMAIL> */ /* internal.c * Written By: <NAME> <<EMAIL>> */ /* internal.[c,h] are various routines used internally * by SDL_console and DrawText. */ #include "SDL.h" /* * Return the pixel value at (x, y) * NOTE: The surface must be locked before calling this! */ Uint32 DT_GetPixel(SDL_Surface *surface, int x, int y) { int bpp = surface->format->BytesPerPixel; /* Here p is the address to the pixel we want to retrieve */ Uint8 *p = (Uint8 *) surface->pixels + y * surface->pitch + x * bpp; switch (bpp) { case 1: return *p; case 2: return *(Uint16 *) p; case 3: if(SDL_BYTEORDER == SDL_BIG_ENDIAN) return p[0] << 16 | p[1] << 8 | p[2]; else return p[0] | p[1] << 8 | p[2] << 16; case 4: return *(Uint32 *) p; default: return 0; /* shouldn't happen, but avoids warnings */ } } /* * Set the pixel at (x, y) to the given value * NOTE: The surface must be locked before calling this! */ void DT_PutPixel(SDL_Surface *surface, int x, int y, Uint32 pixel) { int bpp = surface->format->BytesPerPixel; /* Here p is the address to the pixel we want to set */ Uint8 *p = (Uint8 *) surface->pixels + y * surface->pitch + x * bpp; switch (bpp) { case 1: *p = pixel; break; case 2: *(Uint16 *) p = pixel; break; case 3: if(SDL_BYTEORDER == SDL_BIG_ENDIAN) { p[0] = (pixel >> 16) & 0xff; p[1] = (pixel >> 8) & 0xff; p[2] = pixel & 0xff; } else { p[0] = pixel & 0xff; p[1] = (pixel >> 8) & 0xff; p[2] = (pixel >> 16) & 0xff; } break; case 4: *(Uint32 *) p = pixel; break; default: break; } } <file_sep>/firmware/aica/codec/interrupt_utils.h /* * Defines and Macros for Interrupt-Service-Routines * collected and partly created by * <NAME> <<EMAIL>> * * Copyright 2005 <NAME> * No guarantees, warrantees, or promises, implied or otherwise. * May be used for hobby or commercial purposes provided copyright * notice remains intact. */ #ifndef interrupt_utils_ #define interrupt_utils_ /* The following defines are usefull for interrupt service routine declarations. */ /* RAMFUNC Attribute which defines a function to be located in memory section .fastrun and called via "long calls". See linker-skript and startup-code to see how the .fastrun-section is handled. The definition is not only useful for ISRs but since ISRs should be executed fast the macro is defined in this header */ #define RAMFUNC __attribute__ ((long_call, section (".fastrun"))) /* INTFUNC standard attribute for arm-elf-gcc which marks a function as ISR (for the VIC). Since gcc seems to produce wrong code if this attribute is used in thumb/thumb-interwork the attribute should only be used for "pure ARM-mode" binaries. */ #define INTFUNC __attribute__ ((interrupt("IRQ"))) /* NACKEDFUNC gcc will not add any code to a function declared "nacked". The uses has to take care to save registers and add the needed code for ISR functions. Some macros for this are provided below */ #define NACKEDFUNC __attribute__((naked)) /****************************************************************************** * * MACRO Name: ISR_STORE() * * Description: * This MACRO is used upon entry to an ISR with interrupt nesting. * Should be used together with ISR_ENABLE_NEST(). The MACRO * performs the following steps: * * 1 - Save the non-banked registers r0-r12 and lr onto the IRQ stack. * *****************************************************************************/ #define ISR_STORE() asm volatile( \ "STMDB SP!,{R0-R12,LR}\n" ) /****************************************************************************** * * MACRO Name: ISR_RESTORE() * * Description: * This MACRO is used upon exit from an ISR with interrupt nesting. * Should be used together with ISR_DISABLE_NEST(). The MACRO * performs the following steps: * * 1 - Load the non-banked registers r0-r12 and lr from the IRQ stack. * 2 - Adjusts resume adress * *****************************************************************************/ #define ISR_RESTORE() asm volatile( \ "LDMIA SP!,{R0-R12,LR}\n" \ "SUBS R15,R14,#0x0004\n" ) /****************************************************************************** * * MACRO Name: ISR_ENABLE_NEST() * * Description: * This MACRO is used upon entry from an ISR with interrupt nesting. * Should be used after ISR_ENTRY_STORE. * *****************************************************************************/ #define ISR_ENABLE_NEST() asm volatile( \ "MRS LR, SPSR \n" \ "STMFD SP!, {LR} \n" \ "MSR CPSR_c, #0x1F \n" \ "STMFD SP!, {LR} " ) /****************************************************************************** * * MACRO Name: ISR_DISABLE_NEST() * * Description: * This MACRO is used upon entry from an ISR with interrupt nesting. * Should be used after ISR_ENTRY_STORE. * *****************************************************************************/ #define ISR_DISABLE_NEST() asm volatile( \ "LDMFD SP!, {LR} \n" \ "MSR CPSR_c, #0x92 \n" \ "LDMFD SP!, {LR} \n" \ "MSR SPSR_cxsf, LR \n" ) /* * The macros ISR_ENTRY and ISR_EXIT are from the * file "armVic.h" by: * * Copyright 2004, R O SoftWare * No guarantees, warrantees, or promises, implied or otherwise. * May be used for hobby or commercial purposes provided copyright * notice remains intact. * */ /****************************************************************************** * * MACRO Name: ISR_ENTRY() * * Description: * This MACRO is used upon entry to an ISR. The current version of * the gcc compiler for ARM does not produce correct code for * interrupt routines to operate properly with THUMB code. The MACRO * performs the following steps: * * 1 - Adjust address at which execution should resume after servicing * ISR to compensate for IRQ entry * 2 - Save the non-banked registers r0-r12 and lr onto the IRQ stack. * 3 - Get the status of the interrupted program is in SPSR. * 4 - Push it onto the IRQ stack as well. * *****************************************************************************/ #define ISR_ENTRY() asm volatile(" sub lr, lr,#4\n" \ " stmfd sp!,{r0-r12,lr}\n" \ " mrs r1, spsr\n" \ " stmfd sp!,{r1}") /****************************************************************************** * * MACRO Name: ISR_EXIT() * * Description: * This MACRO is used to exit an ISR. The current version of the gcc * compiler for ARM does not produce correct code for interrupt * routines to operate properly with THUMB code. The MACRO performs * the following steps: * * 1 - Recover SPSR value from stack * 2 - and restore its value * 3 - Pop the return address & the saved general registers from * the IRQ stack & return * *****************************************************************************/ #define ISR_EXIT() asm volatile(" ldmfd sp!,{r1}\n" \ " msr spsr_c,r1\n" \ " ldmfd sp!,{r0-r12,pc}^") /****************************************************************************** * * Function Name: disableIRQ() * * Description: * This function sets the IRQ disable bit in the status register * * Calling Sequence: * void * * Returns: * previous value of CPSR * *****************************************************************************/ unsigned disableIRQ(void); /****************************************************************************** * * Function Name: enableIRQ() * * Description: * This function clears the IRQ disable bit in the status register * * Calling Sequence: * void * * Returns: * previous value of CPSR * *****************************************************************************/ unsigned enableIRQ(void); /****************************************************************************** * * Function Name: restoreIRQ() * * Description: * This function restores the IRQ disable bit in the status register * to the value contained within passed oldCPSR * * Calling Sequence: * void * * Returns: * previous value of CPSR * *****************************************************************************/ unsigned restoreIRQ(unsigned oldCPSR); /****************************************************************************** * * Function Name: disableFIQ() * * Description: * This function sets the FIQ disable bit in the status register * * Calling Sequence: * void * * Returns: * previous value of CPSR * *****************************************************************************/ unsigned disableFIQ(void); /****************************************************************************** * * Function Name: enableFIQ() * * Description: * This function clears the FIQ disable bit in the status register * * Calling Sequence: * void * * Returns: * previous value of CPSR * *****************************************************************************/ unsigned enableFIQ(void); /****************************************************************************** * * Function Name: restoreIRQ() * * Description: * This function restores the FIQ disable bit in the status register * to the value contained within passed oldCPSR * * Calling Sequence: * void * * Returns: * previous value of CPSR * *****************************************************************************/ unsigned restoreFIQ(unsigned oldCPSR); #endif <file_sep>/modules/ftpd/lftpd/private/lftpd_string.h #pragma once #define CRLF "\r\n" char* lftpd_string_trim(char* s); <file_sep>/include/drivers/spi.h /* DreamShell ##version## drivers/spi.h Copyright (C) 2011-2014 SWAT */ #ifndef _SPI_H #define _SPI_H #include <arch/types.h> /** * \file * SPI interface for Sega Dreamcast SCIF * * \author SWAT */ /** * \brief Max speed delay */ #define SPI_DEFAULT_DELAY -1 /** * \brief Some predefined delays */ #define SPI_SDC_MMC_DELAY SPI_DEFAULT_DELAY #define SPI_ENC28J60_DELAY 1000000 /** * \brief Chip select pins */ #define SPI_CS_SCIF_RTS 10 #define SPI_CS_GPIO_VGA 8 // This is a real GPIO index #define SPI_CS_GPIO_RGB 9 #define SPI_CS_SDC SPI_CS_SCIF_RTS #define SPI_CS_ENC28J60 SPI_CS_GPIO_VGA #define SPI_CS_SDC_2 SPI_CS_GPIO_RGB /** * \brief Initializes the SPI interface */ int spi_init(int use_gpio); /** * \brief Shutdown the SPI interface */ int spi_shutdown(); /** * \brief Change the SPI delay for clock * * \param[in] The SPI delay */ void spi_set_delay(int delay); /** * \brief Getting current SPI delay * * \returns The SPI delay */ int spi_get_delay(); /** * \brief Switch on CS pin and lock SPI bus * * \param[in] the CS pin */ void spi_cs_on(int cs); /** * \brief Switch off CS pin and unlock SPI bus * * \param[in] the CS pin */ void spi_cs_off(int cs); /** * \brief Sends a byte over the SPI bus. * * \param[in] b The byte to send. */ void spi_send_byte(register uint8 b); void spi_cc_send_byte(register uint8 b); /** * \brief Receives a byte from the SPI bus. * * \returns The received byte. */ uint8 spi_rec_byte(); uint8 spi_cc_rec_byte(); /** * \brief Send and receive a byte to/from the SPI bus. * * \param[in] b The byte to send. * \returns The received byte. */ uint8 spi_sr_byte(register uint8 b); uint8 spi_cc_sr_byte(register uint8 b); /** * \brief Slow send and receive a byte to/from the SPI bus. * Used for SDC/MMC commands. * * \param[in] b The byte to send. * \returns The received byte. */ uint8 spi_slow_sr_byte(register uint8 b); /** * \brief Sends data contained in a buffer over the SPI bus. * * \param[in] data A pointer to the buffer which contains the data to send. * \param[in] len The number of bytes to send. */ void spi_send_data(const uint8* data, uint16 data_len); void spi_cc_send_data(const uint8* data, uint16 data_len); /** * \brief Receives multiple bytes from the SPI bus and writes them to a buffer. * * \param[out] buffer A pointer to the buffer into which the data gets written. * \param[in] len The number of bytes to read. */ void spi_rec_data(uint8* buffer, uint16 buffer_len); void spi_cc_rec_data(uint8* buffer, uint16 buffer_len); #endif /* _SPI_H */ <file_sep>/firmware/isoldr/loader/include/maple.h /** * DreamShell ISO Loader * Maple sniffing and VMU emulation * (c)2022-2023 SWAT <http://www.dc-swat.ru> */ #ifndef _MAPLE_H #define _MAPLE_H #include <arch/types.h> #define MAPLE_REG(x) (*(vuint32 *)(x)) #define MAPLE_BASE 0xa05f6c00 #define MAPLE_DMA_ADDR (MAPLE_BASE + 0x04) #define MAPLE_DMA_STATUS (MAPLE_BASE + 0x18) int maple_init_irq(); int maple_init_vmu(int num); #endif /* _MAPLE_H */ <file_sep>/commands/gdiopt/main.c /** * gdiopt.c * Copyright (c) 2014-2015 SWAT */ #include <ds.h> #include <stdlib.h> #include <string.h> #include <stdio.h> int bin2iso(const char *source, const char *target) { int seek_header, seek_ecc, sector_size; long i, source_length; char buf[2352]; const uint8_t SYNC_HEADER[12] = {0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0}; FILE *fpSource, *fpTarget; fpSource = fopen(source, "rb"); fpTarget = fopen(target, "wb"); if ((fpSource==NULL) || (fpTarget==NULL)) { return -1; } fread(buf, sizeof(char), 16, fpSource); if (memcmp(SYNC_HEADER, buf, 12)) { seek_header = 8; seek_ecc = 280; sector_size = 2336; } else { switch(buf[15]) { case 2: { seek_header = 24; // Mode2/2352 seek_ecc = 280; sector_size = 2352; break; } case 1: { seek_header = 16; // Mode1/2352 seek_ecc = 288; sector_size = 2352; break; } default: { fclose(fpTarget); fclose(fpSource); return -1; } } } fseek(fpSource, 0L, SEEK_END); source_length = ftell(fpSource)/sector_size; fseek(fpSource, 0L, SEEK_SET); for(i=0; i<source_length; i++) { fseek(fpSource, seek_header, SEEK_CUR); fread(buf, sizeof(char), 2048, fpSource); fwrite(buf, sizeof(char), 2048, fpTarget); fseek(fpSource, seek_ecc, SEEK_CUR); } fclose(fpTarget); fclose(fpSource); return 0; } int main(int argc, char *argv[]) { if(argc < 2) { ds_printf("GDI optimizer v%d.%d build %d by SWAT\n", VER_MAJOR, VER_MINOR, VER_BUILD); ds_printf("Usage: %s input.gdi output.gdi", argv[0]); return CMD_NO_ARG; } FILE *fr, *fw; int i, rc, track_no, track_count; uint32_t start_lba, flags, sector_size, offset; char fn_old[256], fn_new[256]; char outfn[9] = "disk.gdi"; outfn[8] = '\0'; char *out = outfn; fr = fopen(argv[1], "r"); if(!fr) { ds_printf("Can't open for read: %s\n", argv[1]); return CMD_ERROR; } if(argc > 2) { out = argv[2]; } fw = fopen(out, "w"); if(!fw) { ds_printf("Can't open for write: %s\n", out); fclose(fr); return CMD_ERROR; } rc = fscanf(fr, "%d", &track_count); if(rc == 1) { fprintf(fw, "%d\n", track_count); for(i = 0; i < track_count; i++) { start_lba = flags = sector_size = offset = 0; memset(fn_new, 0, sizeof(fn_new)); memset(fn_old, 0, sizeof(fn_old)); rc = fscanf(fr, "%d %ld %ld %ld %s %ld", &track_no, &start_lba, &flags, &sector_size, fn_old, &offset); if(flags == 4) { int len = strlen(fn_old); strncpy(fn_new, fn_old, sizeof(fn_new)); fn_new[len - 3] = 'i'; fn_new[len - 2] = 's'; fn_new[len - 1] = 'o'; fn_new[len] = '\0'; sector_size = 2048; ds_printf("Converting %s to %s ...\n", fn_old, fn_new); if(bin2iso(fn_old, fn_new) < 0) { ds_printf("Error!\n"); fclose(fr); fclose(fw); return CMD_ERROR; } fs_unlink(fn_old); } fprintf(fw, "%d %ld %ld %ld %s %ld\n", track_no, start_lba, flags, sector_size, (flags == 4 ? fn_new : fn_old), offset); } } fclose(fr); fclose(fw); fs_unlink(argv[1]); return CMD_OK; } <file_sep>/firmware/aica/codec/heapsort.h #ifndef _HEAPSORT_H_ #define _HEAPSORT_H_ int heapsort(void *vbase, size_t nmemb, size_t size, int (*compar)(void const *, void const *)); #endif /* _HEAPSORT_H_ */ <file_sep>/applications/iso_loader/modules/app_utils.h /* DreamShell ##version## utils.h - ISO Loader app utils Copyright (C) 2022-2023 SWAT */ /* Indexes of devices */ enum { APP_DEVICE_CD = 0, APP_DEVICE_SD = 1, APP_DEVICE_IDE, APP_DEVICE_PC, APP_DEVICE_COUNT }; enum { CONF_END = 0, CONF_INT = 1, CONF_STR }; typedef struct { const char *name; int conf_type; void *pointer; } isoldr_conf; void trim_spaces(char *input, char *output, int size); char *trim_spaces2(char *txt); char *fix_spaces(char *str); int conf_parse(isoldr_conf *cfg, const char *filename); int getDeviceType(const char *dir); int checkGDI(char *filepath, const char *fmPath, char *dirname, char *filename); char *makePresetFilename(const char *dir, uint8 *md5); char *lib_get_name(); uint32 lib_get_version(); <file_sep>/lib/SDL_gui/TextEntry.cc #include <kos.h> #include <assert.h> #include <stdlib.h> #include "SDL_gui.h" GUI_TextEntry::GUI_TextEntry(const char *aname, int x, int y, int w, int h, GUI_Font *afont, int size) : GUI_Widget(aname, x, y, w, h), font(afont) { SDL_Rect in; in.x = 4; in.y = 4; in.w = area.w-8; in.h = area.h-8; SetTransparent(1); normal_image = new GUI_Surface("normal", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); highlight_image = new GUI_Surface("highlight", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); focus_image = new GUI_Surface("focus", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); textcolor.r = 255; textcolor.g = 255; textcolor.b = 255; textcolor.unused = 255; font->IncRef(); buffer_size = size; buffer_index = 0; buffer = new char[size+1]; strcpy(buffer, ""); normal_image->Fill(NULL, 0xFF000000); highlight_image->Fill(NULL, 0x00FFFFFF); highlight_image->Fill(&in, 0xFF000000); focus_image->Fill(NULL, 0x00FFFFFF); focus_image->Fill(&in, 0x005050C0); focus_callback = 0; unfocus_callback = 0; wtype = WIDGET_TYPE_TEXTENTRY; } GUI_TextEntry::~GUI_TextEntry() { font->DecRef(); normal_image->DecRef(); highlight_image->DecRef(); focus_image->DecRef(); if (focus_callback) focus_callback->DecRef(); if (unfocus_callback) unfocus_callback->DecRef(); delete [] buffer; } void GUI_TextEntry::Update(int force) { if (parent==0) return; if (force) { GUI_Surface *surface; if (flags & WIDGET_TRANSPARENT) parent->Erase(&area); /* draw the background */ if (flags & WIDGET_HAS_FOCUS) { surface = focus_image; } else { if (flags & WIDGET_INSIDE) surface = highlight_image; else surface = normal_image; } if (surface) parent->Draw(surface, NULL, &area); surface = font->RenderQuality(buffer, textcolor); if (surface != NULL) { SDL_Rect dr; SDL_Rect sr; SDL_Rect clip = area; sr.w = dr.w = surface->GetWidth(); sr.h = dr.h = surface->GetHeight(); sr.x = sr.y = 0; dr.x = area.x + 4; dr.y = area.y + (area.h - (dr.h-4)) / 2; if (GUI_ClipRect(&sr, &dr, &clip)) parent->Draw(surface, &sr, &dr); surface->DecRef(); } } } void GUI_TextEntry::Clicked(int x, int y) { GUI_Screen *screen = GUI_GetScreen(); if (flags & WIDGET_HAS_FOCUS) { screen->ClearFocusWidget(); if (unfocus_callback) unfocus_callback->Call(this); } else { if (focus_callback) focus_callback->Call(this); screen->SetFocusWidget(this); } MarkChanged(); } void GUI_TextEntry::Highlighted(int x, int y) { } void GUI_TextEntry::unHighlighted(int x, int y) { } int GUI_TextEntry::Event(const SDL_Event *event, int xoffset, int yoffset) { if (event->type == SDL_KEYDOWN && flags & WIDGET_HAS_FOCUS) { int key = event->key.keysym.sym; int ch = event->key.keysym.unicode; if (key == SDLK_BACKSPACE) { if (buffer_index > 0) { buffer[--buffer_index] = '\0'; MarkChanged(); } return 1; } if (key == SDLK_RETURN) { GUI_Screen *screen = GUI_GetScreen(); screen->ClearFocusWidget(); if (unfocus_callback) unfocus_callback->Call(this); return 1; } //ch = kbd_get_key(); //if (isascii(ch)) { if (ch >= 32 && ch <= 126) { if (buffer_index < buffer_size) { buffer[buffer_index++] = ch; buffer[buffer_index] = 0; MarkChanged(); } return 1; } } return GUI_Widget::Event(event, xoffset, yoffset); } void GUI_TextEntry::SetFont(GUI_Font *afont) { GUI_ObjectKeep((GUI_Object **) &font, afont); /* FIXME: should re-draw the text in the new color */ } void GUI_TextEntry::SetTextColor(int r, int g, int b) { textcolor.r = r; textcolor.g = g; textcolor.b = b; /* FIXME: should re-draw the text in the new color */ } void GUI_TextEntry::SetText(const char *text) { assert(text != NULL); if (strlen(text) < buffer_size) { strcpy(buffer, text); buffer_index = strlen(text); } MarkChanged(); } const char *GUI_TextEntry::GetText(void) { return buffer; } void GUI_TextEntry::SetNormalImage(GUI_Surface *surface) { if (GUI_ObjectKeep((GUI_Object **) &normal_image, surface)) MarkChanged(); } void GUI_TextEntry::SetHighlightImage(GUI_Surface *surface) { if (GUI_ObjectKeep((GUI_Object **) &highlight_image, surface)) MarkChanged(); } void GUI_TextEntry::SetFocusImage(GUI_Surface *surface) { if (GUI_ObjectKeep((GUI_Object **) &focus_image, surface)) MarkChanged(); } void GUI_TextEntry::SetFocusCallback(GUI_Callback *callback) { GUI_ObjectKeep((GUI_Object **) &focus_callback, callback); } void GUI_TextEntry::SetUnfocusCallback(GUI_Callback *callback) { GUI_ObjectKeep((GUI_Object **) &unfocus_callback, callback); } extern "C" { GUI_Widget *GUI_TextEntryCreate(const char *name, int x, int y, int w, int h, GUI_Font *font, int size) { return new GUI_TextEntry(name, x, y, w, h, font, size); } int GUI_TextEntryCheck(GUI_Widget *widget) { // FIXME not implemented return 0; } void GUI_TextEntrySetFont(GUI_Widget *widget, GUI_Font *font) { ((GUI_TextEntry *) widget)->SetFont(font); } void GUI_TextEntrySetTextColor(GUI_Widget *widget, int r, int g, int b) { ((GUI_TextEntry *) widget)->SetTextColor(r, g, b); } void GUI_TextEntrySetText(GUI_Widget *widget, const char *text) { ((GUI_TextEntry *) widget)->SetText(text); } const char *GUI_TextEntryGetText(GUI_Widget *widget) { return ((GUI_TextEntry *) widget)->GetText(); } void GUI_TextEntrySetNormalImage(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_TextEntry *) widget)->SetNormalImage(surface); } void GUI_TextEntrySetHighlightImage(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_TextEntry *) widget)->SetHighlightImage(surface); } void GUI_TextEntrySetFocusImage(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_TextEntry *) widget)->SetFocusImage(surface); } void GUI_TextEntrySetFocusCallback(GUI_Widget *widget, GUI_Callback *callback) { ((GUI_TextEntry *) widget)->SetFocusCallback(callback); } void GUI_TextEntrySetUnfocusCallback(GUI_Widget *widget, GUI_Callback *callback) { ((GUI_TextEntry *) widget)->SetUnfocusCallback(callback); } } <file_sep>/firmware/isoldr/loader/kos/net/udp.c /* KallistiOS ##version## net/udp.c Copyright (C)2004 <NAME> */ #include <main.h> #include "../../fs/net/include/commands.h" #include <kos/net.h> #include <net/net.h> // Table of command handler functions #define D(TYPE) { CMD_##TYPE, CMD_HANDLER_NAME(TYPE) } struct cmd_handler_item { const char * tag; cmd_handler_t hnd; } cmd_handlers[] = { D(EXEC), D(LBIN), D(PBIN), D(SBIN), { "SBIQ", CMD_HANDLER_NAME(SBIN) }, // deprecated D(DBIN), D(SREG), D(VERS), D(RETV), D(RBOT), D(PAUS), D(RSUM), D(TERM), D(CDTO), { NULL, NULL } }; void net_exec(ip_hdr_t * ip, udp_pkt_t * udp) { int i; for (i=0; cmd_handlers[i].tag; i++) { if (!memcmp(udp->data, cmd_handlers[i].tag, 4)) { cmd_handlers[i].hnd(ip, udp); return; } } } int net_udp_input(netif_t *src, uint8 *pkt, int pktsize) { // Find our packet pieces. ip_hdr_t * ip = (ip_hdr_t *)(pkt + sizeof(eth_hdr_t)); udp_pkt_t * udp = (udp_pkt_t *)(pkt + sizeof(eth_hdr_t) + 4 * (ip->version_ihl & 0x0f)); (void)src; (void)pktsize; // If the checksum is zero, it means there's no checksum. if (udp->checksum != 0) { // We have to build this "pseudo packet" to check the UDP checksum. int i; udp_pseudo_pkt_t * pseudo = (udp_pseudo_pkt_t *)(net_txbuf); pseudo->src_ip = ip->src; pseudo->dest_ip = ip->dest; pseudo->zero = 0; pseudo->protocol = ip->protocol; pseudo->udp_length = udp->length; pseudo->src_port = udp->src_port; pseudo->dest_port = udp->dest_port; pseudo->length = udp->length; pseudo->checksum = 0; memset(pseudo->data, 0, (ntohs(udp->length) - sizeof(udp_pkt_t)) + (ntohs(udp->length) % 2)); memcpy(pseudo->data, udp->data, ntohs(udp->length) - sizeof(udp_pkt_t)); i = net_checksum((uint16 *)pseudo, ( sizeof(udp_pseudo_pkt_t) + ntohs(udp->length) - sizeof(udp_pkt_t) ) / 2); // A stored checksum of 0xffff means it was really zero. if (udp->checksum == 0xffff) udp->checksum = 0; // Check it. if (i != udp->checksum) { //printf("bad udp checksum: %02x vs %02\n", i, udp->checksum); return 0; } } // Does it belong to us? if (ntohs(udp->dest_port) != 31313) return 0; // Note the host info net_host_ip = ntohl(ip->src); net_host_port = ntohs(udp->src_port); memcpy(net_host_mac, pkt + 6, 6); /*printf("received good udp packet: %c%c%c%c\n", udp->data[0], udp->data[1], udp->data[2], udp->data[3]);*/ // Find the handler and pass it off. net_exec(ip, udp); return 0; } <file_sep>/modules/gumbo/module.c /* DreamShell ##version## module.c - gumbo-parser module Copyright (C)2013 SWAT */ #include "ds.h" DEFAULT_MODULE_EXPORTS(gumbo); <file_sep>/include/gl/opengl.h /** Header for OpenGL module */ #ifndef DCE_OPENGL #define DCE_OPENGL #include <math.h> #include <dc/fmath.h> #include <dc/matrix.h> #include <dc/matrix3d.h> #include <dc/pvr.h> #include <dc/video.h> #define DEG2RAD (F_PI / 180.0f) #define RAD2DEG (180.0f / F_PI) typedef int vector2i[2]; typedef float vector2f[2]; typedef int vector3i[3]; typedef float vector3f[3]; typedef float vector4f[4]; typedef float matrix4f[4][4]; typedef unsigned int DWORD; typedef long LONG; typedef short BYTE; typedef unsigned short WORD; /* Primitive Types taken from GL for compatability */ #define GL_POINTS 0x01 #define GL_LINES 0x02 #define GL_LINE_LOOP 0x03 #define GL_LINE_STRIP 0x04 #define GL_TRIANGLES 0x05 #define GL_TRIANGLE_STRIP 0x06 #define GL_TRIANGLE_FAN 0x07 #define GL_QUADS 0x08 #define GL_QUAD_STRIP 0x09 #define GL_POLYGON 0x0A /* Matrix modes */ #define GL_MATRIX_MODE 0x0BA0 #define GL_SCREENVIEW 0x00 #define GL_MODELVIEW 0x01 #define GL_PROJECTION 0x02 #define GL_TEXTURE 0x03 #define GL_IDENTITY 0x04 #define GL_RENDER 0x05 #define GL_MATRIX_COUNT 0x04 /* "Depth buffer" -- we don't actually support a depth buffer because the PVR does all of that internally. But these constants are to ease porting. */ #define GL_NEVER 0x0200 #define GL_LESS 0x0201 #define GL_EQUAL 0x0202 #define GL_LEQUAL 0x0203 #define GL_GREATER 0x0204 #define GL_NOTEQUAL 0x0205 #define GL_GEQUAL 0x0206 #define GL_ALWAYS 0x0207 #define GL_DEPTH_TEST 0 #define GL_DEPTH_BITS 0 #define GL_DEPTH_CLEAR_VALUE 0 #define GL_DEPTH_FUNC 0 #define GL_DEPTH_RANGE 0 #define GL_DEPTH_WRITEMASK 0 #define GL_DEPTH_COMPONENT 0 /* Blending: not sure how we'll use these yet; the PVR supports a few of these so we'll want to eventually */ #define GL_BLEND 0x0BE2 /* capability bit */ #define GL_BLEND_SRC 2 #define GL_BLEND_DST 3 #define GL_ZERO 0 #define GL_ONE 1 #define GL_SRC_COLOR 0x0300 #define GL_ONE_MINUS_SRC_COLOR 0x0301 #define GL_SRC_ALPHA 0x0302 #define GL_ONE_MINUS_SRC_ALPHA 0x0303 #define GL_DST_ALPHA 0x0304 #define GL_ONE_MINUS_DST_ALPHA 0x0305 #define GL_DST_COLOR 0x0306 #define GL_ONE_MINUS_DST_COLOR 0x0307 /*#define GL_SRC_ALPHA_SATURATE 0x0308 unsupported */ /* Misc texture constants */ #define GL_TEXTURE_2D 0x0001 /* capability bit */ #define GL_KOS_AUTO_UV 0x8000 /* capability bit */ #define GL_TEXTURE_WRAP_S 0x2802 #define GL_TEXTURE_WRAP_T 0x2803 #define GL_TEXTURE_MAG_FILTER 0x2800 #define GL_TEXTURE_MIN_FILTER 0x2801 #define GL_TEXTURE_FILTER GL_TEXTURE_MIN_FILTER #define GL_FILTER_NONE 0 #define GL_FILTER_BILINEAR 1 #define GL_REPEAT 0x2901 #define GL_CLAMP 0x2900 /* Texture Environment */ #define GL_TEXTURE_ENV_MODE 0x2200 #define GL_REPLACE 0 #define GL_MODULATE 1 #define GL_DECAL 2 #define GL_MODULATEALPHA 3 /* TextureMagFilter */ #define GL_NEAREST 0x2600 #define GL_LINEAR 0x2601 /* Texture mapping */ #define GL_TEXTURE_ENV 0x2300 #define GL_TEXTURE_ENV_COLOR 0x2201 #define GL_NEAREST_MIPMAP_NEAREST 0x2700 #define GL_NEAREST_MIPMAP_LINEAR 0x2702 #define GL_LINEAR_MIPMAP_NEAREST 0x2701 #define GL_LINEAR_MIPMAP_LINEAR 0x2703 /* TextureUnit */ #define GL_TEXTURE0 0x84C0 #define GL_TEXTURE1 0x84C1 #define GL_TEXTURE2 0x84C2 #define GL_TEXTURE3 0x84C3 #define GL_TEXTURE4 0x84C4 #define GL_TEXTURE5 0x84C5 #define GL_TEXTURE6 0x84C6 #define GL_TEXTURE7 0x84C7 #define GL_TEXTURE8 0x84C8 #define GL_TEXTURE9 0x84C9 #define GL_TEXTURE10 0x84CA #define GL_TEXTURE11 0x84CB #define GL_TEXTURE12 0x84CC #define GL_TEXTURE13 0x84CD #define GL_TEXTURE14 0x84CE #define GL_TEXTURE15 0x84CF #define GL_TEXTURE16 0x84D0 #define GL_TEXTURE17 0x84D1 #define GL_TEXTURE18 0x84D2 #define GL_TEXTURE19 0x84D3 #define GL_TEXTURE20 0x84D4 #define GL_TEXTURE21 0x84D5 #define GL_TEXTURE22 0x84D6 #define GL_TEXTURE23 0x84D7 #define GL_TEXTURE24 0x84D8 #define GL_TEXTURE25 0x84D9 #define GL_TEXTURE26 0x84DA #define GL_TEXTURE27 0x84DB #define GL_TEXTURE28 0x84DC #define GL_TEXTURE29 0x84DD #define GL_TEXTURE30 0x84DE #define GL_TEXTURE31 0x84DF /* Misc bitfield things; we don't really use these either */ #define GL_COLOR_BUFFER_BIT 0 #define GL_DEPTH_BUFFER_BIT 0 /* Lighting constants */ #define GL_LIGHTING 0x0b50 #define GL_LIGHT0 0x0010 /* capability bit */ #define GL_LIGHT1 0x0000 #define GL_LIGHT2 0x0000 #define GL_LIGHT3 0x0000 #define GL_LIGHT4 0x0000 #define GL_LIGHT5 0x0000 #define GL_LIGHT6 0x0000 #define GL_LIGHT7 0x0000 #define GL_AMBIENT 0x1200 #define GL_DIFFUSE 0x1201 #define GL_SPECULAR 0 #define GL_SHININESS 0 #define GL_EMISSION 0 #define GL_POSITION 0x1203 #define GL_SHADE_MODEL 0x0b54 #define GL_FLAT 0x1d00 #define GL_SMOOTH 0x1d01 /* KOS near Z-CLIPPING */ #define GL_KOS_NEARZ_CLIPPING 0x0020 /* capability bit */ /* DCE-GL *********************************************************************/ #define GL_UNSIGNED_SHORT_5_6_5 PVR_TXRFMT_RGB565 #define GL_UNSIGNED_SHORT_5_6_5_REV PVR_TXRFMT_RGB565 #define GL_UNSIGNED_SHORT_1_5_5_5 PVR_TXRFMT_ARGB1555 #define GL_UNSIGNED_SHORT_1_5_5_5_REV PVR_TXRFMT_ARGB1555 #define GL_UNSIGNED_SHORT_4_4_4_4 PVR_TXRFMT_ARGB4444 #define GL_UNSIGNED_SHORT_4_4_4_4_REV PVR_TXRFMT_ARGB4444 #define GL_RED 0x00 #define GL_RG 0x01 #define GL_RGB 0x02 #define GL_BGR 0x03 #define GL_RGBA 0x04 #define GL_BGRA 0x05 #define GLint int #define GLfloat float #define GLdouble float #define GLvoid void #define GLuint unsigned int #define GLenum unsigned int #define GLsizei unsigned int #define GLfixed const unsigned int #define GLclampf float #define GLubyte unsigned short #define GLboolean int #define GL_FALSE 0 #define GL_TRUE 1 #define GL_DOUBLE 0xa0 #define GL_FLOAT 0xa0 #define GL_UNSIGNED_INT 0xa1 #define GL_RGB565_TWID PVR_TXRFMT_RGB565 | PVR_TXRFMT_TWIDDLED #define GL_ARGB4444_TWID PVR_TXRFMT_ARGB4444 | PVR_TXRFMT_TWIDDLED void glColor1ui( uint32 c ); void glColor3f( float r, float g, float b ); void glColor3fv( float * rgb ); void glColor4fv( float * rgba ); void glColor4f( float r, float g, float b,float a ); void glColor4ub( GLubyte a, GLubyte r, GLubyte g, GLubyte b ); void glTexCoord2f( float u, float v ); void glTexCoord2fv( float *uv ); void glVertex2f( float x, float y ); void glVertex2fv( float *xy ); void glVertex3f( float x, float y, float z ); void glVertex3fv( float *xyz ); void glNormal3f( float x, float y, float z ); void glGenTextures( GLsizei n, GLuint * textures ); void glKosTex2D( GLint internal_fmt, GLsizei width, GLsizei height, pvr_ptr_t txr_address ); void glTexImage2D( GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, GLvoid * data ); void glBindTexture( GLenum target, GLuint texture ); void glTexParameterf( GLenum target, GLenum pname, GLfloat param ); void glTexParameteri( GLenum target, GLenum pname, GLint param ); void glTexEnvf( GLenum target, GLenum pname, GLfloat param ); void glTexEnvi( GLenum target, GLenum pname, GLint param ); void glBlendFunc( GLenum sfactor, GLenum dfactor ); void glEnable( int mode ); void glDisable( int mode ); void glEnd(); void glBegin( int mode ); void glShadeModel( GLenum mode); void glDepthMask(GLboolean flag); void glDepthFunc(GLenum func); void glClearDepthf(GLfloat depth); #define glClearDepth glClearDepthf void glClearColor( GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha ); void glClear( int mode ); void glKosBeginFrame(); void glKosFinishFrame(); void glKosInit(); /* Transformation / Matrix Functions */ void glLoadIdentity(); void glMatrixMode( GLenum mode ); void glPushMatrix(); void glPopMatrix(); void glTranslatef( GLfloat x, GLfloat y, GLfloat z ); #define glTranslated glTranslatef void glScalef( GLfloat x, GLfloat y, GLfloat z ); #define glScaled glScalef void glRotatef( GLfloat angle, GLfloat x, GLfloat y, GLfloat z ); #define glRotated glRotatef void glOrtho(GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat znear, GLfloat zfar); void gluPerspective( GLfloat angle, GLfloat aspect, GLfloat znear, GLfloat zfar ); void gluLookAt(GLfloat eyex, GLfloat eyey, GLfloat eyez, GLfloat centerx, GLfloat centery, GLfloat centerz, GLfloat upx, GLfloat upy, GLfloat upz); void glDepthRange( GLclampf n, GLclampf f ); void glViewport( GLint x, GLint y, GLsizei width, GLsizei height ); void glFrustum( GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat znear, GLfloat zfar ); void glKosFinishList(); /* GL Array API */ void glVertexPointer( GLint size, GLenum type, GLsizei stride, const GLvoid * pointer ); void glTexCoordPointer( GLint size, GLenum type, GLsizei stride, const GLvoid * pointer ); void glColorPointer( GLint size, GLenum type, GLsizei stride, const GLvoid * pointer ); void glDrawArrays( GLenum mode, GLint first, GLsizei count ); #endif <file_sep>/lib/SDL_gui/Callback.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" extern "C" { int ds_printf(const char *fmt, ...); } GUI_Callback::GUI_Callback(const char *aname) : GUI_Object(aname) { //data = NULL; //freefunc = NULL; } /* GUI_Callback::GUI_Callback(const char *aname, GUI_CallbackFunction *ffunc, void *data) : GUI_Object(aname) { data = data; freefunc = ffunc; }*/ GUI_Callback::~GUI_Callback() { /* if(freefunc != NULL && data != NULL) { ds_printf("FREE: %p\n", data); freefunc(data); data = NULL; }*/ } GUI_Callback_C::GUI_Callback_C(GUI_CallbackFunction *func, GUI_CallbackFunction *ffunc, void *p) : GUI_Callback(NULL) { function = func; freefunc = ffunc; data = p; } GUI_Callback_C::~GUI_Callback_C() { if(freefunc != NULL && data != NULL) { //ds_printf("FREE_C: %p\n", data); freefunc(data); data = NULL; } } void GUI_Callback_C::Call(GUI_Object *object) { if (function) { IncRef(); // ds_printf("GUI_Callback_C::Call: %p %p\n", function, data); function(data); if(GetRef() == 1) { Trash(); } else { DecRef(); } } } extern "C" { GUI_Callback *GUI_CallbackCreate(GUI_CallbackFunction *function, GUI_CallbackFunction *freefunc, void *data) { return new GUI_Callback_C(function, freefunc, data); } void GUI_CallbackCall(GUI_Callback *callback) { callback->Call(0); } } <file_sep>/firmware/isoldr/loader/fs/net/commands.c /* KallistiOS ##version## slinkie/commands.c Copyright (C)2004 <NAME> */ #include "main.h" #include <kos/net.h> #include <net/net.h> #include "include/commands.h" extern int sl_mode; CMD_HANDLER(EXEC) { pkt_tas_t * req = (pkt_tas_t *)udp->data; pkt_tas_t * rsp; //uint32 addr = ntohl(req->addr); // Send an identical EXEC packet to ACK. rsp = (pkt_tas_t *)net_resp_build(); memcpy(rsp, req, sizeof(pkt_tas_t)); net_resp_complete(sizeof(pkt_tas_t)); //sl_exec_addr = addr; sl_mode = SLMODE_COOP; net_exit_loop = 1; } // We have to keep track of this info across multiple packets so we can // successfully complete an LBIN/PBIN^x/DBIN set. struct { uint8 * dst; // Address we're loading to uint32 size; // Amount of data we're reciving uint8 map[2048]; // Bit mask of received blocks } lbin_info; // Clear / init everything to defaults static void lbin_init(uint8 * ptr, uint32 size) { // Set our pointers lbin_info.dst = ptr; lbin_info.size = size; // Clear out the relevant part of the map size = (size + 8191) & ~8191; memset(lbin_info.map, 0, size / (8*1024)); } // Mark the block at ptr as received static void lbin_compl(uint8 * ptr) { // Where in the map is the current block? uint32 blid = ((uint32)(ptr - lbin_info.dst)) / 1024; // Set it received lbin_info.map[blid / 8] |= 1 << (blid % 8); } // Returns non-zero if the block at ptr is marked as received static int lbin_is_compl(uint8 * ptr) { // Where in the map is the current block? uint32 blid = ((uint32)(ptr - lbin_info.dst)) / 1024; return lbin_info.map[blid / 8] & (1 << (blid % 8)); } // Starts at the load pointer origin and searches for the next // block which still needs to be loaded. If we find one, we return // non-zero and set the values in *ptr and *size. static int lbin_find_hole(uint8 ** ptr, uint32 * size) { uint8 * dst; uint8 * dstend = lbin_info.dst + lbin_info.size; uint32 left; for (dst = lbin_info.dst; dst < dstend; dst += 1024) { if (!lbin_is_compl(dst)) { // Found a hole.. figure out how big it is. left = dstend - dst; // Send back the bad news. *ptr = dst; *size = left > 1024 ? 1024 : left; return 1; } } // No holes! return 0; } CMD_HANDLER(LBIN) { pkt_tas_t * req = (pkt_tas_t *)udp->data; pkt_tas_t * rsp; // Get all our pointers setup. uint8 * dst = (uint8 *)(ntohl(req->addr)); uint32 cnt = ntohl(req->size); //printf("LBIN: dst %p, cnt %d\n", dst, cnt); // Init our receive map lbin_init(dst, cnt); // Send back a copy of the LBIN as an ACK. rsp = (pkt_tas_t *)net_resp_build(); memcpy(rsp, req, sizeof(pkt_tas_t)); net_resp_complete(sizeof(pkt_tas_t)); } CMD_HANDLER(PBIN) { pkt_tas_t * req = (pkt_tas_t *)udp->data; // Get all our pointers setup. uint8 * dst = (uint8 *)(ntohl(req->addr)); uint32 cnt = ntohl(req->size); //printf("PBIN: dst %p, cnt %d\n", dst, cnt); // Copy the block out. memcpy(dst, req->data, cnt); // Set this block as received. lbin_compl(dst); } CMD_HANDLER(DBIN) { pkt_tas_t * req = (pkt_tas_t *)udp->data; pkt_tas_t * rsp; uint8 * hole; uint32 hole_size; // Build the response packet. rsp = (pkt_tas_t *)net_resp_build(); memcpy(rsp, req, sizeof(pkt_tas_t)); // Did we miss anything? if (lbin_find_hole(&hole, &hole_size)) { //printf("DBIN: need %p/%u\n", hole, hole_size); // Yes. Re-request it. rsp->addr = htonl((uint32)hole); rsp->size = htonl(hole_size); } else { //printf("DBIN: all fine\n"); // Nope. ACK it all. rsp->addr = rsp->size = 0; } // Send the ACK/NACK. net_resp_complete(sizeof(pkt_tas_t)); } CMD_HANDLER(SBIN) { pkt_tas_t * req = (pkt_tas_t *)udp->data; pkt_tas_t * rsp; // Get all our pointers setup. uint8 * src = (uint8 *)(ntohl(req->addr)); uint32 cnt = ntohl(req->size), now; //printf("SBIN: src %p, cnt %d\n", src, cnt); if ((ptr_t)src < 0x8c010000 || (ptr_t)src > 0x8d000000 || cnt > 16*1024*1024) { //printf("invalid request ignored!\n"); return; } // Build a skeleton response packet rsp = (pkt_tas_t *)net_resp_build(); memcpy(rsp->tag, CMD_SBIN, 4); // Send everything one packet at a time... while (cnt > 0) { // Update counters now = cnt > 1024 ? 1024 : cnt; rsp->addr = htonl((uint32)src); rsp->size = htonl(now); memcpy(rsp->data, src, now); net_resp_complete(sizeof(pkt_tas_t) + now); src += now; cnt -= now; } // Send a DBIN packet to signal completion memcpy(rsp->tag, CMD_DBIN, 4); rsp->addr = 0; rsp->size = 0; net_resp_complete(sizeof(pkt_tas_t)); } CMD_HANDLER(SREG) { } CMD_HANDLER(VERS) { //pkt_tas_t * req = (pkt_tas_t *)udp->data; pkt_tas_t * rsp; // Send back a VERS command with the appropriate info. rsp = (pkt_tas_t *)net_resp_build(); memcpy(rsp->tag, CMD_VERS, 4); rsp->addr = 0; rsp->size = 0; strcpy(rsp->data, VERSION); net_resp_complete(sizeof(pkt_tas_t) + strlen(VERSION) + 1); } CMD_HANDLER(RETV) { pkt_tas_t * req = (pkt_tas_t *)udp->data; pkt_tas_t * rsp; // Get the ret value net_rpc_ret = ntohl(req->addr); // Send an identical RETV packet to ACK. rsp = (pkt_tas_t *)net_resp_build(); memcpy(rsp, req, sizeof(pkt_tas_t)); net_resp_complete(sizeof(pkt_tas_t)); // We're done with the RPC. if (sl_mode == SLMODE_IMME) net_exit_loop = 1; } CMD_HANDLER(RBOT) { //int needquit = 0; //printf("exit requested\n"); net_exit_loop = 1; //if (sl_mode == SLMODE_COOP) //needquit = 1; sl_mode = SLMODE_NONE; //if (needquit) //exec_exit(); } CMD_HANDLER(PAUS) { } CMD_HANDLER(RSUM) { } CMD_HANDLER(TERM) { } CMD_HANDLER(CDTO) { } <file_sep>/include/drivers/aica.h /** * \file aica.h * \brief Definitions for AICA sound system * \date 2013-2014 * \author SWAT www.dc-swat.ru */ #ifndef _DS_AICA_H #define _DS_AICA_H /** * Sound memory start address (0x00800000 - 0x009FFFE0) */ #define AICA_DMA_ADSTAG *((vuint32 *)0xA05F7800) /** * System memory start address (0x0C000000 - 0x0FFFFFE0) */ #define AICA_DMA_ADSTAR *((vuint32 *)0xA05F7804) /** * Transfer size (32-byte aligned) * The setting of bit 31 enables DMA initiation (AICA_DMA_ADEN) when a DMA transfer ends. * 0x00000000 - Do not set DMA initiation setting to 0 * 0x80000000 - Set DMA initiation setting to 0 */ #define AICA_DMA_ADLEN *((vuint32 *)0xA05F7808) /** * Transfer direction * 0x00000000 - System memory to sound memory * 0x00000001 - Sound memory to system memory */ #define AICA_DMA_ADDIR *((vuint32 *)0xA05F780C) /** * DMA initiation method * 0x00000000 - Initiation by CPU * 0x00000002 - Initiation by IRQ * * The setting of bit 3 used for enabling/disabling suspend register */ #define AICA_DMA_ADTRG *((vuint32 *)0xA05F7810) /** * DMA operation * 0x00000000 - DMA enabled * 0x00000001 - DMA disabled */ #define AICA_DMA_ADEN *((vuint32 *)0xA05F7814) /** * DMA initiation by CPU * 0x00000000 - Nothing to do * 0x00000001 - Initiation of DMA */ #define AICA_DMA_ADST *((vuint32 *)0xA05F7818) /** * DMA suspend * 0x00000000 - Resume * 0x00000001 - Suspend */ #define AICA_DMA_ADSUSP *((vuint32 *)0xA05F781C) /** * DMA address counter on sound memory */ #define AICA_DMA_ADSTAGD *((vuint32 *)0xA05F78C0) /** * DMA address counter on system memory */ #define AICA_DMA_ADSTARD *((vuint32 *)0xA05F78C4) /** * DMA transfer counter */ #define AICA_DMA_ADLEND *((vuint32 *)0xA05F78C8) /** * System memory protection * (shared to other G2 devices too) */ #define AICA_DMA_G2APRO *((vuint32 *)0xA05F78BC) /** * System memory protection codes */ #define AICA_DMA_G2APRO_LOCK 0x46597F00 #define AICA_DMA_G2APRO_UNLOCK 0x4659007F /** * AICA macros */ #define SPU_RAM_BASE 0xA0800000 #define SNDREGADDR(x) (0xA0700000 + (x)) #define CHNREGADDR(ch, x) SNDREGADDR(0x80 * (ch) + (x)) #define SNDREG32(x) (*(vuint32 *)SNDREGADDR(x)) #define CHNREG32(ch, x) (*(vuint32 *)CHNREGADDR(ch, x)) /* Initialize AICA with custom firmware */ int snd_init_firmware(const char *filename); #endif /* _DS_AICA_H */ <file_sep>/modules/mp3/libmp3/libmp3/sndmp3_mpg123.c /* sndmp3_mpg123.c (c)2011 SWAT An MP3 player using sndstream and mpg123 */ /* This library is designed to be called from another program in a thread. It expects an input filename, and it will do all the setup and playback work. This requires a working math library for m4-single-only (such as newlib). */ #include <kos.h> #include <mp3/sndserver.h> #include <mp3/sndmp3.h> #include "config.h" #include "compat.h" #include "mpg123.h" /* Bitstream buffer: this is for input data */ //#define BS_SIZE (64*1024) #ifdef BS_SIZE #define BS_WATER (16*1024) /* 8 sectors */ static uint8 *bs_buffer = NULL, *bs_ptr; static int bs_count; static uint32 mp3_fd; #endif /* PCM buffer: for storing data going out to the SPU */ #define PCM_WATER 65536 /* Amt to send to the SPU */ #define PCM_SIZE (PCM_WATER+16384) /* Total buffer size */ static uint8 *pcm_buffer = NULL, *pcm_ptr; static int pcm_count, pcm_discard; static snd_stream_hnd_t stream_hnd = -1; /* MPEG file */ static mpg123_handle *mh; struct mpg123_frameinfo decinfo; static long rate; static int channels; /* Name of last played MP3 file */ static char mp3_last_fn[256]; #ifdef BS_SIZE /* Checks to make sure we have some data available in the bitstream buffer; if there's less than a certain "water level", shift the data back and bring in some more. */ static int bs_fill() { int n = 0; /* Get the current bitstream offset */ //off_t mp3pos = mpg123_tell_stream(mh); /* Make sure we don't underflow */ if (bs_count < 0) bs_count = 0; /* Pull in some more data if we need it */ if (bs_count < BS_WATER) { /* Shift everything back */ memcpy(bs_buffer, bs_ptr, bs_count); /* Read in some more data */ // printf("fs_read(%d,%x,%d)\r\n", mp3_fd, bs_buffer+bs_count, BS_SIZE - bs_count); n = fs_read(mp3_fd, bs_buffer+bs_count, BS_SIZE - bs_count); // printf("==%d\r\n", n); if (n <= 0) return -1; /* Shift pointers back */ bs_count += n; bs_ptr = bs_buffer; } /* Get the bitstream read size */ return n;//mpg123_tell_stream(mh) - mp3pos; } #endif /* Empties out the last (now-used) frame of data from the PCM buffer */ static int pcm_empty(int size) { if (pcm_count >= size) { /* Shift everything back */ memcpy(pcm_buffer, pcm_buffer + size, pcm_count - size); /* Shift pointers back */ pcm_count -= size; pcm_ptr = pcm_buffer + pcm_count; } return 0; } /* This callback is called each time the sndstream driver needs some more data. It will tell us how much it needs in bytes. */ static void* mpg123_callback(snd_stream_hnd_t hnd, int size, int * actual) { //static int frames = 0; size_t done = 0; int err = 0; #ifdef BS_SIZE /* Check for file not started or file finished */ if (mp3_fd == 0) return NULL; #endif /* Dump the last PCM packet */ pcm_empty(pcm_discard); /* Loop decoding until we have a full buffer */ while (pcm_count < size) { #ifdef BS_SIZE /* Pull in some more data (and check for EOF) */ if (bs_fill() < 0 || bs_count < decinfo.framesize) { printf("snd_mp3_server: Decode completed\r\n"); goto errorout; } err = mpg123_decode(mh, bs_ptr, decinfo.framesize, pcm_ptr, size, &done); #else err = mpg123_read(mh, pcm_ptr, size, &done); #endif switch(err) { case MPG123_DONE: printf("snd_mp3_server: Decode completed\r\n"); goto errorout; case MPG123_NEED_MORE: printf("snd_mp3_server: MPG123_NEED_MORE\n"); break; case MPG123_ERR: printf("snd_mp3_server: %s\n", (char*)mpg123_strerror(mh)); goto errorout; break; default: break; } #ifdef BS_SIZE bs_ptr += decinfo.framesize; bs_count -= decinfo.framesize; #endif pcm_ptr += done; pcm_count += done; //frames++; //if (!(frames % 64)) { //printf("Decoded %d frames \r", frames); //} } pcm_discard = *actual = size; /* Got it successfully */ return pcm_buffer; errorout: #ifdef BS_SIZE fs_close(mp3_fd); mp3_fd = 0; #endif return NULL; } /* Open an MPEG stream and prepare for decode */ static int libmpg123_init(const char *fn) { int err; uint32 fd; /* Open the file */ #ifdef BS_SIZE mp3_fd = fd = fs_open(fn, O_RDONLY); #else fd = fs_open(fn, O_RDONLY); #endif if (fd < 0) { printf("Can't open input file %s\r\n", fn); printf("getwd() returns '%s'\r\n", fs_getwd()); return -1; } #ifndef BS_SIZE fs_close(fd); #endif if (fn != mp3_last_fn) { if (fn[0] != '/') { strcpy(mp3_last_fn, fs_getwd()); strcat(mp3_last_fn, "/"); strcat(mp3_last_fn, fn); } else { strcpy(mp3_last_fn, fn); } } /* Allocate buffers */ if (pcm_buffer == NULL) pcm_buffer = malloc(PCM_SIZE); pcm_ptr = pcm_buffer; pcm_count = pcm_discard = 0; #ifdef BS_SIZE if (bs_buffer == NULL) bs_buffer = malloc(BS_SIZE); bs_ptr = bs_buffer; bs_count = 0; /* Fill bitstream buffer */ if (bs_fill() < 0) { printf("Can't read file header\r\n"); goto errorout; } /* Are we looking at a RIFF file? (stupid Windows encoders) */ if (bs_ptr[0] == 'R' && bs_ptr[1] == 'I' && bs_ptr[2] == 'F' && bs_ptr[3] == 'F') { /* Found a RIFF header, scan through it until we find the data section */ printf("Skipping stupid RIFF header\r\n"); while (bs_ptr[0] != 'd' || bs_ptr[1] != 'a' || bs_ptr[2] != 't' || bs_ptr[3] != 'a') { bs_ptr++; if (bs_ptr >= (bs_buffer + BS_SIZE)) { printf("Indeterminately long RIFF header\r\n"); goto errorout; } } /* Skip 'data' and length */ bs_ptr += 8; bs_count -= (bs_ptr - bs_buffer); printf("Final index is %d\r\n", (bs_ptr - bs_buffer)); } if (((uint8)bs_ptr[0] != 0xff) && (!((uint8)bs_ptr[1] & 0xe0))) { printf("Definitely not an MPEG file\r\n"); goto errorout; } #endif mpg123_init(); mh = mpg123_new(NULL, &err); if(mh == NULL) { printf("Can't init mpg123: %s\n", mpg123_strerror(mh)); goto errorout; } /* Open the MP3 context in open_fd mode */ #ifdef BS_SIZE err = mpg123_open_fd(mh, mp3_fd); #else err = mpg123_open(mh, fn); #endif if(err != MPG123_OK) { printf("Can't open mpg123\n"); mpg123_exit(); goto errorout; } int enc; mpg123_getformat(mh, &rate, &channels, &enc); mpg123_info(mh, &decinfo); printf("Output Sampling rate = %ld\r\n", decinfo.rate); printf("Output Bitrate = %d\r\n", decinfo.bitrate); printf("Output Frame size = %d\r\n", decinfo.framesize); printf("mpg123 initialized successfully\r\n"); return 0; errorout: printf("Exiting on error\r\n"); #ifdef BS_SIZE if (bs_buffer) { free(bs_buffer); bs_buffer = NULL; } #endif if (pcm_buffer) { free(pcm_buffer); pcm_buffer = NULL; } #ifdef BS_SIZE fs_close(fd); mp3_fd = 0; #endif return -1; } static void libmpg123_shutdown() { if(mh != NULL) { mpg123_close(mh); } mpg123_exit(); #ifdef BS_SIZE if (bs_buffer) { free(bs_buffer); bs_buffer = NULL; } #endif if (pcm_buffer) { free(pcm_buffer); pcm_buffer = NULL; } #ifdef BS_SIZE if (mp3_fd) { fs_close(mp3_fd); mp3_fd = 0; } #endif } /************************************************************************/ #include <dc/sound/stream.h> /* Status flag */ #define STATUS_INIT 0 #define STATUS_READY 1 #define STATUS_STARTING 2 #define STATUS_PLAYING 3 #define STATUS_STOPPING 4 #define STATUS_QUIT 5 #define STATUS_ZOMBIE 6 #define STATUS_REINIT 7 static volatile int sndmp3_status; /* Wait until the MP3 thread is started and ready */ void sndmp3_wait_start() { while (sndmp3_status != STATUS_READY) ; } /* Semaphore to halt sndmp3 until a command comes in */ static semaphore_t *sndmp3_halt_sem; /* Loop flag */ static volatile int sndmp3_loop; /* Call this function as a thread to handle playback. Playback will stop and this thread will return when you call sndmp3_shutdown(). */ static void sndmp3_thread() { int sj; stream_hnd = snd_stream_alloc(NULL, SND_STREAM_BUFFER_MAX); if(stream_hnd < 0) { printf("sndserver: can't alloc stream\r\n"); return; } /* Main command loop */ while(sndmp3_status != STATUS_QUIT) { switch(sndmp3_status) { case STATUS_INIT: sndmp3_status = STATUS_READY; break; case STATUS_READY: printf("sndserver: waiting on semaphore\r\n"); sem_wait(sndmp3_halt_sem); printf("sndserver: released from semaphore\r\n"); break; case STATUS_STARTING: /* Initialize streaming driver */ if (snd_stream_reinit(stream_hnd, mpg123_callback) < 0) { sndmp3_status = STATUS_READY; } else { snd_stream_start(stream_hnd, rate, channels - 1); sndmp3_status = STATUS_PLAYING; } break; case STATUS_REINIT: /* Re-initialize streaming driver */ snd_stream_reinit(stream_hnd, NULL); sndmp3_status = STATUS_READY; break; case STATUS_PLAYING: { sj = jiffies; if (snd_stream_poll(stream_hnd) < 0) { if (sndmp3_loop) { printf("sndserver: restarting '%s'\r\n", mp3_last_fn); if (libmpg123_init(mp3_last_fn) < 0) { sndmp3_status = STATUS_STOPPING; mp3_last_fn[0] = 0; } } else { printf("sndserver: not restarting\r\n"); snd_stream_stop(stream_hnd); sndmp3_status = STATUS_READY; mp3_last_fn[0] = 0; } // stream_start(); } else thd_sleep(50); break; } case STATUS_STOPPING: snd_stream_stop(stream_hnd); sndmp3_status = STATUS_READY; break; } } /* Done: clean up */ libmpg123_shutdown(); snd_stream_stop(stream_hnd); snd_stream_destroy(stream_hnd); sndmp3_status = STATUS_ZOMBIE; } /* Start playback (implies song load) */ int sndmp3_start(const char *fn, int loop) { /* Can't start again if already playing */ if (sndmp3_status == STATUS_PLAYING) return -1; /* Initialize MP3 engine */ if (fn) { if (libmpg123_init(fn) < 0) return -1; /* Set looping status */ sndmp3_loop = loop; } /* Wait for player thread to be ready */ while (sndmp3_status != STATUS_READY) thd_pass(); /* Tell it to start */ if (fn) sndmp3_status = STATUS_STARTING; else sndmp3_status = STATUS_REINIT; sem_signal(sndmp3_halt_sem); return 0; } /* Stop playback (implies song unload) */ void sndmp3_stop() { if (sndmp3_status == STATUS_READY) return; sndmp3_status = STATUS_STOPPING; while (sndmp3_status != STATUS_READY) thd_pass(); libmpg123_shutdown(); mp3_last_fn[0] = 0; } /* Shutdown the player */ void sndmp3_shutdown() { sndmp3_status = STATUS_QUIT; sem_signal(sndmp3_halt_sem); while (sndmp3_status != STATUS_ZOMBIE) thd_pass(); spu_disable(); } /* Adjust the MP3 volume */ void sndmp3_volume(int vol) { snd_stream_volume(stream_hnd, vol); } /* The main loop for the sound server */ void sndmp3_mainloop() { /* Allocate a semaphore for temporarily halting sndmp3 */ sndmp3_halt_sem = sem_create(0); /* Go into the main thread wait loop */ sndmp3_status=STATUS_INIT; sndmp3_thread(); /* Free the semaphore */ sem_destroy(sndmp3_halt_sem); } <file_sep>/lib/libparallax/src/texture.c /* Parallax for KallistiOS ##version## texture.c (c)2002 <NAME> (c)2013-2014 SWAT */ #include <assert.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <plx/texture.h> //#include <png/png.h> #include <jpeg/jpeg.h> #include <kmg/kmg.h> #include "utils.h" int pvr_to_img(const char *file_name, kos_img_t *rv); int png_to_img(const char *file_name, kos_img_t *rv); /* See the header file for all comments and documentation */ /* Utility function to fill out the initial poly contexts */ static void fill_contexts(plx_texture_t * txr) { pvr_poly_cxt_txr(&txr->cxt_opaque, PVR_LIST_OP_POLY, txr->fmt, txr->w, txr->h, txr->ptr, PVR_FILTER_BILINEAR); pvr_poly_cxt_txr(&txr->cxt_trans, PVR_LIST_TR_POLY, txr->fmt, txr->w, txr->h, txr->ptr, PVR_FILTER_BILINEAR); pvr_poly_cxt_txr(&txr->cxt_pt, PVR_LIST_PT_POLY, txr->fmt, txr->w, txr->h, txr->ptr, PVR_FILTER_BILINEAR); plx_txr_flush_hdrs(txr); } plx_texture_t * plx_txr_load(const char * fn, int use_alpha, int txrload_flags) { kos_img_t img; plx_texture_t * txr; int fnlen; /* What type of texture is it? */ fnlen = strlen(fn); if (!strcasecmp(fn + fnlen - 3, "png")) { /* Load the texture (or try) */ if (png_to_img(fn, &img) < 0) { dbglog(DBG_WARNING, "plx_txr_load: can't load texture from file '%s'\n", fn); return NULL; } } else if (!strcasecmp(fn + fnlen - 3, "jpg")) { /* Load the texture (or try) */ if (jpeg_to_img(fn, 1, &img) < 0) { dbglog(DBG_WARNING, "plx_txr_load: can't load texture from file '%s'\n", fn); return NULL; } } else if (!strcasecmp(fn + fnlen - 3, "kmg")) { /* Load the texture (or try) */ if (kmg_to_img(fn, &img) < 0) { dbglog(DBG_WARNING, "plx_txr_load: can't load texture from file '%s'\n", fn); return NULL; } use_alpha = -1; } else if (!strcasecmp(fn + fnlen - 3, "pvr")) { /* Load the texture (or try) */ if (pvr_to_img(fn, &img) < 0) { dbglog(DBG_WARNING, "plx_txr_load: can't load texture from file '%s'\n", fn); return NULL; } } else { dbglog(DBG_WARNING, "plx_txr_load: unknown extension for file '%s'\n", fn); return NULL; } /* We got it -- allocate a texture struct */ txr = malloc(sizeof(plx_texture_t)); if (txr == NULL) { dbglog(DBG_WARNING, "plx_txr_load: can't allocate memory for texture struct for '%s'\n", fn); kos_img_free(&img, 0); return NULL; } /* Setup the struct */ txr->ptr = pvr_mem_malloc(img.byte_count); txr->w = img.w; txr->h = img.h; if (use_alpha == -1) { /* Pull from the image source */ switch (KOS_IMG_FMT_I(img.fmt) & KOS_IMG_FMT_MASK) { case KOS_IMG_FMT_RGB565: txr->fmt = PVR_TXRFMT_RGB565; break; case KOS_IMG_FMT_ARGB4444: txr->fmt = PVR_TXRFMT_ARGB4444; break; case KOS_IMG_FMT_ARGB1555: txr->fmt = PVR_TXRFMT_ARGB1555; break; default: /* shrug */ dbglog(DBG_WARNING, "plx_txr_load: unknown format '%x'\n", (int)(KOS_IMG_FMT_I(img.fmt) & KOS_IMG_FMT_MASK)); txr->fmt = PVR_TXRFMT_RGB565; break; } } else { txr->fmt = use_alpha ? PVR_TXRFMT_ARGB4444 : PVR_TXRFMT_RGB565; } if (KOS_IMG_FMT_D(img.fmt) & PVR_TXRLOAD_FMT_VQ) txr->fmt |= PVR_TXRFMT_VQ_ENABLE; /* Did we actually get the memory? */ if (txr->ptr == NULL) { dbglog(DBG_WARNING, "plx_txr_load: can't allocate texture ram for '%s'\n", fn); kos_img_free(&img, 0); free(txr); return NULL; } /* Load it up and twiddle it */ pvr_txr_load_kimg(&img, txr->ptr, txrload_flags); kos_img_free(&img, 0); /* Setup the poly context structs */ fill_contexts(txr); return txr; } plx_texture_t * plx_txr_canvas(int w, int h, int fmt) { plx_texture_t * txr; /* Allocate a texture struct */ txr = malloc(sizeof(plx_texture_t)); if (txr == NULL) { dbglog(DBG_WARNING, "plx_txr_canvas: can't allocate memory for %dx%d canvas texture\n", w, h); return NULL; } /* Setup the struct */ txr->ptr = pvr_mem_malloc(w * h * 2); txr->w = w; txr->h = h; txr->fmt = fmt; /* Did we actually get the memory? */ if (txr->ptr == NULL) { dbglog(DBG_WARNING, "plx_txr_canvas: can't allocate texture ram for %dx%d canvas texture\n", w, h); free(txr); return NULL; } /* Setup the poly context structs */ fill_contexts(txr); return txr; } void plx_txr_destroy(plx_texture_t * txr) { assert( txr != NULL ); if (txr == NULL) return; if (txr->ptr != NULL) { /* Free the PVR memory */ pvr_mem_free(txr->ptr); } /* Free the struct itself */ free(txr); } void plx_txr_setfilter(plx_texture_t * txr, int mode) { assert( txr != NULL ); if (txr == NULL) return; txr->cxt_opaque.txr.filter = mode; txr->cxt_trans.txr.filter = mode; txr->cxt_pt.txr.filter = mode; plx_txr_flush_hdrs(txr); } void plx_txr_setuvclamp(plx_texture_t * txr, int umode, int vmode) { int mode; assert( txr != NULL ); if (txr == NULL) return; if (umode == PLX_UV_REPEAT && vmode == PLX_UV_REPEAT) mode = PVR_UVCLAMP_NONE; else if (umode == PLX_UV_REPEAT && vmode == PLX_UV_CLAMP) mode = PVR_UVCLAMP_V; else if (umode == PLX_UV_CLAMP && vmode == PLX_UV_REPEAT) mode = PVR_UVCLAMP_U; else if (umode == PLX_UV_CLAMP && vmode == PLX_UV_CLAMP) mode = PVR_UVCLAMP_UV; else { assert_msg( 0, "Invalid UV clamp mode" ); mode = PVR_UVCLAMP_NONE; } txr->cxt_opaque.txr.uv_clamp = mode; txr->cxt_trans.txr.uv_clamp = mode; txr->cxt_pt.txr.uv_clamp = mode; plx_txr_flush_hdrs(txr); } void plx_txr_flush_hdrs(plx_texture_t * txr) { assert( txr != NULL ); if (txr == NULL) return; pvr_poly_compile(&txr->hdr_opaque, &txr->cxt_opaque); pvr_poly_compile(&txr->hdr_trans, &txr->cxt_trans); pvr_poly_compile(&txr->hdr_pt, &txr->cxt_pt); } void plx_txr_send_hdr(plx_texture_t * txr, int list, int flush) { assert( txr != NULL ); if (txr == NULL) return; /* Flush the poly hdrs if necessary */ if (flush) plx_txr_flush_hdrs(txr); /* Figure out which list to send for */ switch (list) { case PVR_LIST_OP_POLY: pvr_prim(&txr->hdr_opaque, sizeof(txr->hdr_opaque)); break; case PVR_LIST_TR_POLY: pvr_prim(&txr->hdr_trans, sizeof(txr->hdr_trans)); break; case PVR_LIST_PT_POLY: pvr_prim(&txr->hdr_pt, sizeof(txr->hdr_pt)); break; default: assert_msg( 0, "Invalid list specification" ); } } <file_sep>/lib/SDL_gui/AbstractButton.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_AbstractButton::GUI_AbstractButton(const char *aname, int x, int y, int w, int h) : GUI_Widget(aname, x, y, w, h) { SetTransparent(1); caption = 0; caption2 = 0; click = 0; context_click = 0; hover = 0; unhover = 0; wtype = WIDGET_TYPE_BUTTON; } GUI_AbstractButton::~GUI_AbstractButton() { if (caption) caption->DecRef(); if (caption2) caption2->DecRef(); if (click) click->DecRef(); if (context_click) context_click->DecRef(); if (hover) hover->DecRef(); if (unhover) unhover->DecRef(); } GUI_Surface *GUI_AbstractButton::GetCurrentImage() { return 0; } void GUI_AbstractButton::Update(int force) { if (parent==0) return; if (force) { GUI_Surface *surface = GetCurrentImage(); SDL_Rect src; src.x = src.y = 0; src.w = area.w; src.h = area.h; if (flags & WIDGET_TRANSPARENT) parent->Erase(&area); if (surface) parent->Draw(surface, &src, &area); } if (caption) caption->DoUpdate(force); if (caption2) caption2->DoUpdate(force); } void GUI_AbstractButton::Fill(const SDL_Rect *dr, SDL_Color c) { } void GUI_AbstractButton::Erase(const SDL_Rect *dr) { /* SDL_Rect d; d.w = dr->w; d.h = dr->h; d.x = area.x + dr->x; d.y = area.x + dr->y; parent->Erase(&d); */ } void GUI_AbstractButton::Notify(int mask) { MarkChanged(); GUI_Drawable::Notify(mask); } void GUI_AbstractButton::Clicked(int x, int y) { if (click) click->Call(this); } void GUI_AbstractButton::ContextClicked(int x, int y) { if (context_click) context_click->Call(this); } void GUI_AbstractButton::Highlighted(int x, int y) { if (hover) hover->Call(this); } void GUI_AbstractButton::unHighlighted(int x, int y) { if (unhover) unhover->Call(this); } void GUI_AbstractButton::RemoveWidget(GUI_Widget *widget) { if (widget == caption) Keep(&caption, NULL); if (widget == caption2) Keep(&caption2, NULL); } void GUI_AbstractButton::SetCaption(GUI_Widget *widget) { Keep(&caption, widget); } void GUI_AbstractButton::SetCaption2(GUI_Widget *widget) { Keep(&caption2, widget); } GUI_Widget *GUI_AbstractButton::GetCaption() { return caption; } GUI_Widget *GUI_AbstractButton::GetCaption2() { return caption2; } void GUI_AbstractButton::SetClick(GUI_Callback *callback) { GUI_ObjectKeep((GUI_Object **) &click, callback); } void GUI_AbstractButton::SetContextClick(GUI_Callback *callback) { GUI_ObjectKeep((GUI_Object **) &context_click, callback); } void GUI_AbstractButton::SetMouseover(GUI_Callback *callback) { GUI_ObjectKeep((GUI_Object **) &hover, callback); } void GUI_AbstractButton::SetMouseout(GUI_Callback *callback) { GUI_ObjectKeep((GUI_Object **) &unhover, callback); } <file_sep>/include/drivers/enc28j60.h /* DreamShell ##version## drivers/enc28j60.h Copyright (C) 2011-2014 SWAT */ #ifndef ENC28J60_H #define ENC28J60_H #include <arch/types.h> /** * \file * enc28j60 driver * * \author SWAT */ /** * \internal * Initializes the SPI interface to the ENC28J60 chip. * * \param[in] cs The SPI chip select pin. * \param[in] cs The SPI reset pin. */ void enc28j60_io_init(int cs, int rs); /** * \internal * Forces a reset to the ENC28J60. * * After the reset a reinitialization is necessary. */ void enc28j60_reset(); /** * \internal * Reads the value of a hardware register. * * \param[in] address The address of the register to read. * \returns The register value. */ uint8 enc28j60_read(uint8 address); /** * \internal * Writes the value of a hardware register. * * \param[in] address The address of the register to write. * \param[in] value The value to write into the register. */ void enc28j60_write(uint8 address, uint8 value); /** * \internal * Clears bits in a hardware register. * * Performs a NAND operation on the current register value * and the given bitmask. * * \param[in] address The address of the register to alter. * \param[in] bits A bitmask specifiying the bits to clear. */ void enc28j60_clear_bits(uint8 address, uint8 bits); /** * \internal * Sets bits in a hardware register. * * Performs an OR operation on the current register value * and the given bitmask. * * \param[in] address The address of the register to alter. * \param[in] bits A bitmask specifiying the bits to set. */ void enc28j60_set_bits(uint8 address, uint8 bits); /** * \internal * Reads the value of a hardware PHY register. * * \param[in] address The address of the PHY register to read. * \returns The register value. */ uint16 enc28j60_read_phy(uint8 address); /** * \internal * Writes the value to a hardware PHY register. * * \param[in] address The address of the PHY register to write. * \param[in] value The value to write into the register. */ void enc28j60_write_phy(uint8 address, uint16 value); /** * \internal * Reads a byte from the RAM buffer at the current position. * * \returns The byte read from the current RAM position. */ uint8 enc28j60_read_buffer_byte(); /** * \internal * Writes a byte to the RAM buffer at the current position. * * \param[in] b The data byte to write. */ void enc28j60_write_buffer_byte(uint8 b); /** * \internal * Reads multiple bytes from the RAM buffer. * * \param[out] buffer A pointer to the buffer which receives the data. * \param[in] buffer_len The buffer length and number of bytes to read. */ void enc28j60_read_buffer(uint8* buffer, uint16 buffer_len); /** * \internal * Writes multiple bytes to the RAM buffer. * * \param[in] buffer A pointer to the buffer containing the data to write. * \param[in] buffer_len The number of bytes to write. */ void enc28j60_write_buffer(const uint8* buffer, uint16 buffer_len); /** * Switches the hardware register bank. * * \param[in] num The index of the register bank to switch to. */ void enc28j60_bank(uint8 num); /** * Reset and initialize the ENC28J60 and starts packet transmission/reception. * * \param[in] mac A pointer to a 6-byte buffer containing the MAC address. * \returns \c true on success, \c false on failure. */ int enc28j60_init(const uint8* mac); /** * Fetches a pending packet from the RAM buffer of the ENC28J60. * * The packet is written into the given buffer and the size of the packet * (ethernet header plus payload, exclusive the CRC) is returned. * * Zero is returned in the following cases: * - There is no packet pending. * - The packet is too large to completely fit into the buffer. * - Some error occured. * * \param[out] buffer The pointer to the buffer which receives the packet. * \param[in] buffer_len The length of the buffer. * \returns The packet size in bytes on success, \c 0 in the cases noted above. */ uint16 enc28j60_receive_packet(uint8* buffer, uint16 buffer_len); /** * Writes a packet to the RAM buffer of the ENC28J60 and starts transmission. * * The packet buffer contains the ethernet header and the payload without CRC. * The checksum is automatically generated by the on-chip calculator. * * \param[in] buffer A pointer to the buffer containing the packet to be sent. * \param[in] buffer_len The length of the ethernet packet header plus payload. * \returns \c true if the packet was sent, \c false otherwise. */ int enc28j60_send_packet(const uint8* buffer, uint16 buffer_len); /** * Initialize network interface * * \param[in] cs The SPI chip select pin. * \param[in] cs The SPI reset pin. * \returns \c true if initialized, \c false otherwise. */ int enc28j60_if_init(int cs, int rs); /** * Shutdown network interface * * \returns \c true if shutdown success, \c false otherwise. */ int enc28j60_if_shutdown(); #endif /* ENC28J60_H */ <file_sep>/modules/luaSQL/module.c /* DreamShell ##version## module.c - luaSQL module Copyright (C)2007-2014 SWAT */ #include <kos.h> #include <kos/exports.h> #include "ds.h" DEFAULT_MODULE_HEADER(luaSQL); int luaopen_luasql_sqlite3(lua_State *L); int lib_open(klibrary_t * lib) { luaopen_luasql_sqlite3(GetLuaState()); RegisterLuaLib(lib_get_name(), (LuaRegLibOpen *)luaopen_luasql_sqlite3); return nmmgr_handler_add(&ds_luaSQL_hnd.nmmgr); } int lib_close(klibrary_t * lib) { UnregisterLuaLib(lib_get_name()); return nmmgr_handler_remove(&ds_luaSQL_hnd.nmmgr); } <file_sep>/lib/SDL_gui/ListBox.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_ListBox::GUI_ListBox(const char *aname, int x, int y, int w, int h, GUI_Font *afont) : GUI_AbstractTable(aname, x, y, w, h), font(afont) { item_count = 0; item_max = 16; items = new char *[item_max]; font->IncRef(); textcolor.r = 255; textcolor.g = 255; textcolor.b = 255; } GUI_ListBox::~GUI_ListBox() { int i; for (i=0; i<item_count; i++) delete items[i]; delete [] items; font->DecRef(); } int GUI_ListBox::GetRowCount(void) { return item_count; } int GUI_ListBox::GetRowSize(int row) { SDL_Rect r = font->GetTextSize("X"); return r.h; } int GUI_ListBox::GetColumnCount(void) { return 1; } int GUI_ListBox::GetColumnSize(int column) { return area.w; } void GUI_ListBox::SetFont(GUI_Font *afont) { if (GUI_ObjectKeep((GUI_Object **) &font, afont)) MarkChanged(); } void GUI_ListBox::SetTextColor(int r, int g, int b) { textcolor.r = r; textcolor.g = g; textcolor.b = b; MarkChanged(); } void GUI_ListBox::DrawCell(int column, int row, const SDL_Rect *r) { GUI_Surface *image = font->RenderQuality(items[row], textcolor); SDL_Rect sr; sr.x = sr.y = 0; sr.w = image->GetWidth(); sr.h = image->GetHeight(); SDL_Rect dr = *r; dr.w = sr.w; dr.h = sr.h; Draw(image, &sr, &dr); image->DecRef(); } void GUI_ListBox::AddItem(const char *s) { if (item_count == item_max) { item_max += 16; char **newitems = new char *[item_max]; int i; for (i=0; i<item_count; i++) newitems[i] = items[i]; delete [] items; items = newitems; } char *buffer = items[item_count++] = new char[strlen(s)+1]; strcpy(buffer, s); } void GUI_ListBox::RemoveItem(int n) { if (n >= 0 && n < item_count) { delete items[n]; item_count--; while (n<item_count) { items[n] = items[n+1]; n++; } } } extern "C" { GUI_ListBox *GUI_CreateListBox(const char *aname, int x, int y, int w, int h, GUI_Font *afont) { return new GUI_ListBox(aname, x, y, w, h, afont); } int GUI_ListBoxGetRowCount(GUI_ListBox *list) { return list->GetRowCount(); } int GUI_ListBoxGetRowSize(GUI_ListBox *list, int row) { return list->GetRowSize(row); } int GUI_ListBoxGetColumnCount(GUI_ListBox *list) { return list->GetColumnCount(); } int GUI_ListBoxGetColumnSize(GUI_ListBox *list, int column) { return list->GetColumnSize(column); } void GUI_ListBoxSetFont(GUI_ListBox *list, GUI_Font *afont) { list->SetFont(afont); } void GUI_ListBoxSetTextColor(GUI_ListBox *list, int r, int g, int b) { list->SetTextColor(r, g, b); } void GUI_ListBoxDrawCell(GUI_ListBox *list, int column, int row, const SDL_Rect *r) { list->DrawCell(column, row, r); } void GUI_ListBoxAddItem(GUI_ListBox *list, const char *s) { list->AddItem(s); } void GUI_ListBoxRemoveItem(GUI_ListBox *list, int n) { list->RemoveItem(n); } } <file_sep>/firmware/bootloader/src/spiral.c /** * DreamShell boot loader * Spiral * (c)2011-2016 SWAT <http://www.dc-swat.ru> */ #include "main.h" static pvr_ptr_t txr_dot, txr_logo; static float phase; static int frame; uint32 spiral_color = 0x44ed1800; static int gzip_kmg_to_img(const char * fn, kos_img_t * rv) { gzFile f; kmg_header_t hdr; /* Open the file */ f = gzopen(fn, "r"); if (f == NULL) { dbglog(DBG_ERROR, "%s: can't open file '%s'\n", __func__, fn); return -1; } /* Read the header */ if (gzread(f, &hdr, sizeof(hdr)) != sizeof(hdr)) { gzclose(f); dbglog(DBG_ERROR, "%s: can't read header from file '%s'\n", __func__, fn); return -2; } /* Verify a few things */ if (hdr.magic != KMG_MAGIC || hdr.version != KMG_VERSION || hdr.platform != KMG_PLAT_DC) { gzclose(f); dbglog(DBG_ERROR, "%s: file '%s' is incompatible:\n" " magic %08lx version %d platform %d\n", __func__, fn, hdr.magic, (int)hdr.version, (int)hdr.platform); return -3; } /* Setup the kimg struct */ rv->w = hdr.width; rv->h = hdr.height; rv->byte_count = hdr.byte_count; rv->data = malloc(hdr.byte_count); if (!rv->data) { dbglog(DBG_ERROR, "%s: can't malloc(%d) while loading '%s'\n", __func__, (int)hdr.byte_count, fn); gzclose(f); return -4; } int dep = 0; if (hdr.format & KMG_DCFMT_VQ) dep |= PVR_TXRLOAD_FMT_VQ; if (hdr.format & KMG_DCFMT_TWIDDLED) dep |= PVR_TXRLOAD_FMT_TWIDDLED; switch (hdr.format & KMG_DCFMT_MASK) { case KMG_DCFMT_RGB565: rv->fmt = KOS_IMG_FMT(KOS_IMG_FMT_RGB565, dep); break; case KMG_DCFMT_ARGB4444: rv->fmt = KOS_IMG_FMT(KOS_IMG_FMT_ARGB4444, dep); break; case KMG_DCFMT_ARGB1555: rv->fmt = KOS_IMG_FMT(KOS_IMG_FMT_ARGB1555, dep); break; case KMG_DCFMT_YUV422: rv->fmt = KOS_IMG_FMT(KOS_IMG_FMT_YUV422, dep); break; case KMG_DCFMT_BUMP: /* XXX */ rv->fmt = KOS_IMG_FMT(KOS_IMG_FMT_RGB565, dep); break; case KMG_DCFMT_4BPP_PAL: case KMG_DCFMT_8BPP_PAL: default: dbglog(DBG_ERROR, "%s: currently-unsupported KMG pixel format", __func__); gzclose(f); free(rv->data); return -5; } if (gzread(f, rv->data, rv->byte_count) != rv->byte_count) { dbglog(DBG_ERROR, "%s: can't read %d bytes while loading '%s'\n", __func__, (int)hdr.byte_count, fn); gzclose(f); free(rv->data); return -6; } /* Ok, all done */ gzclose(f); /* If the byte count is not a multiple of 32, bump it up as well. This is for DMA/SQ usage. */ rv->byte_count = (rv->byte_count + 31) & ~31; return 0; } static void load_txr(const char *fn, pvr_ptr_t *txr) { char path[NAME_MAX]; sprintf(path, "%s/%s", RES_PATH, fn); kos_img_t img; if (gzip_kmg_to_img(path, &img) < 0) assert(0); dbglog(DBG_INFO, "Loaded %s: %dx%d, format %d\n", path, (int)img.w, (int)img.h, (int)img.fmt); assert((img.fmt & KOS_IMG_FMT_MASK) == KOS_IMG_FMT_ARGB4444); *txr = pvr_mem_malloc(img.w * img.h * 2); pvr_txr_load_kimg(&img, *txr, 0); //kos_img_free(&img, 0); } static void draw_one_dot(float x, float y, float z) { pvr_vertex_t v; v.flags = PVR_CMD_VERTEX; v.x = x-32.0/2; v.y = y+32.0/2; v.z = z; v.u = 0.0f; v.v = 1.0f; v.argb = spiral_color; v.oargb = 0; pvr_prim(&v, sizeof(v)); v.y = y-32.0/2; v.v = 0.0f; pvr_prim(&v, sizeof(v)); v.x = x+32.0/2; v.y = y+32.0/2; v.u = 1.0f; v.v = 1.0f; pvr_prim(&v, sizeof(v)); v.flags = PVR_CMD_VERTEX_EOL; v.y = y-32.0/2; v.v = 0.0f; pvr_prim(&v, sizeof(v)); } static void draw_spiral(float phase) { pvr_poly_hdr_t hdr; pvr_poly_cxt_t cxt; float x, y, t, r, z, scale; pvr_poly_cxt_txr(&cxt, PVR_LIST_TR_POLY, PVR_TXRFMT_ARGB4444, 32, 32, txr_dot, PVR_FILTER_BILINEAR); pvr_poly_compile(&hdr, &cxt); pvr_prim(&hdr, sizeof(hdr)); for (z=1.0f, r=15.0, t=M_PI/2 - M_PI/4 + phase; t<(6*M_PI+phase); ) { x = r*fcos(t); y = r*fsin(t); draw_one_dot(320 + x, 189 + y, z); scale = 12.0f - 11.0f * ((t-phase) / (6*M_PI)); t+=scale*2*M_PI/360.0; r+=scale*0.6f/(2*M_PI); z+=0.1f; } } static float _y = 235.0f; static void draw_logo() { pvr_poly_hdr_t hdr; pvr_poly_cxt_t cxt; pvr_vertex_t v; float x, y; pvr_poly_cxt_txr(&cxt, PVR_LIST_TR_POLY, PVR_TXRFMT_ARGB4444, 1024, 512, txr_logo, PVR_FILTER_BILINEAR); pvr_poly_compile(&hdr, &cxt); pvr_prim(&hdr, sizeof(hdr)); x = 810.0f; y = _y; v.flags = PVR_CMD_VERTEX; v.x = x - 1024.0f; v.y = y + 512.0f; v.z = 0.1f; v.u = 0.0f; v.v = 1.0f; v.argb = 0xffffffff; v.oargb = 0; pvr_prim(&v, sizeof(v)); v.y = y; v.v = 0.0f; pvr_prim(&v, sizeof(v)); v.x = x; v.y = y + 512.0f; v.u = 1.0f; v.v = 1.0f; pvr_prim(&v, sizeof(v)); v.flags = PVR_CMD_VERTEX_EOL; v.y = y; v.v = 0.0f; pvr_prim(&v, sizeof(v)); if(_y > 53.5f) { _y -= M_PI * fcos(frame * M_PI / 180.0f); //printf("Y = %f\n", _y); } } int spiral_init() { load_txr("dot.kmg.gz", &txr_dot); load_txr("DreamShell.kmg.gz", &txr_logo); phase = 0.0f; frame = 0; return 0; } /* Call during trans poly */ void spiral_frame() { draw_spiral(phase); draw_logo(); frame++; if(frame > 360) frame = 0; phase = 2*M_PI * fsin(frame * 2*M_PI / 360.0f); } <file_sep>/firmware/isoldr/loader/dcload.c /* * DreamShell ISO Loader * dcload support * (c)2009-2022 SWAT <http://www.dc-swat.ru> */ #include <main.h> #include <dcload.h> #include <exception.h> #include <arch/irq.h> #ifdef HAVE_IRQ #define dclsc(...) ({ \ int rv, old; \ if (!exception_inside_int()) { \ old = irq_disable(); \ } \ do {} while ((*(vuint32 *)0xa05f688c) & 0x20); \ rv = dcloadsyscall(__VA_ARGS__); \ if (!exception_inside_int()) \ irq_restore(old); \ rv; \ }) #else #define dclsc(...) ({ \ int rv, old; \ old = irq_disable(); \ do {} while ((*(vuint32 *)0xa05f688c) & 0x20); \ rv = dcloadsyscall(__VA_ARGS__); \ irq_restore(old); \ rv; \ }) #endif /* Printk replacement */ int dcload_write_buffer(const uint8 *data, int len) { return dclsc(DCLOAD_WRITE, 1, data, len); } int dcload_reinit() { return dclsc(DCLOAD_REINIT, 0, 0, 0); } #ifdef HAVE_GDB size_t dcload_gdbpacket(const char* in_buf, size_t in_size, char* out_buf, size_t out_size) { /* we have to pack the sizes together because the dcloadsyscall handler can only take 4 parameters */ return dclsc(DCLOAD_GDBPACKET, in_buf, (in_size << 16) | (out_size & 0xffff), out_buf); } #endif int dcload_type = DCLOAD_TYPE_NONE; int dcload_init() { if(*DCLOADMAGICADDR != DCLOADMAGICVALUE) { return -1; } dcload_reinit(); /* Give dcload the 64k it needs to compress data (if on serial) */ if(dclsc(DCLOAD_ASSIGNWRKMEM, NULL) == -1) { dcload_type = DCLOAD_TYPE_IP; printf("dc-load-ip initialized\n"); } else { dcload_type = DCLOAD_TYPE_SER; printf("dc-load-serial initialized\n"); } return 0; } <file_sep>/src/console.c /**************************** * DreamShell ##version## * * console.c * * DreamShell console * * Created by SWAT * * http://www.dc-swat.ru * ***************************/ #include "ds.h" #include "video.h" #include "console.h" #include <arch/spinlock.h> //#define CONSOLE_DEBUG 1 static ConsoleInformation *DSConsole = NULL; static Event_t *con_input_event; static Event_t *con_video_event; static int console_debug = 0; static char printf_buf[1024]; static spinlock_t lock = SPINLOCK_INITIALIZER; void SetConsoleDebug(int mode) { spinlock_lock(&lock); console_debug = mode; spinlock_unlock(&lock); } int ds_printf(const char *fmt, ...) { char *ptemp, *b, *cr; va_list args; int i; if(!irq_inside_int()) { spinlock_lock(&lock); } va_start(args, fmt); i = vsnprintf(printf_buf, sizeof(printf_buf), fmt, args); va_end(args); if(console_debug) { dbglog(DBG_DEBUG, printf_buf); } if(DSConsole != NULL) { ptemp = printf_buf; if(ConsoleIsVisible()) { SetEventState(con_video_event, EVENT_STATE_SLEEP); } while((b = strsep(&ptemp, "\n")) != NULL) { while(strlen(b) > DSConsole->VChars) { CON_NewLineConsole(DSConsole); strncpy(DSConsole->ConsoleLines[0], b, DSConsole->VChars); DSConsole->ConsoleLines[0][DSConsole->VChars] = '\0'; b = &b[DSConsole->VChars]; } cr = b + strlen(b) - 1; if(*cr != '\r') { CON_NewLineConsole(DSConsole); } strncpy(DSConsole->ConsoleLines[0], b, DSConsole->VChars); DSConsole->ConsoleLines[0][DSConsole->VChars] = '\0'; } if(ConsoleIsVisible()) { CON_UpdateConsole(DSConsole); SetEventState(con_video_event, EVENT_STATE_ACTIVE); } } if(!irq_inside_int()) { spinlock_unlock(&lock); } return i; } static void *CommandThread(void *command) { int argc; char *argv[32]; char *str = (char *)command; for (argc = 0; argc < 32;) { if ((argv[argc] = strsep(&str, " \t\n")) == NULL) break; if (*argv[argc] != '\0') argc++; } if(CallCmd(argc, argv) == CMD_NOT_EXISTS) { ds_printf("DS_ERROR: Command '%s' not found.\n", argv[0]); } free(command); return NULL; } static void Command_Handler(ConsoleInformation *console, char* command) { if (command[0] == '\0') { return; } int len = strlen(command); if(command[len - 1] == '&') { command[len - 2] = '\0'; thd_create(1, CommandThread, strdup(command)); } else { CommandThread(strdup(command)); } } static char *TabFunction(char* command) { if(strcasestr(command, " ") != NULL) { return command; } Item_list_t *cmds = GetCmdList(); Cmd_t *c; Item_t *i; int internal = 0; SLIST_FOREACH(i, cmds, list) { c = (Cmd_t *) i->data; if(!strncmp(c->command, command, strlen(command))) { strcpy(command, c->command); internal = 1; break; } } if(!internal) { file_t fd; dirent_t *ent; char dir[NAME_MAX]; snprintf(dir, NAME_MAX, "%s/cmds", getenv("PATH")); fd = fs_open(dir, O_RDONLY | O_DIR); if(fd != FILEHND_INVALID) { while ((ent = fs_readdir(fd)) != NULL) { if(ent->attr != O_DIR && !strncmp(ent->name, command, strlen(command))) { strcpy(command, ent->name); } } fs_close(fd); } } return command; } static void ConsoleDrawHandler(void *ds_event, void *param, int action) { switch(action) { case EVENT_ACTION_RENDER: CON_DrawConsole(DSConsole); break; case EVENT_ACTION_UPDATE: CON_UpdateConsole(DSConsole); break; default: break; } } static void ConsoleEventHandler(void *ds_event, void *param, int action) { SDL_Event *event = (SDL_Event *) param; if(ConsoleIsVisible()) { CON_Events(event); switch(event->type) { case SDL_KEYDOWN: switch(event->key.keysym.sym) { case SDLK_F1: case SDLK_ESCAPE: HideConsole(); default: break; } break; default: break; } } else { switch(event->type) { case SDL_KEYDOWN: switch(event->key.keysym.sym) { case SDLK_F1: case SDLK_ESCAPE: ShowConsole(); default: break; } break; default: break; } } } static void SetGuiState(int state) { Event_t *e = NULL; e = GetEventByName("GUI_Video"); if(e) { SetEventState(e, state); } e = GetEventByName("GUI_Input"); if(e) { SetEventState(e, state); } } int InitConsole(const char *font, const char *background, int lines, int x, int y, int w, int h, int alpha) { SDL_Rect Con_rect; Con_rect.x = x; Con_rect.y = y; Con_rect.w = w; Con_rect.h = h; if((DSConsole = CON_Init(font, GetScreen(), lines, Con_rect)) == NULL) return 0; CON_SetPrompt(DSConsole, "D$: "); if(background != NULL) { CON_Background(DSConsole, background, 0, 0); } CON_SetExecuteFunction(DSConsole, Command_Handler); CON_SetTabCompletion(DSConsole, TabFunction); CON_Alpha(DSConsole, alpha); ds_printf("Enter 'help' for print command list.\n\n"); con_input_event = AddEvent("Console_Input", EVENT_TYPE_INPUT, ConsoleEventHandler, NULL); con_video_event = AddEvent("Console_Video", EVENT_TYPE_VIDEO, ConsoleDrawHandler, NULL); // CON_Topmost(DSConsole); return 1; } void ShutdownConsole() { RemoveEvent(con_input_event); RemoveEvent(con_video_event); CON_Destroy(DSConsole); } int ToggleConsole() { int vis = 0; if(DSConsole != NULL) { if((vis = ConsoleIsVisible())) { HideConsole(); } else { ShowConsole(); } } return vis; } void ShowConsole() { if(!ConsoleIsVisible()) { CON_Show(DSConsole); CON_Topmost(DSConsole); CON_UpdateConsole(DSConsole); SDL_DC_EmulateMouse(SDL_FALSE); SetGuiState(EVENT_STATE_SLEEP); SetEventState(con_video_event, EVENT_STATE_ACTIVE); } } void HideConsole() { if(ConsoleIsVisible()) { ScreenFadeOut(); CON_Hide(DSConsole); CON_Topmost(NULL); while(DSConsole->Visible != CON_CLOSED) thd_sleep(100); SDL_DC_EmulateMouse(SDL_TRUE); SetEventState(con_video_event, EVENT_STATE_SLEEP); SetGuiState(EVENT_STATE_ACTIVE); ProcessVideoEventsUpdate(NULL); ScreenFadeIn(); } } ConsoleInformation *GetConsole() { return DSConsole; } int ConsoleIsVisible() { return CON_isVisible(DSConsole); } <file_sep>/include/isofs/cdi.h /** * Copyright (c) 2013-2014 by SWAT <<EMAIL>> www.dc-swat.ru * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef _ISOFS_CDI_H #define _ISOFS_CDI_H #include <kos.h> /** * \file * DiscJuggler CDI support for isofs * * \author SWAT */ #define CDI_V2_ID 0x80000004 #define CDI_V3_ID 0x80000005 #define CDI_V35_ID 0x80000006 /* This limits only for DC games */ #define CDI_MAX_SESSIONS 2 #define CDI_MAX_TRACKS 99 typedef enum CDI_sector_mode { CDI_SECTOR_MODE_CDDA = 0, CDI_SECTOR_MODE_DATA = 1, CDI_SECTOR_MODE_MULTI = 2 } CDI_sector_mode_t; typedef enum cdi_sector_size { CDI_SECTOR_SIZE_DATA = 0, // 2048 CDI_SECTOR_SIZE_SEMIRAW = 1, // 2336 CDI_SECTOR_SIZE_CDDA = 2 // 2352 } CDI_sector_size_t; typedef struct CDI_trailer { uint32 version; uint32 header_offset; } CDI_trailer_t; typedef struct CDI_track { uint32 pregap_length; uint32 length; uint32 mode; uint32 start_lba; uint32 total_length; uint32 sector_size; uint32 offset; } CDI_track_t; typedef struct CDI_session { uint16 track_count; CDI_track_t *tracks[CDI_MAX_TRACKS]; } CDI_session_t; typedef struct CDI_header { CDI_trailer_t trail; uint16 session_count; CDI_session_t *sessions[CDI_MAX_SESSIONS]; } CDI_header_t; CDI_header_t *cdi_open(file_t fd); int cdi_close(CDI_header_t *hdr); uint16 cdi_track_sector_size(CDI_track_t *track); CDI_track_t *cdi_get_track(CDI_header_t *hdr, uint32 lba); uint32 cdi_get_offset(CDI_header_t *hdr, uint32 lba, uint16 *sector_size); int cdi_get_toc(CDI_header_t *hdr, CDROM_TOC *toc); int cdi_read_sectors(CDI_header_t *hdr, file_t fd, uint8 *buff, uint32 start, uint32 count); #endif /* _ISOFS_CDI_H */ <file_sep>/modules/luaSocket/src/inet.c /*=========================================================================*\ * Internet domain functions * LuaSocket toolkit * * RCS ID: $Id: inet.c,v 1.28 2005/10/07 04:40:59 diego Exp $ \*=========================================================================*/ #include <stdio.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #include "inet.h" /*=========================================================================*\ * Internal function prototypes. \*=========================================================================*/ static int inet_global_toip(lua_State *L); static int inet_global_tohostname(lua_State *L); static void inet_pushresolved(lua_State *L, struct hostent *hp); static int inet_global_gethostname(lua_State *L); /* DNS functions */ static luaL_reg func[] = { { "toip", inet_global_toip }, { "tohostname", inet_global_tohostname }, { "gethostname", inet_global_gethostname}, { NULL, NULL} }; /*=========================================================================*\ * Exported functions \*=========================================================================*/ /*-------------------------------------------------------------------------*\ * Initializes module \*-------------------------------------------------------------------------*/ int inet_open(lua_State *L) { lua_pushstring(L, "dns"); lua_newtable(L); luaL_openlib(L, NULL, func, 0); lua_settable(L, -3); return 0; } /*=========================================================================*\ * Global Lua functions \*=========================================================================*/ /*-------------------------------------------------------------------------*\ * Returns all information provided by the resolver given a host name * or ip address \*-------------------------------------------------------------------------*/ static int inet_gethost(const char *address, struct hostent **hp) { struct in_addr addr; if (inet_aton(address, &addr)) return IO_UNKNOWN; //socket_gethostbyaddr((char *) &addr, sizeof(addr), hp); else return socket_gethostbyname(address, hp); } /*-------------------------------------------------------------------------*\ * Returns all information provided by the resolver given a host name * or ip address \*-------------------------------------------------------------------------*/ static int inet_global_tohostname(lua_State *L) { const char *address = luaL_checkstring(L, 1); struct hostent *hp = NULL; int err = inet_gethost(address, &hp); if (err != IO_DONE) { lua_pushnil(L); lua_pushstring(L, socket_hoststrerror(err)); return 2; } lua_pushstring(L, hp->h_name); inet_pushresolved(L, hp); return 2; } /*-------------------------------------------------------------------------*\ * Returns all information provided by the resolver given a host name * or ip address \*-------------------------------------------------------------------------*/ static int inet_global_toip(lua_State *L) { const char *address = luaL_checkstring(L, 1); struct hostent *hp = NULL; int err = inet_gethost(address, &hp); if (err != IO_DONE) { lua_pushnil(L); lua_pushstring(L, socket_hoststrerror(err)); return 2; } lua_pushstring(L, inet_ntoa(*((struct in_addr *) hp->h_addr))); inet_pushresolved(L, hp); return 2; } /*-------------------------------------------------------------------------*\ * Gets the host name \*-------------------------------------------------------------------------*/ static int inet_global_gethostname(lua_State *L) { char name[257]; name[256] = '\0'; if (gethostname(name, 256) < 0) { lua_pushnil(L); lua_pushstring(L, "gethostname failed"); return 2; } else { lua_pushstring(L, name); return 1; } } /*=========================================================================*\ * Lua methods \*=========================================================================*/ /*-------------------------------------------------------------------------*\ * Retrieves socket peer name \*-------------------------------------------------------------------------*/ int inet_meth_getpeername(lua_State *L, p_socket ps) { // struct sockaddr_in peer; // socklen_t peer_len = sizeof(peer); // if (getpeername(*ps, (SA *) &peer, &peer_len) < 0) { lua_pushnil(L); lua_pushstring(L, "getpeername failed"); // } else { // lua_pushstring(L, inet_ntoa(peer.sin_addr)); // lua_pushnumber(L, ntohs(peer.sin_port)); // } return 2; } /*-------------------------------------------------------------------------*\ * Retrieves socket local name \*-------------------------------------------------------------------------*/ int inet_meth_getsockname(lua_State *L, p_socket ps) { // struct sockaddr_in local; // socklen_t local_len = sizeof(local); // if (getsockname(*ps, (SA *) &local, &local_len) < 0) { lua_pushnil(L); lua_pushstring(L, "getsockname failed"); // } else { // lua_pushstring(L, inet_ntoa(local.sin_addr)); // lua_pushnumber(L, ntohs(local.sin_port)); // } return 2; } /*=========================================================================*\ * Internal functions \*=========================================================================*/ /*-------------------------------------------------------------------------*\ * Passes all resolver information to Lua as a table \*-------------------------------------------------------------------------*/ static void inet_pushresolved(lua_State *L, struct hostent *hp) { char **alias; struct in_addr **addr; int i, resolved; lua_newtable(L); resolved = lua_gettop(L); lua_pushstring(L, "name"); lua_pushstring(L, hp->h_name); lua_settable(L, resolved); lua_pushstring(L, "ip"); lua_pushstring(L, "alias"); i = 1; alias = hp->h_aliases; lua_newtable(L); if (alias) { while (*alias) { lua_pushnumber(L, i); lua_pushstring(L, *alias); lua_settable(L, -3); i++; alias++; } } lua_settable(L, resolved); i = 1; lua_newtable(L); addr = (struct in_addr **) hp->h_addr_list; if (addr) { while (*addr) { lua_pushnumber(L, i); lua_pushstring(L, inet_ntoa(**addr)); lua_settable(L, -3); i++; addr++; } } lua_settable(L, resolved); } /*-------------------------------------------------------------------------*\ * Tries to create a new inet socket \*-------------------------------------------------------------------------*/ const char *inet_trycreate(p_socket ps, int type) { return socket_strerror(socket_create(ps, AF_INET, type, 0)); } /*-------------------------------------------------------------------------*\ * Tries to connect to remote address (address, port) \*-------------------------------------------------------------------------*/ const char *inet_tryconnect(p_socket ps, const char *address, unsigned short port, p_timeout tm) { struct sockaddr_in remote; int err; memset(&remote, 0, sizeof(remote)); remote.sin_family = AF_INET; remote.sin_port = htons(port); if (strcmp(address, "*")) { if (!inet_aton(address, &remote.sin_addr)) { struct hostent *hp = NULL; struct in_addr **addr; err = socket_gethostbyname(address, &hp); if (err != IO_DONE) return socket_hoststrerror(err); addr = (struct in_addr **) hp->h_addr_list; memcpy(&remote.sin_addr, *addr, sizeof(struct in_addr)); } } else remote.sin_family = AF_UNSPEC; err = socket_connect(ps, (SA *) &remote, sizeof(remote), tm); return socket_strerror(err); } /*-------------------------------------------------------------------------*\ * Tries to bind socket to (address, port) \*-------------------------------------------------------------------------*/ const char *inet_trybind(p_socket ps, const char *address, unsigned short port) { struct sockaddr_in local; int err; memset(&local, 0, sizeof(local)); /* address is either wildcard or a valid ip address */ local.sin_addr.s_addr = htonl(INADDR_ANY); local.sin_port = htons(port); local.sin_family = AF_INET; if (strcmp(address, "*") && !inet_aton(address, &local.sin_addr)) { struct hostent *hp = NULL; struct in_addr **addr; err = socket_gethostbyname(address, &hp); if (err != IO_DONE) return socket_hoststrerror(err); addr = (struct in_addr **) hp->h_addr_list; memcpy(&local.sin_addr, *addr, sizeof(struct in_addr)); } err = socket_bind(ps, (SA *) &local, sizeof(local)); if (err != IO_DONE) socket_destroy(ps); return socket_strerror(err); } /*-------------------------------------------------------------------------*\ * Some systems do not provide this so that we provide our own. It's not * marvelously fast, but it works just fine. \*-------------------------------------------------------------------------*/ #ifdef INET_ATON int inet_aton(const char *cp, struct in_addr *inp) { unsigned int a = 0, b = 0, c = 0, d = 0; int n = 0, r; unsigned long int addr = 0; r = sscanf(cp, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n); if (r == 0 || n == 0) return 0; cp += n; if (*cp) return 0; if (a > 255 || b > 255 || c > 255 || d > 255) return 0; if (inp) { addr += a; addr <<= 8; addr += b; addr <<= 8; addr += c; addr <<= 8; addr += d; inp->s_addr = htonl(addr); } return 1; } #endif <file_sep>/firmware/isoldr/loader/include/exception.h /** * DreamShell ISO Loader * Exception handling * (c)2014-2023 SWAT <http://www.dc-swat.ru> * Based on Netplay VOOT code by <NAME> <<EMAIL>> */ #ifndef __EXCEPTION_H__ #define __EXCEPTION_H__ #include <main.h> #include <exception-lowlevel.h> #if defined(HAVE_GDB) # define EXP_TABLE_SIZE 8 #elif defined(HAVE_UBC) # define EXP_TABLE_SIZE 2 #else # define EXP_TABLE_SIZE 1 #endif typedef void *(* exception_handler_f) (register_stack *, void *); typedef struct { uint32 type; uint32 code; exception_handler_f handler; } exception_table_entry; typedef struct { /* Exception counters */ // uint32 general_exception_count; // uint32 cache_exception_count; // uint32 interrupt_exception_count; // uint32 ubc_exception_count; // uint32 odd_exception_count; /* Function hooks for various interrupts */ exception_table_entry table[EXP_TABLE_SIZE]; } exception_table; int exception_init(uint32 vbr_addr); int exception_inited(void); int exception_add_handler(const exception_table_entry *new_entry, exception_handler_f *parent_handler); void *exception_handler(register_stack *stack); int exception_inside_int(void); void dump_regs(register_stack *stack); #endif <file_sep>/firmware/isoldr/loader/kos/dc/net/lan_adapter.h /* KallistiOS ##version## * * dc/net/lan_adapter.h * * (c)2002 <NAME> * * $Id: lan_adapter.h,v 1.2 2003/02/25 07:39:37 bardtx Exp $ */ #ifndef __DC_NET_LAN_ADAPTER_H #define __DC_NET_LAN_ADAPTER_H #include <sys/cdefs.h> __BEGIN_DECLS #include <kos/net.h> /* Initialize */ int la_init(); /* Shutdown */ int la_shutdown(); extern netif_t la_if; __END_DECLS #endif /* __DC_NET_LAN_ADAPTER_H */ <file_sep>/include/fatfs/ff_utils.h /** * Fatfs utils */ #ifndef __FF_UTILS_H__ #define __FF_UTILS_H__ #include "integer.h" struct _time_block { int year; int mon; int day; int hour; int min; int sec; }; unsigned long rtc_secs(void); struct _time_block *conv_gmtime(unsigned long t); DWORD get_fattime(); #endif <file_sep>/modules/mp3/libmp3/xingmp3/cwin.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** cwin.c *************************************************** include to cwinm.c MPEG audio decoder, float window routines portable C ******************************************************************/ #ifdef ASM_X86 extern void window_mpg_asm(float *a, int b, short *c); extern void window_dual_asm(float *a, int b, short *c); extern void window16_asm(float *a, int b, short *c); extern void window16_dual_asm(float *a, int b, short *c); extern void window8_asm(float *a, int b, short *c); extern void window8_dual_asm(float *a, int b, short *c); #endif /* ASM_X86 */ #include "mhead.h" /*-------------------------------------------------------------------------*/ void window(MPEG *m, float *vbuf, int vb_ptr, short *pcm) { #ifdef ASM_X86 window_mpg_asm(vbuf, vb_ptr, pcm); #else int i, j; int si, bx; float *coef; float sum; long tmp; si = vb_ptr + 16; bx = (si + 32) & 511; coef = wincoef; /*-- first 16 --*/ for (i = 0; i < 16; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si = (si + 64) & 511; sum -= (*coef++) * vbuf[bx]; bx = (bx + 64) & 511; } si++; bx--; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = tmp; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx = (bx + 64) & 511; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = tmp; /*-- last 15 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 15; i++) { si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si = (si + 64) & 511; sum += (*coef--) * vbuf[bx]; bx = (bx + 64) & 511; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = tmp; } #endif } /*------------------------------------------------------------*/ void window_dual(MPEG *m, float *vbuf, int vb_ptr, short *pcm) { #ifdef ASM_X86 window_dual_asm(vbuf, vb_ptr, pcm); #else int i, j; /* dual window interleaves output */ int si, bx; float *coef; float sum; long tmp; si = vb_ptr + 16; bx = (si + 32) & 511; coef = wincoef; /*-- first 16 --*/ for (i = 0; i < 16; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si = (si + 64) & 511; sum -= (*coef++) * vbuf[bx]; bx = (bx + 64) & 511; } si++; bx--; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = tmp; pcm += 2; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx = (bx + 64) & 511; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = tmp; pcm += 2; /*-- last 15 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 15; i++) { si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si = (si + 64) & 511; sum += (*coef--) * vbuf[bx]; bx = (bx + 64) & 511; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = tmp; pcm += 2; } #endif } /*------------------------------------------------------------*/ /*------------------- 16 pt window ------------------------------*/ void window16(MPEG *m, float *vbuf, int vb_ptr, short *pcm) { #ifdef ASM_X86 window16_asm(vbuf, vb_ptr, pcm); #else int i, j; unsigned char si, bx; float *coef; float sum; long tmp; si = vb_ptr + 8; bx = si + 16; coef = wincoef; /*-- first 8 --*/ for (i = 0; i < 8; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si += 32; sum -= (*coef++) * vbuf[bx]; bx += 32; } si++; bx--; coef += 16; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = tmp; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx += 32; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = tmp; /*-- last 7 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 7; i++) { coef -= 16; si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si += 32; sum += (*coef--) * vbuf[bx]; bx += 32; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = tmp; } #endif } /*--------------- 16 pt dual window (interleaved output) -----------------*/ void window16_dual(MPEG *m, float *vbuf, int vb_ptr, short *pcm) { #ifdef ASM_X86 window16_dual_asm(vbuf, vb_ptr, pcm); #else int i, j; unsigned char si, bx; float *coef; float sum; long tmp; si = vb_ptr + 8; bx = si + 16; coef = wincoef; /*-- first 8 --*/ for (i = 0; i < 8; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si += 32; sum -= (*coef++) * vbuf[bx]; bx += 32; } si++; bx--; coef += 16; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = tmp; pcm += 2; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx += 32; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = tmp; pcm += 2; /*-- last 7 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 7; i++) { coef -= 16; si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si += 32; sum += (*coef--) * vbuf[bx]; bx += 32; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = tmp; pcm += 2; } #endif } /*------------------- 8 pt window ------------------------------*/ void window8(MPEG8 *m, float *vbuf, int vb_ptr, short *pcm) { #ifdef ASM_X86 window8_asm(vbuf, vb_ptr, pcm); #else int i, j; int si, bx; float *coef; float sum; long tmp; si = vb_ptr + 4; bx = (si + 8) & 127; coef = wincoef; /*-- first 4 --*/ for (i = 0; i < 4; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si = (si + 16) & 127; sum -= (*coef++) * vbuf[bx]; bx = (bx + 16) & 127; } si++; bx--; coef += 48; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = tmp; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx = (bx + 16) & 127; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = tmp; /*-- last 3 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 3; i++) { coef -= 48; si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si = (si + 16) & 127; sum += (*coef--) * vbuf[bx]; bx = (bx + 16) & 127; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm++ = tmp; } #endif } /*--------------- 8 pt dual window (interleaved output) -----------------*/ void window8_dual(MPEG8 *m, float *vbuf, int vb_ptr, short *pcm) { #ifdef ASM_X86 window8_dual_asm(vbuf, vb_ptr, pcm); #else int i, j; int si, bx; float *coef; float sum; long tmp; si = vb_ptr + 4; bx = (si + 8) & 127; coef = wincoef; /*-- first 4 --*/ for (i = 0; i < 4; i++) { sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[si]; si = (si + 16) & 127; sum -= (*coef++) * vbuf[bx]; bx = (bx + 16) & 127; } si++; bx--; coef += 48; tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = tmp; pcm += 2; } /*-- special case --*/ sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef++) * vbuf[bx]; bx = (bx + 16) & 127; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = tmp; pcm += 2; /*-- last 3 --*/ coef = wincoef + 255; /* back pass through coefs */ for (i = 0; i < 3; i++) { coef -= 48; si--; bx++; sum = 0.0F; for (j = 0; j < 8; j++) { sum += (*coef--) * vbuf[si]; si = (si + 16) & 127; sum += (*coef--) * vbuf[bx]; bx = (bx + 16) & 127; } tmp = (long) sum; if (tmp > 32767) tmp = 32767; else if (tmp < -32768) tmp = -32768; *pcm = tmp; pcm += 2; } #endif } /*------------------------------------------------------------*/ <file_sep>/sdk/toolchain/download.sh #!/bin/sh # These version numbers are all that should ever have to be changed. . $PWD/versions.sh while [ "$1" != "" ]; do PARAM=`echo $1 | awk -F= '{print $1}'` case $PARAM in --no-gmp) unset GMP_VER ;; --no-mpfr) unset MPFR_VER ;; --no-mpc) unset MPC_VER ;; --no-deps) unset GMP_VER unset MPFR_VER unset MPC_VER ;; *) echo "ERROR: unknown parameter \"$PARAM\"" exit 1 ;; esac shift done # Download everything. if command -v wget >/dev/null 2>&1; then echo "Downloading binutils-$BINUTILS_VER..." wget -c ftp://ftp.gnu.org/gnu/binutils/binutils-$BINUTILS_VER.tar.bz2 || exit 1 echo "Downloading GCC $GCC_VER..." wget -c ftp://ftp.gnu.org/gnu/gcc/gcc-$GCC_VER/gcc-$GCC_VER.tar.gz || exit 1 echo "Downloading Newlib $NEWLIB_VER..." wget -c ftp://sourceware.org/pub/newlib/newlib-$NEWLIB_VER.tar.gz || exit 1 if [ -n "$GMP_VER" ]; then echo "Downloading GMP $GMP_VER..." wget -c ftp://gcc.gnu.org/pub/gcc/infrastructure/gmp-$GMP_VER.tar.bz2 || exit 1 fi if [ -n "$MPFR_VER" ]; then echo "Downloading MPFR $MPFR_VER..." wget -c ftp://gcc.gnu.org/pub/gcc/infrastructure/mpfr-$MPFR_VER.tar.bz2 || exit 1 fi if [ -n "$MPC_VER" ]; then echo "Downloading MPC $MPC_VER..." wget -c ftp://gcc.gnu.org/pub/gcc/infrastructure/mpc-$MPC_VER.tar.gz || exit 1 fi elif command -v curl >/dev/null 2>&1; then echo "Downloading Binutils $BINUTILS_VER..." curl -C - -O ftp://ftp.gnu.org/gnu/binutils/binutils-$BINUTILS_VER.tar.bz2 || exit 1 echo "Downloading GCC $GCC_VER..." curl -C - -O ftp://ftp.gnu.org/gnu/gcc/gcc-$GCC_VER/gcc-$GCC_VER.tar.bz2 || exit 1 echo "Downloading Newlib $NEWLIB_VER..." curl -C - -O ftp://sourceware.org/pub/newlib/newlib-$NEWLIB_VER.tar.gz || exit 1 if [ -n "$GMP_VER" ]; then echo "Downloading GMP $GMP_VER..." curl -C - -O ftp://gcc.gnu.org/pub/gcc/infrastructure/gmp-$GMP_VER.tar.bz2 || exit 1 fi if [ -n "$MPFR_VER" ]; then echo "Downloading MPFR $MPFR_VER..." curl -C - -O ftp://gcc.gnu.org/pub/gcc/infrastructure/mpfr-$MPFR_VER.tar.bz2 || exit 1 fi if [ -n "$MPC_VER" ]; then echo "Downloading MPC $MPC_VER..." curl -C - -O ftp://gcc.gnu.org/pub/gcc/infrastructure/mpc-$MPC_VER.tar.gz || exit 1 fi else echo >&2 "You must have either wget or cURL installed to use this script!" exit 1 fi <file_sep>/firmware/bootloader/src/menu.c /** * DreamShell boot loader * Menu * (c)2011-2023 SWAT <http://www.dc-swat.ru> */ #include "main.h" #include "fs.h" static pvr_ptr_t txr_font; static float alpha, curs_alpha; static int frame, curs_alpha_dir; static float progress_w, old_per; static mutex_t video_mutex = MUTEX_INITIALIZER; static volatile int load_process = 0; static int load_in_thread = 0; static volatile int binary_ready = 0; static uint32 binary_size = 0; static uint8 *binary_buff = NULL; typedef struct menu_item { char name[NAME_MAX]; char path[NAME_MAX]; int mode; int is_gz; int is_scrambled; struct menu_item *next; } menu_item_t; static menu_item_t *items; static int items_cnt = 0; static int selected = 0; static char message[NAME_MAX]; //static char cur_path[NAME_MAX]; //static void clear_menu(); static int must_lock_video() { kthread_t *ct = thd_get_current(); return ct->tid != 1; } #define lock_video() \ do { \ if(must_lock_video()) \ mutex_lock(&video_mutex); \ } while(0) #define unlock_video() \ do { \ if(must_lock_video()) \ mutex_unlock(&video_mutex); \ } while(0) int show_message(const char *fmt, ...) { va_list args; int i; if(!start_pressed) return 0; va_start(args, fmt); i = vsnprintf(message, NAME_MAX, fmt, args); va_end(args); return i; } void init_menu_txr() { uint16 *vram; int x, y; txr_font = pvr_mem_malloc(256*256*2); vram = (uint16*)txr_font; for (y = 0; y < 8; y++) { for (x = 0; x < 16; x++) { bfont_draw(vram, 256, 0, y * 16 + x); vram += 16; } vram += 23 * 256; } } /* The following funcs blatently ripped from libconio =) */ /* Draw one font character (6x12) */ static void draw_char(float x1, float y1, float z1, float a, float r, float g, float b, int c) { pvr_vertex_t vert; int ix, iy; float u1, v1, u2, v2; if (c == ' ') return; if(c > ' ' && c < 127) { ix = (c % 16) * 16; iy = (c / 16) * 24; u1 = ix * 1.0f / 256.0f; v1 = iy * 1.0f / 256.0f; u2 = (ix+12) * 1.0f / 256.0f; v2 = (iy+24) * 1.0f / 256.0f; vert.flags = PVR_CMD_VERTEX; vert.x = x1; vert.y = y1 + 24; vert.z = z1; vert.u = u1; vert.v = v2; vert.argb = PVR_PACK_COLOR(a, r, g, b); vert.oargb = 0; pvr_prim(&vert, sizeof(vert)); vert.x = x1; vert.y = y1; vert.u = u1; vert.v = v1; pvr_prim(&vert, sizeof(vert)); vert.x = x1 + 12; vert.y = y1 + 24; vert.u = u2; vert.v = v2; pvr_prim(&vert, sizeof(vert)); vert.flags = PVR_CMD_VERTEX_EOL; vert.x = x1 + 12; vert.y = y1; vert.u = u2; vert.v = v1; pvr_prim(&vert, sizeof(vert)); } } /* draw len chars at string */ static void draw_string(float x, float y, float z, float a, float r, float g, float b, char *str, int len) { int i; pvr_poly_cxt_t cxt; pvr_poly_hdr_t poly; pvr_poly_cxt_txr(&cxt, PVR_LIST_TR_POLY, PVR_TXRFMT_ARGB1555 | PVR_TXRFMT_NONTWIDDLED, 256, 256, txr_font, PVR_FILTER_NONE); pvr_poly_compile(&poly, &cxt); pvr_prim(&poly, sizeof(poly)); for (i = 0; i < len; i++) { draw_char(x, y, z, a, r, g, b, str[i]); x += 12; } } /* draw a box (used by cursor and border, etc) (at 1.0f z coord) */ static void draw_box(float x, float y, float w, float h, float z, float a, float r, float g, float b) { pvr_poly_cxt_t cxt; pvr_poly_hdr_t poly; pvr_vertex_t vert; pvr_poly_cxt_col(&cxt, PVR_LIST_TR_POLY); pvr_poly_compile(&poly, &cxt); pvr_prim(&poly, sizeof(poly)); vert.flags = PVR_CMD_VERTEX; vert.x = x; vert.y = y + h; vert.z = z; vert.u = vert.v = 0.0f; vert.argb = PVR_PACK_COLOR(a, r, g, b); vert.oargb = 0; pvr_prim(&vert, sizeof(vert)); vert.y -= h; pvr_prim(&vert, sizeof(vert)); vert.y += h; vert.x += w; pvr_prim(&vert, sizeof(vert)); vert.flags = PVR_CMD_VERTEX_EOL; vert.y -= h; pvr_prim(&vert, sizeof(vert)); } static int search_root_check(char *device, char *path, char *file) { char check[NAME_MAX]; if(file == NULL) { sprintf(check, "/%s%s", device, path); } else { sprintf(check, "/%s%s/%s", device, path, file); } if((file == NULL && DirExists(check)) || (file != NULL && FileExists(check))) { return 0; } return -1; } static int search_root() { dirent_t *ent; file_t hnd; menu_item_t *item; char name[NAME_MAX]; int i; hnd = fs_open("/", O_RDONLY | O_DIR); if(hnd == FILEHND_INVALID) { dbglog(DBG_ERROR, "Can't open root directory!\n"); return -1; } while ((ent = fs_readdir(hnd)) != NULL) { if(!RootDeviceIsSupported(ent->name)) { continue; } item = calloc(1, sizeof(menu_item_t)); if(!item) { break; } item->next = items; items = item; for(i = 0; i < strlen(ent->name); i++) { name[i] = toupper((int)ent->name[i]); } name[i] = '\0'; snprintf(item->name, NAME_MAX, "Boot from %s", name); item->mode = 0; items_cnt++; dbglog(DBG_INFO, "Checking for root directory on /%s\n", ent->name); if(!search_root_check(ent->name, "/DS", "/DS_CORE.BIN")) { snprintf(item->path, NAME_MAX, "/%s/DS/DS_CORE.BIN", ent->name); } else if(!search_root_check(ent->name, "", "/DS_CORE.BIN")) { snprintf(item->path, NAME_MAX, "/%s/DS_CORE.BIN", ent->name); } else if(!search_root_check(ent->name, "", "/1DS_CORE.BIN")) { snprintf(item->path, NAME_MAX, "/%s/1DS_CORE.BIN", ent->name); item->is_scrambled = 1; } else if(!search_root_check(ent->name, "/DS", "/ZDS_CORE.BIN")) { snprintf(item->path, NAME_MAX, "/%s/DS/ZDS_CORE.BIN", ent->name); item->is_gz = 1; } else if(!search_root_check(ent->name, "", "/ZDS_CORE.BIN")) { snprintf(item->path, NAME_MAX, "/%s/ZDS_CORE.BIN", ent->name); item->is_gz = 1; } else { item->path[0] = 0; } } fs_close(hnd); return 0; } /* static int read_directory() { dirent_t *ent; file_t hnd; menu_item_t *item; int i; hnd = fs_open(cur_path, O_RDONLY | O_DIR); if(hnd == FILEHND_INVALID) { dbglog(DBG_ERROR, "Can't open root directory!\n"); return -1; } while ((ent = fs_readdir(hnd)) != NULL) { if(!strcasecmp(ent->name, ".")) { continue; } item = calloc(1, sizeof(menu_item_t)); if(item) { item->next = items; items = item; if(ent->attr == O_DIR) { strncpy(item->name, ent->name, NAME_MAX); item->mode = 0; } else { snprintf(item->name, NAME_MAX, "%s %dKB", ent->name, ent->size); item->mode = 1; } item->name[strlen(item->name)] = '\0'; snprintf(item->path, NAME_MAX, "%s/%s", cur_path, ent->name); item->path[strlen(item->path)] = '\0'; items_cnt++; } else { break; } } fs_close(hnd); return 0; } */ static void update_progress(float per) { lock_video(); progress_w = (460.0f / 100.0f) * per; if(old_per != per) { old_per = per; show_message("Loading %02d%c", (int)per, '%'); } unlock_video(); } static uint32 gzip_get_file_size(char *filename) { file_t fd; uint32 len; uint32 size; fd = fs_open(filename, O_RDONLY); if(fd < 0) return 0; if(fs_seek(fd, -4, SEEK_END) <= 0) { fs_close(fd); return 0; } len = fs_read(fd, &size, sizeof(size)); fs_close(fd); if(len != 4) { return 0; } return size; } void *loading_thd(void *param) { menu_item_t *item = (menu_item_t *)param; file_t fd = FILEHND_INVALID; gzFile fdz = NULL; uint8 *pbuff; uint32 count = 0; int i = 0; if(item->is_gz) { dbglog(DBG_INFO, "Loading compressed binary %s ...\n", item->path); binary_size = gzip_get_file_size(item->path); fdz = gzopen(item->path, "r"); if(fdz == NULL) { lock_video(); show_message("Can't open file"); unlock_video(); load_process = 0; binary_size = 0; return NULL; } } else { dbglog(DBG_INFO, "Loading binary %s ...\n", item->path); fd = fs_open(item->path, O_RDONLY); if(fd == FILEHND_INVALID) { lock_video(); show_message("Can't open file"); unlock_video(); load_process = 0; return NULL; } binary_size = fs_total(fd); } if(!binary_size) { lock_video(); show_message("File is empty"); unlock_video(); if(fd != FILEHND_INVALID) fs_close(fd); if(fdz) gzclose(fdz); load_process = 0; return NULL; } update_progress(0); binary_buff = (uint8 *)memalign(32, binary_size); if(binary_buff != NULL) { memset(binary_buff, 0, binary_size); pbuff = binary_buff; if(item->is_gz) { if(!load_in_thread) { i = gzread(fdz, pbuff, binary_size); if(i < 0) { lock_video(); show_message("Loading error"); load_process = 0; binary_size = 0; free(binary_buff); gzclose(fdz); unlock_video(); return NULL; } } else { while((i = gzread(fdz, pbuff, 16384)) > 0) { update_progress((float)count / ((float)binary_size / 100.0f)); pbuff += i; count += i; } } gzclose(fdz); } else { if(!load_in_thread) { i = fs_read(fd, pbuff, binary_size); if(i < 0) { lock_video(); show_message("Loading error"); load_process = 0; binary_size = 0; free(binary_buff); fs_close(fd); unlock_video(); return NULL; } } else { while((i = fs_read(fd, pbuff, 32768)) > 0) { update_progress((float)count / ((float)binary_size / 100.0f)); // dbglog(DBG_INFO, "Loaded %d to %p\n", i, pbuff); // thd_sleep(10); pbuff += i; count += i; } } fs_close(fd); } if(item->is_scrambled) { lock_video(); show_message("Descrambling..."); unlock_video(); uint8 *tmp_buf = (uint8 *)malloc(binary_size); descramble(binary_buff, tmp_buf, binary_size); free(binary_buff); binary_buff = tmp_buf; } lock_video(); show_message("Executing..."); unlock_video(); if(load_in_thread) { thd_sleep(100); binary_ready = 1; } else { dbglog(DBG_INFO, "Executing...\n"); arch_exec(binary_buff, binary_size); } } else { lock_video(); show_message("Not enough memory: %d Kb", binary_size / 1024); binary_size = 0; unlock_video(); } load_process = 0; return NULL; } static menu_item_t *get_selected() { menu_item_t *item = NULL; int i = 0; for (item = items, i = 0; i < selected; i++, item = item->next) ; return item; } /* static void clear_menu() { menu_item_t *item = NULL; int i = 0; for (item = items, i = 0; i < items_cnt; i++, item = item->next) { if(item) free(item); } } */ void loading_core(int no_thd) { menu_item_t *item = get_selected(); if(item->path[0] != 0 && !load_process) { file_t f; f = fs_open(item->path, O_RDONLY); if(f == FILEHND_INVALID) { show_message("Can't open %s", item->path); return; } fs_close(f); show_message("Loading..."); load_process = 1; if(no_thd) { load_in_thread = 0; loading_thd((void*)item); } else { load_in_thread = 1; thd_create(0, loading_thd, (void*)item); } } } static uint32 last_btns = 0; static uint32 frames = 0; static void check_input() { maple_device_t *cont = NULL; cont_state_t *state = NULL; if(binary_ready) { arch_exec(binary_buff, binary_size); } cont = maple_enum_type(0, MAPLE_FUNC_CONTROLLER); frames++; if(cont) { state = (cont_state_t *)maple_dev_status(cont); if(!state) return; if (last_btns != state->buttons) { if (state->buttons & CONT_DPAD_UP) { selected--; if (selected < 0) selected += items_cnt; } if (state->buttons & CONT_DPAD_DOWN) { selected++; if (selected >= items_cnt) selected -= items_cnt; } if ((state->buttons & CONT_DPAD_LEFT) || (state->buttons & CONT_DPAD_RIGHT)) { menu_item_t *item = get_selected(); item->mode = item->mode ? 0 : 1; } if (state->buttons & CONT_A) { loading_core(0); } if (state->buttons & CONT_B) { loading_core(0); } if(state->buttons & CONT_Y) { loading_core(1); } if(state->buttons & CONT_X) { loading_core(1); } frames = 0; last_btns = state->buttons; } } if(frames > 300) { loading_core(0); frames = 0; } } int menu_init() { alpha = 0.0f; frame = 0; selected = 0; progress_w = 0.0f; curs_alpha = 0.5f; curs_alpha_dir = 0; if(start_pressed) init_menu_txr(); search_root(); while(selected < items_cnt) { menu_item_t *item = get_selected(); if(item->path[0] != 0) { return 0; } selected++; } selected = 0; return 0; } void menu_frame() { menu_item_t *item; float y; /* Delay */ frame++; if (frame < 120) return; /* Adjust alpha */ if (alpha < 1.0f) alpha += 1/30.0f; else alpha = 1.0f; if(!curs_alpha_dir) { curs_alpha -= 1/120.0f; if(curs_alpha <= 0.30f) { curs_alpha_dir = 1; } } else { curs_alpha += 1/120.0f; if(curs_alpha >= 0.70f) { curs_alpha_dir = 0; } } /* Draw title */ draw_box(90, 90, 640-180, 26, 100.0f, alpha * 0.6f, 0.0f, 0.0f, 0.0f); draw_string(320.0f - (12*sizeof(title))/2, 92.0f, 101.0f, alpha, 1, 1, 1, (char*)title, sizeof(title)); /* Draw background plane */ draw_box(90, 90+26, 640-180, 480-(180+26), 100.0f, alpha * 0.3f, 0.0f, 0.0f, 0.0f); //draw_box(88, 88+30, 640-176, 480-(180+22), 100.0f, alpha * 0.6f, 0.0f, 0.0f, 0.0f); /* Draw menu items */ for (y = 90+37, item = items; item; item = item->next, y += 25.0f) { if(item->path[0] != 0) { draw_string(100.0f, y, 101.0f, alpha, 1, 1, 1, (item->mode ? item->path : item->name), strlen(item->mode ? item->path : item->name)); } else { draw_string(100.0f, y, 101.0f, alpha * 0.6f, 1, 1, 1, item->name, strlen(item->name)); } } /* Cursor */ draw_box(90, 90 + 36 + selected * 25 - 1, 640-180, 26, 100.5f, alpha * curs_alpha, 0.3f, 0.3f, 0.3f); mutex_lock(&video_mutex); draw_box(90, 480-(90+26), 640-180, 26, 100.0f, alpha * 0.6f, 0.0f, 0.0f, 0.0f); draw_box(90, 480-(90+26), progress_w, 26, 101.0f, alpha * 0.9f, 0.85f, 0.15f, 0.15f); draw_string(320.0f - (12*strlen(message))/2, 480-(90+24), 102.0f, alpha, 1, 1, 1, message, strlen(message)); mutex_unlock(&video_mutex); /* Check for key input */ check_input(); } <file_sep>/lib/SDL_image/IMG_jpg.c /* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2012 <NAME> <<EMAIL>> Copyright (C) 2014 SWAT <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #if !defined(__APPLE__) || defined(SDL_IMAGE_USE_COMMON_BACKEND) /* This is a JPEG image file loading framework */ #include <stdio.h> #include <string.h> #include <setjmp.h> #if defined(__DREAMCAST__) #include <malloc.h> #endif #include "SDL_image.h" #ifdef LOAD_JPG #include <jpeglib.h> #ifdef JPEG_TRUE /* MinGW version of jpeg-8.x renamed TRUE to JPEG_TRUE etc. */ typedef JPEG_boolean boolean; #define TRUE JPEG_TRUE #define FALSE JPEG_FALSE #endif #if defined(HAVE_STDIO_H) && !defined(__DREAMCAST__) int fileno(FILE *f); #endif /* Define this for fast loading and not as good image quality */ /*#define FAST_JPEG*/ /* Define this for quicker (but less perfect) JPEG identification */ #define FAST_IS_JPEG static struct { int loaded; void *handle; void (*jpeg_calc_output_dimensions) (j_decompress_ptr cinfo); void (*jpeg_CreateDecompress) (j_decompress_ptr cinfo, int version, size_t structsize); void (*jpeg_destroy_decompress) (j_decompress_ptr cinfo); boolean (*jpeg_finish_decompress) (j_decompress_ptr cinfo); int (*jpeg_read_header) (j_decompress_ptr cinfo, boolean require_image); JDIMENSION (*jpeg_read_scanlines) (j_decompress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION max_lines); boolean (*jpeg_resync_to_restart) (j_decompress_ptr cinfo, int desired); boolean (*jpeg_start_decompress) (j_decompress_ptr cinfo); struct jpeg_error_mgr * (*jpeg_std_error) (struct jpeg_error_mgr * err); } lib; #ifdef LOAD_JPG_DYNAMIC int IMG_InitJPG() { if ( lib.loaded == 0 ) { lib.handle = SDL_LoadObject(LOAD_JPG_DYNAMIC); if ( lib.handle == NULL ) { return -1; } lib.jpeg_calc_output_dimensions = (void (*) (j_decompress_ptr)) SDL_LoadFunction(lib.handle, "jpeg_calc_output_dimensions"); if ( lib.jpeg_calc_output_dimensions == NULL ) { SDL_UnloadObject(lib.handle); return -1; } lib.jpeg_CreateDecompress = (void (*) (j_decompress_ptr, int, size_t)) SDL_LoadFunction(lib.handle, "jpeg_CreateDecompress"); if ( lib.jpeg_CreateDecompress == NULL ) { SDL_UnloadObject(lib.handle); return -1; } lib.jpeg_destroy_decompress = (void (*) (j_decompress_ptr)) SDL_LoadFunction(lib.handle, "jpeg_destroy_decompress"); if ( lib.jpeg_destroy_decompress == NULL ) { SDL_UnloadObject(lib.handle); return -1; } lib.jpeg_finish_decompress = (boolean (*) (j_decompress_ptr)) SDL_LoadFunction(lib.handle, "jpeg_finish_decompress"); if ( lib.jpeg_finish_decompress == NULL ) { SDL_UnloadObject(lib.handle); return -1; } lib.jpeg_read_header = (int (*) (j_decompress_ptr, boolean)) SDL_LoadFunction(lib.handle, "jpeg_read_header"); if ( lib.jpeg_read_header == NULL ) { SDL_UnloadObject(lib.handle); return -1; } lib.jpeg_read_scanlines = (JDIMENSION (*) (j_decompress_ptr, JSAMPARRAY, JDIMENSION)) SDL_LoadFunction(lib.handle, "jpeg_read_scanlines"); if ( lib.jpeg_read_scanlines == NULL ) { SDL_UnloadObject(lib.handle); return -1; } lib.jpeg_resync_to_restart = (boolean (*) (j_decompress_ptr, int)) SDL_LoadFunction(lib.handle, "jpeg_resync_to_restart"); if ( lib.jpeg_resync_to_restart == NULL ) { SDL_UnloadObject(lib.handle); return -1; } lib.jpeg_start_decompress = (boolean (*) (j_decompress_ptr)) SDL_LoadFunction(lib.handle, "jpeg_start_decompress"); if ( lib.jpeg_start_decompress == NULL ) { SDL_UnloadObject(lib.handle); return -1; } lib.jpeg_std_error = (struct jpeg_error_mgr * (*) (struct jpeg_error_mgr *)) SDL_LoadFunction(lib.handle, "jpeg_std_error"); if ( lib.jpeg_std_error == NULL ) { SDL_UnloadObject(lib.handle); return -1; } } ++lib.loaded; return 0; } void IMG_QuitJPG() { if ( lib.loaded == 0 ) { return; } if ( lib.loaded == 1 ) { SDL_UnloadObject(lib.handle); } --lib.loaded; } #else int IMG_InitJPG() { if ( lib.loaded == 0 ) { lib.jpeg_calc_output_dimensions = jpeg_calc_output_dimensions; lib.jpeg_CreateDecompress = jpeg_CreateDecompress; lib.jpeg_destroy_decompress = jpeg_destroy_decompress; lib.jpeg_finish_decompress = jpeg_finish_decompress; lib.jpeg_read_header = jpeg_read_header; lib.jpeg_read_scanlines = jpeg_read_scanlines; lib.jpeg_resync_to_restart = jpeg_resync_to_restart; lib.jpeg_start_decompress = jpeg_start_decompress; lib.jpeg_std_error = jpeg_std_error; } ++lib.loaded; return 0; } void IMG_QuitJPG() { if ( lib.loaded == 0 ) { return; } if ( lib.loaded == 1 ) { } --lib.loaded; } #endif /* LOAD_JPG_DYNAMIC */ /* See if an image is contained in a data source */ int IMG_isJPG(SDL_RWops *src) { int start; int is_JPG; int in_scan; Uint8 magic[4]; /* This detection code is by <NAME> <<EMAIL>> */ /* Blame me, not Sam, if this doesn't work right. */ /* And don't forget to report the problem to the the sdl list too! */ if ( !src ) return 0; start = SDL_RWtell(src); is_JPG = 0; in_scan = 0; if ( SDL_RWread(src, magic, 1, 2) == 2 ) { if ( (magic[0] == 0xFF) && (magic[1] == 0xD8) ) { is_JPG = 1; while (is_JPG == 1) { if(SDL_RWread(src, magic, 1, 2) != 2) { is_JPG = 0; } else if( (magic[0] != 0xFF) && (in_scan == 0) ) { is_JPG = 0; } else if( (magic[0] != 0xFF) || (magic[1] == 0xFF) ) { /* Extra padding in JPEG (legal) */ /* or this is data and we are scanning */ SDL_RWseek(src, -1, RW_SEEK_CUR); } else if(magic[1] == 0xD9) { /* Got to end of good JPEG */ break; } else if( (in_scan == 1) && (magic[1] == 0x00) ) { /* This is an encoded 0xFF within the data */ } else if( (magic[1] >= 0xD0) && (magic[1] < 0xD9) ) { /* These have nothing else */ } else if(SDL_RWread(src, magic+2, 1, 2) != 2) { is_JPG = 0; } else { /* Yes, it's big-endian */ Uint32 start; Uint32 size; Uint32 end; start = SDL_RWtell(src); size = (magic[2] << 8) + magic[3]; end = SDL_RWseek(src, size-2, RW_SEEK_CUR); if ( end != start + size - 2 ) is_JPG = 0; if ( magic[1] == 0xDA ) { /* Now comes the actual JPEG meat */ #ifdef FAST_IS_JPEG /* Ok, I'm convinced. It is a JPEG. */ break; #else /* I'm not convinced. Prove it! */ in_scan = 1; #endif } } } /* Additional check */ if(!is_JPG && magic[0] == 0xFF && magic[1] == 0xE0) { SDL_RWseek(src, 6, RW_SEEK_SET); if(SDL_RWread(src, magic, 1, 4) == 4 && !strncasecmp((char*)magic, "JFIF", 4)) { is_JPG = 1; } } } } SDL_RWseek(src, start, RW_SEEK_SET); #ifdef DEBUG_IMGLIB fprintf(stderr, "IMG_isJPG: %d (%02x%02x%02x%02x)\n", is_JPG, magic[0], magic[1], magic[2], magic[3]); #endif return(is_JPG); } #define INPUT_BUFFER_SIZE 8192 typedef struct { struct jpeg_source_mgr pub; SDL_RWops *ctx; Uint8 buffer[INPUT_BUFFER_SIZE] __attribute__((aligned(32))); } my_source_mgr; /* * Initialize source --- called by jpeg_read_header * before any data is actually read. */ static void init_source (j_decompress_ptr cinfo) { /* We don't actually need to do anything */ return; } /* * Fill the input buffer --- called whenever buffer is emptied. */ static boolean fill_input_buffer (j_decompress_ptr cinfo) { my_source_mgr * src = (my_source_mgr *) cinfo->src; int nbytes; #if defined(HAVE_STDIO_H) && !defined(__DREAMCAST__) int fd = fileno(src->ctx->hidden.stdio.fp); if(fd > -1) { nbytes = read(fd, src->buffer, INPUT_BUFFER_SIZE); } else { SDL_RWread(src->ctx, src->buffer, INPUT_BUFFER_SIZE, 1); } #else nbytes = SDL_RWread(src->ctx, src->buffer, 1, INPUT_BUFFER_SIZE); #endif if (nbytes <= 0) { /* Insert a fake EOI marker */ src->buffer[0] = (Uint8) 0xFF; src->buffer[1] = (Uint8) JPEG_EOI; nbytes = 2; } src->pub.next_input_byte = src->buffer; src->pub.bytes_in_buffer = nbytes; return TRUE; } /* * Skip data --- used to skip over a potentially large amount of * uninteresting data (such as an APPn marker). * * Writers of suspendable-input applications must note that skip_input_data * is not granted the right to give a suspension return. If the skip extends * beyond the data currently in the buffer, the buffer can be marked empty so * that the next read will cause a fill_input_buffer call that can suspend. * Arranging for additional bytes to be discarded before reloading the input * buffer is the application writer's problem. */ static void skip_input_data (j_decompress_ptr cinfo, long num_bytes) { my_source_mgr * src = (my_source_mgr *) cinfo->src; /* Just a dumb implementation for now. Could use fseek() except * it doesn't work on pipes. Not clear that being smart is worth * any trouble anyway --- large skips are infrequent. */ if (num_bytes > 0) { while (num_bytes > (long) src->pub.bytes_in_buffer) { num_bytes -= (long) src->pub.bytes_in_buffer; (void) src->pub.fill_input_buffer(cinfo); /* note we assume that fill_input_buffer will never * return FALSE, so suspension need not be handled. */ } src->pub.next_input_byte += (size_t) num_bytes; src->pub.bytes_in_buffer -= (size_t) num_bytes; } } /* * Terminate source --- called by jpeg_finish_decompress * after all data has been read. */ static void term_source (j_decompress_ptr cinfo) { /* We don't actually need to do anything */ return; } /* * Prepare for input from a stdio stream. * The caller must have already opened the stream, and is responsible * for closing it after finishing decompression. */ static void jpeg_SDL_RW_src (j_decompress_ptr cinfo, SDL_RWops *ctx) { my_source_mgr *src; /* The source object and input buffer are made permanent so that a series * of JPEG images can be read from the same file by calling jpeg_stdio_src * only before the first one. (If we discarded the buffer at the end of * one image, we'd likely lose the start of the next one.) * This makes it unsafe to use this manager and a different source * manager serially with the same JPEG object. Caveat programmer. */ if (cinfo->src == NULL) { /* first time for this JPEG object? */ cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_source_mgr)); src = (my_source_mgr *) cinfo->src; } src = (my_source_mgr *) cinfo->src; src->pub.init_source = init_source; src->pub.fill_input_buffer = fill_input_buffer; src->pub.skip_input_data = skip_input_data; src->pub.resync_to_restart = lib.jpeg_resync_to_restart; /* use default method */ src->pub.term_source = term_source; src->ctx = ctx; src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ src->pub.next_input_byte = NULL; /* until buffer loaded */ } struct my_error_mgr { struct jpeg_error_mgr errmgr; jmp_buf escape; }; static void my_error_exit(j_common_ptr cinfo) { struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err; longjmp(err->escape, 1); } static void output_no_message(j_common_ptr cinfo) { /* do nothing */ } /* Load a JPEG type image from an SDL datasource */ SDL_Surface *IMG_LoadJPG_RW(SDL_RWops *src) { int start; struct jpeg_decompress_struct cinfo; JSAMPROW rowptr[1]; SDL_Surface *volatile surface = NULL; struct my_error_mgr jerr; if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); if ( !IMG_Init(IMG_INIT_JPG) ) { return NULL; } /* Create a decompression structure and load the JPEG header */ cinfo.err = lib.jpeg_std_error(&jerr.errmgr); jerr.errmgr.error_exit = my_error_exit; jerr.errmgr.output_message = output_no_message; if(setjmp(jerr.escape)) { /* If we get here, libjpeg found an error */ lib.jpeg_destroy_decompress(&cinfo); if ( surface != NULL ) { SDL_FreeSurface(surface); } SDL_RWseek(src, start, RW_SEEK_SET); IMG_SetError("JPEG loading error"); return NULL; } lib.jpeg_create_decompress(&cinfo); jpeg_SDL_RW_src(&cinfo, src); lib.jpeg_read_header(&cinfo, TRUE); if(cinfo.num_components == 4) { /* Set 32-bit Raw output */ cinfo.out_color_space = JCS_CMYK; cinfo.quantize_colors = FALSE; lib.jpeg_calc_output_dimensions(&cinfo); /* Allocate an output surface to hold the image */ surface = SDL_AllocSurface(SDL_SWSURFACE, cinfo.output_width, cinfo.output_height, 32, #if SDL_BYTEORDER == SDL_LIL_ENDIAN 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); #else 0x0000FF00, 0x00FF0000, 0xFF000000, 0x000000FF); #endif } else { /* Set 24-bit RGB output */ cinfo.out_color_space = JCS_RGB; cinfo.quantize_colors = FALSE; #ifdef FAST_JPEG cinfo.scale_num = 1; cinfo.scale_denom = 1; cinfo.dct_method = JDCT_FASTEST; cinfo.do_fancy_upsampling = FALSE; #endif lib.jpeg_calc_output_dimensions(&cinfo); /* Allocate an output surface to hold the image */ surface = SDL_AllocSurface(SDL_SWSURFACE, cinfo.output_width, cinfo.output_height, 24, #if SDL_BYTEORDER == SDL_LIL_ENDIAN 0x0000FF, 0x00FF00, 0xFF0000, #else 0xFF0000, 0x00FF00, 0x0000FF, #endif 0); } if ( surface == NULL ) { lib.jpeg_destroy_decompress(&cinfo); SDL_RWseek(src, start, RW_SEEK_SET); IMG_SetError("Out of memory"); return NULL; } /* Decompress the image */ lib.jpeg_start_decompress(&cinfo); while ( cinfo.output_scanline < cinfo.output_height ) { rowptr[0] = (JSAMPROW)(Uint8 *)surface->pixels + cinfo.output_scanline * surface->pitch; lib.jpeg_read_scanlines(&cinfo, rowptr, (JDIMENSION) 1); } lib.jpeg_finish_decompress(&cinfo); lib.jpeg_destroy_decompress(&cinfo); return(surface); } #else int IMG_InitJPG() { IMG_SetError("JPEG images are not supported"); return(-1); } void IMG_QuitJPG() { } /* See if an image is contained in a data source */ int IMG_isJPG(SDL_RWops *src) { return(0); } /* Load a JPEG type image from an SDL datasource */ SDL_Surface *IMG_LoadJPG_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_JPG */ #endif /* !defined(__APPLE__) || defined(SDL_IMAGE_USE_COMMON_BACKEND) */ <file_sep>/modules/ftpd/module.c /* DreamShell ##version## module.c - FTP server module Copyright (C)2023 SWAT */ #include <ds.h> #include <lftpd.h> DEFAULT_MODULE_HEADER(ftpd); typedef struct ftpd { int port; char *dir; kthread_t *thread; lftpd_t lftpd; } ftpd_t; void *ftpd_thread(void *param) { ftpd_t *srv = (ftpd_t *)param; lftpd_start(srv->dir, srv->port, &srv->lftpd); return NULL; } static void ftpd_free(void *ptr) { ftpd_t *srv = (ftpd_t *)ptr; lftpd_stop(&srv->lftpd); thd_join(srv->thread, NULL); free(srv->dir); free(srv); } static Item_list_t *servers; int builtin_ftpd_cmd(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s options args\n" "Options: \n" " -s, --start -Start FTP server\n" " -t, --stop -Stop FTP server\n\n"); ds_printf("Arguments: \n" " -p, --port -Server listen port (default 21)\n" " -d, --dir -Root directory (default /)\n\n" "Example: %s --start\n\n", argv[0], argv[0]); return CMD_NO_ARG; } int start_srv = 0, stop_srv = 0, port = 21; char *dir = NULL; Item_t *item; ftpd_t *srv; struct cfg_option options[] = { {"start", 's', NULL, CFG_BOOL, (void *) &start_srv, 0}, {"stop", 't', NULL, CFG_BOOL, (void *) &stop_srv, 0}, {"port", 'p', NULL, CFG_INT, (void *) &port, 0}, {"dir", 'd', NULL, CFG_STR, (void *) &dir, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(start_srv) { if (dir == NULL) { dir = strdup("/"); } item = listGetItemByName(servers, dir); if(item != NULL) { srv = (ftpd_t *)item->data; ds_printf("DS_ERROR: FTP server on port %d, root %s already running\n", srv->port, srv->dir); return CMD_ERROR; } ds_printf("DS_PROCESS: Starting FTP server on port %d, root %s\n", port, dir); srv = (ftpd_t *)malloc(sizeof(ftpd_t)); if (srv == NULL) { ds_printf("DS_ERROR: Out of memory\n"); return CMD_ERROR; } srv->port = port; srv->dir = dir; srv->thread = thd_create(0, ftpd_thread, (void *)srv); listAddItem(servers, LIST_ITEM_USERDATA, dir, srv, sizeof(ftpd_t)); return CMD_OK; } if(stop_srv) { item = listGetItemByName(servers, dir); if(item != NULL) { srv = (ftpd_t *)item->data; ds_printf("DS_PROCESS: Stopping FTP server on port %d, root %s\n", srv->port, srv->dir); listRemoveItem(servers, item, (listFreeItemFunc *)ftpd_free); } else { ds_printf("DS_ERROR: FTP server with root %s is not running\n"); } return CMD_OK; } return CMD_NO_ARG; } int lib_open(klibrary_t * lib) { servers = listMake(); AddCmd(lib_get_name(), "FTP server", (CmdHandler *) builtin_ftpd_cmd); return nmmgr_handler_add(&ds_ftpd_hnd.nmmgr); } int lib_close(klibrary_t * lib) { listDestroy(servers, (listFreeItemFunc *)ftpd_free); RemoveCmd(GetCmdByName(lib_get_name())); return nmmgr_handler_remove(&ds_ftpd_hnd.nmmgr); } <file_sep>/src/app/load.c /***************************** * DreamShell ##version## * * load.c * * DreamShell App loader * * Created by SWAT * * http://www.dc-swat.ru * ****************************/ #include "ds.h" //#define DEBUG 1 #ifdef DEBUG #define APP_LOAD_DEBUG #endif typedef struct lua_callback_data { lua_State *state; const char *script; } lua_callback_data_t; typedef struct export_callback_data { uint32 addr; GUI_Widget *widget; } export_callback_data_t; typedef struct scrollbar_callback_data { GUI_Widget *scroll; GUI_Widget *panel; } scrollbar_callback_data_t; static void parseNodeSize(mxml_node_t *node, SDL_Rect *parent, int *w, int *h); static void parseNodePosition(mxml_node_t *node, SDL_Rect *parent, int *x, int *y); static int parseAppResource(App_t *app, mxml_node_t *node); static int parseAppSurfaceRes(App_t *app, mxml_node_t *node, char *name); static int parseAppFontRes(App_t *app, mxml_node_t *node, char *name, char *src); static int parseAppImageRes(App_t *app, mxml_node_t *node, char *name, char *src); static int parseAppFileRes(App_t *app, mxml_node_t *node, char *name, char *src); static int parseAppTheme(App_t *app, mxml_node_t *node); static uint32 GetAppExportFuncAddr(const char *fstr); static GUI_Callback *CreateAppElementCallback(App_t *app, const char *event, GUI_Widget *widget); static GUI_Widget *parseAppElement(App_t *app, mxml_node_t *node, SDL_Rect *parent); static GUI_Widget *parseAppImageElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h); static GUI_Widget *parseAppLabelElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h); static GUI_Widget *parseAppButtonElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h); static GUI_Widget *parseAppToggleButtonElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h); static GUI_Widget *parseAppTextEntryElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h); static GUI_Widget *parseAppScrollBarElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h); static GUI_Widget *parseAppProgressBarElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h); static GUI_Widget *parseAppPanelElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h); static GUI_ListBox *parseAppListBoxElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h); static GUI_Widget *parseAppCardStackElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h); static GUI_Widget *parseAppRTFElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h); static GUI_Widget *parseAppFileManagerElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h); static GUI_Surface *getElementSurface(App_t *app, char *name); static GUI_Surface *getElementSurfaceTheme(App_t *app, mxml_node_t *node, char *attr); static GUI_Font *getElementFont(App_t *app, mxml_node_t *node, char *name); static void SetupAppLua(App_t *app) { if(app->lua == NULL) { //if(!GetCurApp()) //ResetLua(); app->lua = NewLuaThread(); lua_pushnumber(app->lua, app->id); lua_setglobal(app->lua, "THIS_APP_ID"); } } static uint32 GetAppExportFuncAddr(const char *fstr) { char evt[128]; if(sscanf(fstr, "export:%[0-9a-zA-Z_]", evt)) { return GET_EXPORT_ADDR(evt); } return -1; } int CallAppExportFunc(App_t *app, const char *fstr) { uint32 fa = GetAppExportFuncAddr(fstr); int r = 0; if(fa > 0 && fa != 0xffffffff) { EXPT_GUARD_BEGIN; void (*cb_func)(App_t *) = (void (*)(App_t *))fa; cb_func(app); r = 1; EXPT_GUARD_CATCH; r = 0; EXPT_GUARD_END; } return r; } /* static int parse_pos_size(char *num) { int len = strlen(num); if(num[len-1] == '%') { char n[4]; strncpy(n, num, len-1); int i = atoi(n); } else { return atoi(num); } }*/ int LoadApp(App_t *app, int build) { mxml_node_t *node; file_t fd; ds_printf("DS_PROCESS: Loading app %s ...\n", app->name); app->state |= APP_STATE_PROCESS; if(app->xml == NULL) { fd = fs_open(app->fn, O_RDONLY); if(fd == FILEHND_INVALID) { app->state &= ~APP_STATE_PROCESS; ds_printf("DS_ERROR: Can't load app %s\n", app->fn); return 0; } if((app->xml = mxmlLoadFd(NULL, fd, NULL)) == NULL) { app->state &= ~APP_STATE_PROCESS; ds_printf("DS_ERROR: Can't parse xml %s\n", app->fn); fs_close(fd); return 0; } fs_close(fd); } if((node = mxmlFindElement(app->xml, app->xml, "body", NULL, NULL, MXML_DESCEND)) != NULL) { #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Creating empty app body...\n"); #endif int x, y, w, h; parseNodeSize(node, NULL, &w, &h); parseNodePosition(node, NULL, &x, &y); app->body = GUI_PanelCreate(app->name, x, y, w, h); } else { ds_printf("DS_ERROR: <body> element not found\n"); app->state &= ~APP_STATE_PROCESS; return 0; } #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Loading app resources...\n"); #endif app->resources = listMake(); app->elements = listMake(); if((node = mxmlFindElement(app->xml, app->xml, "resources", NULL, NULL, MXML_DESCEND)) != NULL) { node = node->child->next; while(node) { if(node->type == MXML_ELEMENT) { if(!parseAppResource(app, node)) { app->state &= ~APP_STATE_PROCESS; UnLoadApp(app); return 0; } } node = node->next; } } app->state |= APP_STATE_LOADED; if(build) { return BuildAppBody(app); } else { app->state &= ~APP_STATE_PROCESS; return 1; } } int BuildAppBody(App_t *app) { mxml_node_t *node; int x, y, w, h; GUI_Widget *el; GUI_Surface *s = NULL; SDL_Rect body_area; if((node = mxmlFindElement(app->xml, app->xml, "body", NULL, NULL, MXML_DESCEND)) != NULL) { #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Build app body...\n"); #endif if(!app->body) { parseNodeSize(node, NULL, &w, &h); parseNodePosition(node, NULL, &x, &y); app->body = GUI_PanelCreate(app->name, x, y, w, h); } if(!app->body) return 0; char *onload = FindXmlAttr("onload", node, NULL); char *bg = FindXmlAttr("background", node, NULL); if(bg != NULL) { if(*bg == '#') { SDL_Color c; unsigned int r = 0, g = 0, b = 0; sscanf(bg, "#%02x%02x%02x", &r, &g, &b); c.r = r; c.g = g; c.b = b; c.unused = 0; GUI_PanelSetBackgroundColor(app->body, c); } else if((s = getElementSurface(app, bg)) != NULL) { GUI_PanelSetBackground(app->body, s); } else { ds_printf("DS_ERROR: Can't find resource '%s' or resource is not surface\n", bg); } } node = node->child->next; body_area = GUI_WidgetGetArea(app->body); while(node) { if(node->type == MXML_ELEMENT && node->value.element.name[0] != '!') { if((el = parseAppElement(app, node, &body_area)) != NULL) { GUI_ContainerAdd(app->body, el); const char *n = GUI_ObjectGetName((GUI_Object *) el); if(n == NULL) { GUI_ObjectDecRef((GUI_Object *) el); } else { listAddItem(app->elements, LIST_ITEM_GUI_WIDGET, n, (void *) el, 0); } } } node = node->next; } app->state &= ~APP_STATE_PROCESS; app->state |= APP_STATE_READY; if(onload != NULL) { #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Call to onload event...\n"); #endif if(!strncmp(onload, "export:", 7)) { CallAppExportFunc(app, onload); } else if(!strncmp(onload, "console:", 8)) { dsystem_buff(onload + 8); } else { SetupAppLua(app); //lua_checkstack(app->lua, 2048); //LockVideo(); LuaDo(LUA_DO_STRING, onload, app->lua); //UnlockVideo(); } } //return 1; } else { app->state &= ~APP_STATE_PROCESS; app->state |= APP_STATE_READY; ds_printf("DS_WARNING: Can't find <body> in app.xml, GUI screen will not be changed.\n"); } return 1; } int UnLoadApp(App_t *app) { if(!(app->state & APP_STATE_LOADED)) { return 1; } CallAppBodyEvent(app, "onunload"); app->state |= APP_STATE_PROCESS; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Free app body...\n"); #endif if(app->body != NULL) { //App_t *a = GetCurApp(); /* if(a->id == app->id) { //LockVideo(); } */ GUI_ObjectDecRef((GUI_Object *) app->body); app->body = NULL; /* if(a->id == app->id) { //UnlockVideo(); }*/ } #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Unloading app elements...\n"); #endif if(app->elements) { UnloadAppResources(app->elements); app->elements = NULL; } #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Unloading app resources...\n"); #endif if(app->resources) { UnloadAppResources(app->resources); app->resources = NULL; } #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Closing app lua state...\n"); #endif if(app->lua != NULL) { //lua_close(app->lua); app->lua = NULL; } #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Destroy app thread...\n"); #endif if(app->thd != NULL) { thd_join(app->thd, NULL); app->thd = NULL; } #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Deleting XML node tree...\n"); #endif if(app->xml) { mxmlDelete(app->xml); app->xml = NULL; } #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Clear flags...\n"); #endif app->state = 0; //&= ~(APP_STATE_LOADED | APP_STATE_READY | APP_STATE_PROCESS | APP_STATE_WAIT_UNLOAD); #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: App unload complete.\n"); #endif return 1; } void UnloadAppResources(Item_list_t *lst) { Item_t *c, *n; c = SLIST_FIRST(lst); while(c) { n = SLIST_NEXT(c, list); if(c->type == LIST_ITEM_MODULE) { if(c->data) CloseModule((Module_t *) c->data); } else if(c->type == LIST_ITEM_SDL_RWOPS) { if(c->data) SDL_FreeRW(c->data); } else if(c->type == LIST_ITEM_GUI_SURFACE || c->type == LIST_ITEM_GUI_WIDGET || c->type == LIST_ITEM_GUI_FONT) { if(c->data) { #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Unloading: %s\n", GUI_ObjectGetName((GUI_Object *) c->data)); #endif GUI_ObjectDecRef((GUI_Object *) c->data); //ds_printf("DS_DEBUG: Unloaded: %8x\n", (uint32)c->data); } } else { if(c->data && c->size) free(c->data); } free(c); c = n; } SLIST_INIT(lst); free(lst); } char *FindXmlAttr(char *name, mxml_node_t *node, char *defValue) { char *attr = (char*)mxmlElementGetAttr(node, name); return attr != NULL ? attr : defValue; } static void parseNodeSize(mxml_node_t *node, SDL_Rect *parent, int *w, int *h) { int parent_w, parent_h; float tmp; char *width = FindXmlAttr("width", node, "100%"); char *height = FindXmlAttr("height", node, "100%"); if(parent) { parent_w = parent->w; parent_h = parent->h; } else { parent_w = GetScreenWidth(); parent_h = GetScreenHeight(); } if(width[strlen(width)-1] == '%') { if(!strncmp(width, "100%", 4)) { *w = parent_w; } else { tmp = ((float)parent_w / 100); *w = tmp * (float)atoi(width); } } else { *w = atoi(width); } if(height[strlen(height)-1] == '%') { if(!strncmp(height, "100%", 4)) { *h = parent_h; } else { tmp = ((float)parent_h / 100); *h = tmp * (float)atoi(height); } } else { *h = atoi(height); } } static void parseNodePosition(mxml_node_t *node, SDL_Rect *parent, int *x, int *y) { int parent_w, parent_h; float tmp; char *xp = FindXmlAttr("x", node, "0"); char *yp = FindXmlAttr("y", node, "0"); if(parent) { parent_w = parent->w; parent_h = parent->h; } else { parent_w = GetScreenWidth(); parent_h = GetScreenHeight(); } if(*xp == '0') { *x = 0; } else if(xp[strlen(xp)-1] == '%') { tmp = ((float)parent_w / 100); *x = tmp * (float)atoi(xp); } else { *x = atoi(xp); } if(*yp == '0') { *y = 0; } else if(yp[strlen(yp)-1] == '%') { tmp = ((float)parent_h / 100); *y = tmp * (float)atoi(yp); } else { *y = atoi(yp); } } static int alignStrToFlag(char *align) { if(!strncmp(align, "center", 6)) return WIDGET_HORIZ_CENTER; else if(!strncmp(align, "right", 5)) return WIDGET_HORIZ_RIGHT; else if(!strncmp(align, "left", 4)) return WIDGET_HORIZ_LEFT; else return 0; } static int valignStrToFlag(char *valign) { if(!strncmp(valign, "center", 6)) return WIDGET_VERT_CENTER; else if(!strncmp(valign, "top", 3)) return WIDGET_VERT_TOP; else if(!strncmp(valign, "bottom", 6)) return WIDGET_VERT_BOTTOM; else return 0; } void *getAppElement(App_t *app, const char *name, ListItemType type) { Item_t *item; switch(type) { case LIST_ITEM_GUI_WIDGET: item = listGetItemByName(app->elements, name); break; case LIST_ITEM_GUI_SURFACE: case LIST_ITEM_GUI_FONT: default: item = listGetItemByNameAndType(app->resources, name, type); break; } if(item != NULL && item->type == type) { return item->data; } ds_printf("DS_ERROR: %s: Couldn't find or wrong type '%s'\n", app->name, name); return NULL; } static GUI_Surface *getElementSurface(App_t *app, char *name) { GUI_Surface *s = NULL; Item_t *res; if(name != NULL) { if((res = listGetItemByName(app->resources, name)) != NULL && res->type == LIST_ITEM_GUI_SURFACE) { s = (GUI_Surface *) res->data; } else { char file[NAME_MAX]; relativeFilePath_wb(file, app->fn, name); s = GUI_SurfaceLoad(file); if(s != NULL) listAddItem(app->resources, LIST_ITEM_GUI_SURFACE, name, (void *) s, 0); } } return s; } static GUI_Surface *getElementSurfaceTheme(App_t *app, mxml_node_t *node, char *attr) { Item_t *item; mxml_node_t *n; char *value = FindXmlAttr(attr, node, NULL); #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Get surface %s for %s\n", attr, node->value.element.name); #endif if(value) { return getElementSurface(app, value); } value = FindXmlAttr("theme", node, NULL); if(value) { #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Search theme %s\n", value); #endif item = listGetItemByNameAndType(app->resources, value, LIST_ITEM_XML_NODE); if(item) { #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Found theme %s\n", value); #endif n = (mxml_node_t *)item->data; value = FindXmlAttr(attr, n, NULL); if(value) { return getElementSurface(app, value); } } } if(!strncmp(node->value.element.name, "input", 5)) { value = FindXmlAttr("type", node, node->value.element.name); } else { value = node->value.element.name; } #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Search theme %s\n", value); #endif item = listGetItemByNameAndType(app->resources, value, LIST_ITEM_XML_NODE); if(item) { #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Found theme %s\n", value); #endif n = (mxml_node_t *)item->data; value = FindXmlAttr(attr, n, NULL); if(value) { return getElementSurface(app, value); } } return NULL; } static GUI_Font *getElementFont(App_t *app, mxml_node_t *node, char *name) { GUI_Font *fnt = NULL; Item_t *res; if(name != NULL) { if((res = listGetItemByName(app->resources, name)) != NULL && res->type == LIST_ITEM_GUI_FONT) { fnt = (GUI_Font *) res->data; } else { char file[NAME_MAX]; relativeFilePath_wb(file, app->fn, name); fnt = GUI_FontLoadTrueType(file, atoi(FindXmlAttr("fontsize", node, "12"))); if(fnt != NULL) listAddItem(app->resources, LIST_ITEM_GUI_FONT, name, (void *) fnt, 0); } } return fnt; } static Uint32 parseAppSurfColor(GUI_Surface *surface, char *color) { Uint32 c = 0; uint r = 0, g = 0, b = 0, a = 0, cnt = 0; cnt = sscanf(color, "#%02x%02x%02x%02x", &r, &g, &b, &a); if(cnt == 4) { c = GUI_SurfaceMapRGBA(surface, r, g, b, a); } else { c = GUI_SurfaceMapRGB(surface, r, g, b); } return c; } static void parseAppSurfaceAlign(mxml_node_t *node, SDL_Rect *rect, SDL_Rect *surf_area) { char *align = FindXmlAttr("align", node, NULL); char *valign = FindXmlAttr("valign", node, NULL); if(align) { switch (alignStrToFlag(align)) { case WIDGET_HORIZ_CENTER: rect->x = (surf_area->w - rect->w) / 2; break; case WIDGET_HORIZ_LEFT: rect->x = 0; break; case WIDGET_HORIZ_RIGHT: rect->x = surf_area->w - rect->w; break; default: break; } } if(valign) { switch (valignStrToFlag(valign)) { case WIDGET_VERT_CENTER: rect->y = (surf_area->h - rect->h) / 2; break; case WIDGET_VERT_TOP: rect->y = 0; break; case WIDGET_VERT_BOTTOM: rect->y = surf_area->h - rect->h; break; default: break; } } } static void parseAppSurfaceFill(App_t *app, mxml_node_t *node, GUI_Surface *surface, Uint32 c) { SDL_Rect rect, surf_area; int xr, yr, wr, hr; surf_area.w = GUI_SurfaceGetWidth(surface); surf_area.h = GUI_SurfaceGetHeight(surface); parseNodeSize(node, &surf_area, &wr, &hr); parseNodePosition(node, &surf_area, &xr, &yr); if(wr == surf_area.w && xr) { wr -= xr; } if(hr == surf_area.h && yr) { hr -= yr; } rect.x = xr; rect.y = yr; rect.w = wr; rect.h = hr; parseAppSurfaceAlign(node, &rect, &surf_area); #ifdef APP_LOAD_DEBUG ds_printf("Fill surface: x=%d y=%d w=%d h=%d color=%08lx\n", rect.x, rect.y, rect.w, rect.h, c); #endif GUI_SurfaceFill(surface, &rect, c); } static void parseAppSurfaceBlit(App_t *app, mxml_node_t *node, GUI_Surface *surface) { char *src = NULL; SDL_Rect area, rect, surf_area; int xr, yr, wr, hr; area.x = area.y = 0; surf_area.w = GUI_SurfaceGetWidth(surface); surf_area.h = GUI_SurfaceGetHeight(surface); parseNodeSize(node, &surf_area, &wr, &hr); parseNodePosition(node, &surf_area, &xr, &yr); if(wr == surf_area.w && xr) { wr -= xr; } if(hr == surf_area.h && yr) { hr -= yr; } rect.x = xr; rect.y = yr; rect.w = wr; rect.h = hr; src = FindXmlAttr("surface", node, NULL); if(src != NULL) { Item_t *res; GUI_Surface *surf = NULL; int decref = 0; char file[NAME_MAX]; if((res = listGetItemByName(app->resources, src)) != NULL) { if(res->type == LIST_ITEM_GUI_SURFACE) { surf = (GUI_Surface *) res->data; } } else { relativeFilePath_wb(file, app->fn, src); surf = GUI_SurfaceLoad(file); decref = 1; } if(surf != NULL) { wr = GUI_SurfaceGetWidth(surf); hr = GUI_SurfaceGetHeight(surf); if(rect.w > wr) { rect.w = wr; } if(rect.h > hr) { rect.h = hr; } parseAppSurfaceAlign(node, &rect, &surf_area); #ifdef APP_LOAD_DEBUG ds_printf("Blit surface: x=%d y=%d w=%d h=%d surface=%s\n", rect.x, rect.y, rect.w, rect.h, decref ? file : src); #endif if(wr > surf_area.w) { area.x = (wr - surf_area.w) / 2; } if(hr > surf_area.h) { area.y = (hr - surf_area.h) / 2; } area.w = rect.w; area.h = rect.h; GUI_SurfaceBlit(surf, &area, surface, &rect); if(decref) GUI_ObjectDecRef((GUI_Object*)surf); } } } static void parseAppSurfaceRect(App_t *app, mxml_node_t *node, GUI_Surface *surface, Uint32 c) { Sint16 x1, y1, x2, y2; x1 = atoi(FindXmlAttr("x1", node, "0")); y1 = atoi(FindXmlAttr("y1", node, "0")); x2 = atoi(FindXmlAttr("x2", node, "0")); y2 = atoi(FindXmlAttr("y2", node, "0")); #ifdef APP_LOAD_DEBUG ds_printf("Rect surface: x1=%d y1=%d x2=%d y2=%d color=%08x\n", x1, y1, x2, y2, c); #endif GUI_SurfaceRectagle(surface, x1, y1, x2, y2, c); } static void parseAppSurfaceLine(App_t *app, mxml_node_t *node, GUI_Surface *surface, Uint32 c) { Sint16 x1, y1, x2, y2; char *aa; int width; x1 = atoi(FindXmlAttr("x1", node, "0")); y1 = atoi(FindXmlAttr("y1", node, "0")); x2 = atoi(FindXmlAttr("x2", node, "0")); y2 = atoi(FindXmlAttr("y2", node, "0")); width = atoi(FindXmlAttr("w", node, "0")); aa = FindXmlAttr("aa", node, "false"); #ifdef APP_LOAD_DEBUG ds_printf("Line surface: x1=%d y1=%d x2=%d y2=%d color=%08x\n", x1, y1, x2, y2, c); #endif if(!strncmp(aa, "true", 4)) { GUI_SurfaceLineAA(surface, x1, y1, x2, y2, c); } else if(width > 0) { GUI_SurfaceThickLine(surface, x1, y1, x2, y2, (Uint8)width, c); } else { GUI_SurfaceLine(surface, x1, y1, x2, y2, c); } } static void parseAppSurfaceCircle(App_t *app, mxml_node_t *node, GUI_Surface *surface, Uint32 c) { Sint16 x, y, rad; char *aa, *fill; x = atoi(FindXmlAttr("x1", node, "0")); y = atoi(FindXmlAttr("y1", node, "0")); rad = atoi(FindXmlAttr("rad", node, "0")); aa = FindXmlAttr("aa", node, "false"); fill = FindXmlAttr("aa", node, "false"); #ifdef APP_LOAD_DEBUG ds_printf("Circle surface: x=%d y=%d rad=%d color=%08x\n", x, y, rad, c); #endif if(!strcmp(aa, "true")) { GUI_SurfaceCircleAA(surface, x, y, rad, c); } else if(!strcmp(fill, "true")) { GUI_SurfaceCircleFill(surface, x, y, rad, c); } else { GUI_SurfaceCircle(surface, x, y, rad, c); } } static void parseAppSurfaceTrigon(App_t *app, mxml_node_t *node, GUI_Surface *surface, Uint32 c) { Sint16 x1, y1, x2, y2, x3, y3; char *aa, *fill; x1 = atoi(FindXmlAttr("x1", node, "0")); y1 = atoi(FindXmlAttr("y1", node, "0")); x2 = atoi(FindXmlAttr("x2", node, "0")); y2 = atoi(FindXmlAttr("y2", node, "0")); x3 = atoi(FindXmlAttr("x3", node, "0")); y3 = atoi(FindXmlAttr("y3", node, "0")); aa = FindXmlAttr("aa", node, "false"); fill = FindXmlAttr("aa", node, "false"); #ifdef APP_LOAD_DEBUG ds_printf("Trigon surface: x1=%d y1=%d x2=%d y2=%d x3=%d y3=%d color=%08x\n", x1, y1, x2, y2, x3, y3, c); #endif if(!strncmp(aa, "true", 4)) { GUI_SurfaceTrigonAA(surface, x1, y1, x2, y2, x3, y3, c); } else if(!strncmp(fill, "true", 4)) { GUI_SurfaceTrigonFill(surface, x1, y1, x2, y2, x3, y3, c); } else { GUI_SurfaceTrigon(surface, x1, y1, x2, y2, x3, y3, c); } } static void parseAppSurfaceBezier(App_t *app, mxml_node_t *node, GUI_Surface *surface, Uint32 c) { Sint16 vx; Sint16 vy; int n; int s; vx = atoi(FindXmlAttr("x", node, "0")); vy = atoi(FindXmlAttr("y", node, "0")); n = atoi(FindXmlAttr("n", node, "0")); s = atoi(FindXmlAttr("s", node, "0")); #ifdef APP_LOAD_DEBUG ds_printf("Bezier surface: vx=%d vy=%d n=%d s=%d color=%08x\n", vx, vy, n, s, c); #endif GUI_SurfaceBezier(surface, &vx, &vy, n, s, c); } static int parseAppResource(App_t *app, mxml_node_t *node) { if(node->value.element.name[0] == '!') return 1; char *s = FindXmlAttr("src", node, NULL); char src[NAME_MAX]; if(s == NULL && strncmp(node->value.element.name, "surface", 7) && strncmp(node->value.element.name, "theme", 5)) { ds_printf("DS_ERROR: Empty src attribute in %s\n", node->value.element.name); return 0; } else { relativeFilePath_wb(src, app->fn, s); } char *name = FindXmlAttr("name", node, NULL); if(!strncmp(node->value.element.name, "font", 4)) { return parseAppFontRes(app, node, name, src); } else if(!strncmp(node->value.element.name, "image", 5)) { return parseAppImageRes(app, node, name, src); } else if(!strncmp(node->value.element.name, "surface", 7)) { return parseAppSurfaceRes(app, node, name); } else if(!strncmp(node->value.element.name, "script", 6)) { #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Loading %s %s type %s\n", node->value.element.name, src, FindXmlAttr("type", node, "text/lua")); #endif if(!strncmp(FindXmlAttr("type", node, "text/lua"), "text/lua", 8)) { SetupAppLua(app); if(app->lua != NULL) { LuaDo(LUA_DO_FILE, src, app->lua); } else { ds_printf("DS_ERROR: Can't initialize lua thread for %s\n", src); return 0; } } } else if(!strncmp(node->value.element.name, "module", 6)) { #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Loading %s %s\n", node->value.element.name, src); #endif Module_t *m = OpenModule(src); if(m == NULL) { ds_printf("DS_ERROR: Can't load module %s\n", src); return 0; } else { listAddItem(app->resources, LIST_ITEM_MODULE, m->lib_get_name(), (void *) m, sizeof(Module_t)); } } else if(!strncmp(node->value.element.name, "file", 4)) { return parseAppFileRes(app, node, name, src); } else if(!strncmp(node->value.element.name, "theme", 5)) { return parseAppTheme(app, node); } else { ds_printf("DS_ERROR: Uknown resurce - %s\n", node->value.element.name); } return 1; } static int parseAppSurfaceRes(App_t *app, mxml_node_t *node, char *name) { GUI_Surface *surface = NULL; mxml_node_t *n; int alpha, w, h;//, flags = 0; Uint32 c = 0xFFFFFFFF; char *color = NULL; #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Creating %s \"%s\"\n", node->value.element.name, name); #endif SDL_Rect parent_area = GUI_WidgetGetArea(app->body); parseNodeSize(node, &parent_area, &w, &h); alpha = atoi(FindXmlAttr("alpha", node, "-1")); SDL_Surface *screen = GetScreen(); /* flags = screen->flags; if(alpha > -1) { flags |= SDL_SRCALPHA; }*/ surface = GUI_SurfaceCreate(name, screen->flags | SDL_SRCALPHA, w, h, screen->format->BitsPerPixel, screen->format->Rmask, screen->format->Gmask, screen->format->Bmask, screen->format->Amask); if(surface == NULL) { ds_printf("DS_ERROR: Can't create surface \"%s\"\n", name); return 0; } n = node->child->next; while(n) { if(n->type == MXML_ELEMENT) { color = FindXmlAttr("color", n, "#FFFFFF"); if(color != NULL) { c = parseAppSurfColor(surface, color); } if(!strncmp(n->value.element.name, "fill", 4)) { parseAppSurfaceFill(app, n, surface, c); } else if(!strncmp(n->value.element.name, "blit", 4)) { parseAppSurfaceBlit(app, n, surface); } else if(!strncmp(n->value.element.name, "rect", 4)) { parseAppSurfaceRect(app, n, surface, c); } else if(!strncmp(n->value.element.name, "line", 4)) { parseAppSurfaceLine(app, n, surface, c); } else if(!strncmp(n->value.element.name, "circle", 6)) { parseAppSurfaceCircle(app, n, surface, c); } else if(!strncmp(n->value.element.name, "trigon", 6)) { parseAppSurfaceTrigon(app, n, surface, c); } else if(!strncmp(n->value.element.name, "bezier", 6)) { parseAppSurfaceBezier(app, n, surface, c); } } n = n->next; } if(alpha >= 0) { GUI_SurfaceSetAlpha(surface, SDL_SRCALPHA|SDL_ALPHA_TRANSPARENT, alpha); } listAddItem(app->resources, LIST_ITEM_GUI_SURFACE, name, (void *)surface, 0); return 1; } static int parseAppFontRes(App_t *app, mxml_node_t *node, char *name, char *src) { #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Loading %s %s size %d\n", node->value.element.name, src, atoi(FindXmlAttr("size", node, "12"))); #endif char *type = FindXmlAttr("type", node, "ttf"); GUI_Font *f = NULL; if(!strncmp(type, "bitmap", 6)) { f = GUI_FontLoadBitmap(src); } else if(!strcmp(type, "ttf")) { f = GUI_FontLoadTrueType(src, atoi(FindXmlAttr("size", node, "12"))); } if(f == NULL) { ds_printf("DS_ERROR: Can't load font %s\n", src); return 0; } listAddItem(app->resources, LIST_ITEM_GUI_FONT, name, (void *) f, 0); return 1; } static int parseAppImageRes(App_t *app, mxml_node_t *node, char *name, char *src) { #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Loading %s %s\n", node->value.element.name, src); #endif GUI_Surface *s; SDL_Rect r; char *x = FindXmlAttr("x", node, NULL); char *y = FindXmlAttr("y", node, NULL); char *w = FindXmlAttr("width", node, NULL); char *h = FindXmlAttr("height", node, NULL); if(x || y || w || h) { r.x = x ? atoi(x) : 0; r.y = y ? atoi(y) : 0; r.w = w ? atoi(w) : 0; r.h = h ? atoi(h) : 0; s = GUI_SurfaceLoad_Rect(src, &r); } else { s = GUI_SurfaceLoad(src); } if(s == NULL) { ds_printf("DS_ERROR: Can't load image %s\n", src); return 0; } listAddItem(app->resources, LIST_ITEM_GUI_SURFACE, name, (void *) s, 0); return 1; } static int parseAppFileRes(App_t *app, mxml_node_t *node, char *name, char *src) { #ifdef APP_LOAD_DEBUG ds_printf("DS_PROCESS: Loading %s %s\n", node->value.element.name, src); #endif char *ftype = FindXmlAttr("type", node, "basic"); if(!strncmp(ftype, "rwops", 5)) { SDL_RWops *rw = SDL_RWFromFile(src, "rb"); if(rw == NULL) { ds_printf("DS_ERROR: Can't load file %s\n", src); return 0; } else { listAddItem(app->resources, LIST_ITEM_SDL_RWOPS, name, (void *) rw, FileSize(src)); } } else { file_t f = fs_open(src, O_RDONLY); if(f == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open file: %s\n", src); return 0; } uint32 size = fs_total(f); uint8 *buff = (uint8*) malloc(size); if(!buff) { fs_close(f); return 0; } fs_read(f, buff, size); fs_close(f); listAddItem(app->resources, LIST_ITEM_USERDATA, name, (void *) buff, size); } return 1; } static int parseAppTheme(App_t *app, mxml_node_t *node) { mxml_node_t *n; char *name; if(node->child && node->child->next) { n = node->child->next; while(n) { if(n->type == MXML_ELEMENT && n->value.element.name[0] != '!') { name = FindXmlAttr("name", n, NULL); if(!name) { if(!strncmp(n->value.element.name, "input", 5)) { name = FindXmlAttr("type", n, n->value.element.name); } else { name = n->value.element.name; } } #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Creating theme - %s\n", name); #endif listAddItem(app->resources, LIST_ITEM_XML_NODE, name, (void *)n, 0); } n = n->next; } } return 1; } static GUI_Widget *parseAppElement(App_t *app, mxml_node_t *node, SDL_Rect *parent) { int x, y, w, h; GUI_Widget *widget; char *attr, *name; parseNodeSize(node, parent, &w, &h); parseNodePosition(node, parent, &x, &y); if(w == parent->w && x) { w -= x; } if(h == parent->h && y) { h -= y; } name = FindXmlAttr("name", node, NULL); if(!strncmp(node->value.element.name, "image", 5)) { widget = parseAppImageElement(app, node, name, x, y, w, h); } else if(!strncmp(node->value.element.name, "label", 5)) { widget = parseAppLabelElement(app, node, name, x, y, w, h); } else if(!strncmp(node->value.element.name, "input", 5)) { char *type = FindXmlAttr("type", node, "unknown"); if(!strncmp(type, "button", 6)) { widget = parseAppButtonElement(app, node, name, x, y, w, h); } else if(!strncmp(type, "checkbox", 8)) { widget = parseAppToggleButtonElement(app, node, name, x, y, w, h); } else if(!strncmp(type, "text", 4)) { widget = parseAppTextEntryElement(app, node, name, x, y, w, h); } else { return NULL; } } else if(!strncmp(node->value.element.name, "scrollbar", 9)) { widget = parseAppScrollBarElement(app, node, name, x, y, w, h); } else if(!strncmp(node->value.element.name, "progressbar", 11)) { widget = parseAppProgressBarElement(app, node, name, x, y, w, h); } else if(!strncmp(node->value.element.name, "panel", 5)) { widget = parseAppPanelElement(app, node, name, x, y, w, h); } else if(!strncmp(node->value.element.name, "listbox", 7)) { widget = (GUI_Widget *) parseAppListBoxElement(app, node, name, x, y, w, h); } else if(!strncmp(node->value.element.name, "cardstack", 9)) { widget = parseAppCardStackElement(app, node, name, x, y, w, h); } else if(!strncmp(node->value.element.name, "rtf", 3)) { widget = parseAppRTFElement(app, node, name, x, y, w, h); } else if(!strncmp(node->value.element.name, "filemanager", 11)) { widget = parseAppFileManagerElement(app, node, name, x, y, w, h); /* } else if(!strcmp(node->value.element.name, "nanox")) { widget = parseAppNanoXElement(app, node, name, x, y, w, h); */ } else { return NULL; } if(widget == NULL) { return NULL; } attr = FindXmlAttr("align", node, NULL); char *valign = FindXmlAttr("valign", node, NULL); if(attr || valign) { int align_flags = 0; if(attr) { align_flags |= alignStrToFlag(attr); } if(valign) { align_flags |= valignStrToFlag(valign); } GUI_WidgetSetAlign(widget, align_flags); } attr = FindXmlAttr("tile", node, NULL); if(attr) { GUI_Surface *surface = getElementSurface(app, attr); if(surface != NULL) { GUI_WidgetTileImage(widget, surface, NULL, 0, 0); } } attr = FindXmlAttr("visibility", node, NULL); if(attr) { if(!strncmp(attr, "false", 5)) { GUI_WidgetSetFlags(widget, WIDGET_HIDDEN); } else { GUI_WidgetClearFlags(widget, WIDGET_HIDDEN); } GUI_WidgetMarkChanged(widget); } attr = FindXmlAttr("transparent", node, NULL); if(attr) GUI_WidgetSetTransparent(widget, atoi(attr)); attr = FindXmlAttr("inactive", node, NULL); if(attr) GUI_WidgetSetEnabled(widget, 0); return widget; } static GUI_Widget *parseAppImageElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h) { GUI_Surface *s; GUI_Widget *img; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing Image: %s\n", name); #endif if((s = getElementSurface(app, FindXmlAttr("src", node, NULL))) == NULL) return NULL; img = GUI_PictureCreate(name, x, y, w, h, s); if(node->child && node->child->next && node->child->next->value.element.name[0] != '!') { #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing Image Child: %s\n", node->child->next->value.element.name); #endif SDL_Rect parent_area = GUI_WidgetGetArea(img); GUI_Widget *el = parseAppElement(app, node->child->next, &parent_area); if(el != NULL) { const char *n = GUI_ObjectGetName((GUI_Object *) el); GUI_PictureSetCaption(img, el); if(n == NULL) { GUI_ObjectDecRef((GUI_Object *) el); } else { listAddItem(app->elements, LIST_ITEM_GUI_WIDGET, n, (void *) el, 0); } } } //#ifdef APP_LOAD_DEBUG // ds_printf("Image: %s x=%d y=%d w=%d h=%d\n", name, x, y, w, h); //#endif return img; } static GUI_Widget *parseAppLabelElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h) { GUI_Font *font; char *src; GUI_Widget *label; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing Label: %s\n", name); #endif src = FindXmlAttr("font", node, NULL); if(src == NULL || (font = getElementFont(app, node, src)) == NULL) { ds_printf("DS_ERROR: Can't find font '%s'\n", src); return NULL; } label = GUI_LabelCreate(name, x, y, w, h, font, FindXmlAttr("text", node, " ")); if(label == NULL) return NULL; //Uint32 c = colorHexToRGB(FindXmlAttr("color", node, "#ffffff"), &clr); char *color = FindXmlAttr("color", node, NULL); unsigned int r = 0, g = 0, b = 0; if(color != NULL) { sscanf(color, "#%02x%02x%02x", &r, &g, &b); } #ifdef APP_LOAD_DEBUG ds_printf("Label (%s): %s | Color: %d.%d.%d | font: %s\n", name, FindXmlAttr("text", node, " "), r, g, b, src); #endif GUI_LabelSetTextColor(label, r, g, b); return label; } static GUI_Widget *parseAppRTFElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h) { GUI_Widget *widget; char *src, *color, *offset, *freesrc, *font; unsigned int r = 0, g = 0, b = 0; Item_t *item; SDL_RWops *rwf; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing RTF: %s\n", name); #endif src = FindXmlAttr("file", node, NULL); if(src == NULL) { return NULL; } font = FindXmlAttr("font", node, NULL); item = listGetItemByNameAndType(app->resources, src, LIST_ITEM_SDL_RWOPS); if(item != NULL) { rwf = (SDL_RWops *) item->data; freesrc = FindXmlAttr("freesrc", node, "0"); widget = GUI_RTF_LoadRW(name, rwf, atoi(freesrc), font, x, y, w, h); } else { char file[NAME_MAX]; relativeFilePath_wb(file, app->fn, src); widget = GUI_RTF_Load(name, file, font, x, y, w, h); } color = FindXmlAttr("bgcolor", node, NULL); if(color != NULL) { sscanf(color, "#%02x%02x%02x", &r, &g, &b); GUI_RTF_SetBgColor(widget, r, g, b); } offset = FindXmlAttr("offset", node, NULL); if(offset != NULL) { GUI_RTF_SetOffset(widget, atoi(offset)); } return widget; } static void lua_callback_function(void *data) { lua_callback_data_t *d = (lua_callback_data_t *) data; LuaDo(LUA_DO_STRING, d->script, (lua_State *) d->state); } static void export_callback_function(void *data) { export_callback_data_t *d = (export_callback_data_t *) data; EXPT_GUARD_BEGIN; void (*func)(GUI_Widget *widget) = (void (*)(GUI_Widget *widget))d->addr; func(d->widget); EXPT_GUARD_CATCH; EXPT_GUARD_END; } static void cmd_callback_function(void *data) { dsystem_buff((char *)data); } static GUI_Callback *CreateAppElementCallback(App_t *app, const char *event, GUI_Widget *widget) { GUI_Callback *cb = NULL; if(!strncmp(event, "export:", 7)) { export_callback_data_t *de = (export_callback_data_t*) malloc(sizeof(export_callback_data_t)); if(de != NULL) { de->addr = GetAppExportFuncAddr(event); de->widget = widget; if(de->addr > 0 && de->addr != 0xffffffff) { cb = GUI_CallbackCreate(export_callback_function, free, (void*)de); return cb; } free(de); } } else if(!strncmp(event, "console:", 8)) { cb = GUI_CallbackCreate(cmd_callback_function, NULL, (void*)event+8); } else if(app->lua != NULL) { lua_callback_data_t *d = (lua_callback_data_t*) malloc(sizeof(lua_callback_data_t)); if(d != NULL) { d->script = event; d->state = app->lua; cb = GUI_CallbackCreate(lua_callback_function, free, (void *) d); if(cb == NULL) { free(d); } } } return cb; } /* #include "nano-X.h" #include "nanowm.h" static void NanoXDefaultEventHandler(void *data) { GR_EVENT gevent; GrGetNextEvent(&gevent); //printf("NanoXDefaultEventHandler: %d\n", gevent.type); GUI_WidgetMarkChanged((GUI_Widget *)data); switch (gevent.type) { case GR_EVENT_TYPE_EXPOSURE: GUI_WidgetMarkChanged((GUI_Widget *)data); break; case GR_EVENT_TYPE_UPDATE: GUI_WidgetMarkChanged((GUI_Widget *)data); break; case GR_EVENT_TYPE_MOUSE_MOTION: GUI_WidgetMarkChanged((GUI_Widget *)data); break; case GR_EVENT_TYPE_CLOSE_REQ: //GrClose(); break; } } static GUI_Widget *parseAppNanoXElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h) { GUI_Widget *widget; GUI_Callback *cb; char *event = NULL; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing NanoX: %s\n", name); #endif widget = GUI_NANOX_Create(name, x, y, w, h); event = FindXmlAttr("event", node, NULL); if(event != NULL) { cb = CreateAppElementCallback(app, event, widget); } else { ds_printf("NanoXDefaultEventHandler: OK\n"); cb = GUI_CallbackCreate((GUI_CallbackFunction *)NanoXDefaultEventHandler, NULL, widget); } if(cb != NULL) { GUI_NANOX_SetGEventHandler(widget, cb); GUI_ObjectDecRef((GUI_Object *) cb); } return widget; } */ static GUI_Widget *parseAppButtonElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h) { GUI_Widget *button; GUI_Surface *sf; char *onclick, *oncontextclick, *onmouseover, *onmouseout; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing Button: %s\n", name); #endif button = GUI_ButtonCreate(name, x, y, w, h); if(button == NULL) return NULL; onclick = FindXmlAttr("onclick", node, NULL); oncontextclick = FindXmlAttr("oncontextclick", node, NULL); onmouseover = FindXmlAttr("onmouseover", node, NULL); onmouseout = FindXmlAttr("onmouseout", node, NULL); if((sf = getElementSurfaceTheme(app, node, "normal")) != NULL) { GUI_ButtonSetNormalImage(button, sf); } if((sf = getElementSurfaceTheme(app, node, "highlight")) != NULL) { GUI_ButtonSetHighlightImage(button, sf); } if((sf = getElementSurfaceTheme(app, node, "pressed")) != NULL) { GUI_ButtonSetPressedImage(button, sf); } if((sf = getElementSurfaceTheme(app, node, "disabled")) != NULL) { GUI_ButtonSetDisabledImage(button, sf); } GUI_Callback *cb; if(onclick != NULL) { cb = CreateAppElementCallback(app, onclick, button); if(cb != NULL) { GUI_ButtonSetClick(button, cb); GUI_ObjectDecRef((GUI_Object *) cb); } } if(oncontextclick != NULL) { cb = CreateAppElementCallback(app, oncontextclick, button); if(cb != NULL) { GUI_ButtonSetContextClick(button, cb); GUI_ObjectDecRef((GUI_Object *) cb); } } if(onmouseover != NULL) { cb = CreateAppElementCallback(app, onmouseover, button); if(cb != NULL) { GUI_ButtonSetMouseover(button, cb); GUI_ObjectDecRef((GUI_Object *) cb); } } if(onmouseout != NULL && app->lua != NULL) { cb = CreateAppElementCallback(app, onmouseout, button); if(cb != NULL) { GUI_ButtonSetMouseout(button, cb); GUI_ObjectDecRef((GUI_Object *) cb); } } if(node->child && node->child->next && node->child->next->value.element.name[0] != '!') { #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing Button Child = %s\n", node->child->next->value.element.name); #endif SDL_Rect parent_area = GUI_WidgetGetArea(button); GUI_Widget *el = parseAppElement(app, node->child->next, &parent_area); if(el != NULL) { const char *n = GUI_ObjectGetName((GUI_Object *) el); GUI_ButtonSetCaption(button, el); if(n == NULL) { GUI_ObjectDecRef((GUI_Object *) el); } else { listAddItem(app->elements, LIST_ITEM_GUI_WIDGET, n, (void *) el, 0); } } } return button; } static GUI_Widget *parseAppToggleButtonElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h) { GUI_Widget *button; GUI_Surface *sf; char *onclick, *oncontextclick, *checked, *onmouseover, *onmouseout; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing Toggle Button: %s\n", name); #endif button = GUI_ToggleButtonCreate(name, x, y, w, h); if(button == NULL) return NULL; onclick = FindXmlAttr("onclick", node, NULL); oncontextclick = FindXmlAttr("oncontextclick", node, NULL); onmouseover = FindXmlAttr("onmouseover", node, NULL); onmouseout = FindXmlAttr("onmouseout", node, NULL); checked = FindXmlAttr("checked", node, NULL); if((sf = getElementSurfaceTheme(app, node, "onnormal")) != NULL) { GUI_ToggleButtonSetOnNormalImage(button, sf); } if((sf = getElementSurfaceTheme(app, node, "onhighlight")) != NULL) { GUI_ToggleButtonSetOnHighlightImage(button, sf); } if((sf = getElementSurfaceTheme(app, node, "offnormal")) != NULL) { GUI_ToggleButtonSetOffNormalImage(button, sf); } if((sf = getElementSurfaceTheme(app, node, "offhighlight")) != NULL) { GUI_ToggleButtonSetOffHighlightImage(button, sf); } if(checked != NULL && strncmp(checked, "false", 5) && strncmp(checked, "no", 2)) { GUI_WidgetSetState(button, 1); } else { GUI_WidgetSetState(button, 0); } GUI_Callback *cb; if(onclick != NULL) { cb = CreateAppElementCallback(app, onclick, button); if(cb != NULL) { GUI_ToggleButtonSetClick(button, cb); GUI_ObjectDecRef((GUI_Object *) cb); } } if(oncontextclick != NULL) { cb = CreateAppElementCallback(app, oncontextclick, button); if(cb != NULL) { GUI_ToggleButtonSetContextClick(button, cb); GUI_ObjectDecRef((GUI_Object *) cb); } } if(onmouseover != NULL) { cb = CreateAppElementCallback(app, onmouseover, button); if(cb != NULL) { GUI_ToggleButtonSetMouseover(button, cb); GUI_ObjectDecRef((GUI_Object *) cb); } } if(onmouseout != NULL) { cb = CreateAppElementCallback(app, onmouseout, button); if(cb != NULL) { GUI_ToggleButtonSetMouseout(button, cb); GUI_ObjectDecRef((GUI_Object *) cb); } } if(node->child && node->child->next && node->child->next->value.element.name[0] != '!') { #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing Toggle Button Child: %s\n", node->child->next->value.element.name); #endif SDL_Rect parent_area = GUI_WidgetGetArea(button); GUI_Widget *el = parseAppElement(app, node->child->next, &parent_area); if(el != NULL) { const char *n = GUI_ObjectGetName((GUI_Object *) el); GUI_ToggleButtonSetCaption(button, el); if(n == NULL) { GUI_ObjectDecRef((GUI_Object *) el); } else { listAddItem(app->elements, LIST_ITEM_GUI_WIDGET, n, (void *) el, 0); } } } return button; } static GUI_Widget *parseAppTextEntryElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h) { GUI_Widget *text; GUI_Surface *sf; GUI_Font *font = NULL; char *onfocus, *onblur, *src; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing TextEntry: %s\n", name); #endif onfocus = FindXmlAttr("onfocus", node, NULL); onblur = FindXmlAttr("onblur", node, NULL); src = FindXmlAttr("font", node, NULL); if(src == NULL || (font = getElementFont(app, node, src)) == NULL) { ds_printf("DS_ERROR: Can't find font '%s'\n", src); return NULL; } text = GUI_TextEntryCreate(name, x, y, w, h, font, atoi(FindXmlAttr("size", node, "12"))); if(text == NULL) return NULL; char *color = FindXmlAttr("fontcolor", node, NULL); unsigned int r = 0, g = 0, b = 0; if(color != NULL) { sscanf(color, "#%02x%02x%02x", &r, &g, &b); } GUI_TextEntrySetTextColor(text, r, g, b); if(font) GUI_TextEntrySetFont(text, font); GUI_TextEntrySetText(text, FindXmlAttr("value", node, "")); if((sf = getElementSurfaceTheme(app, node, "normal")) != NULL) { GUI_TextEntrySetNormalImage(text, sf); } if((sf = getElementSurfaceTheme(app, node, "highlight")) != NULL) { GUI_TextEntrySetHighlightImage(text, sf); } if((sf = getElementSurfaceTheme(app, node, "focus")) != NULL) { GUI_TextEntrySetFocusImage(text, sf); } GUI_Callback *cb; if(onfocus != NULL) { cb = CreateAppElementCallback(app, onfocus, text); if(cb != NULL) { GUI_TextEntrySetFocusCallback(text, cb); GUI_ObjectDecRef((GUI_Object *) cb); } } if(onblur != NULL) { cb = CreateAppElementCallback(app, onblur, text); if(cb != NULL) { GUI_TextEntrySetUnfocusCallback(text, cb); GUI_ObjectDecRef((GUI_Object *) cb); } } return text; } static void scrollbar_move_callback(void *data) { scrollbar_callback_data_t *d = (scrollbar_callback_data_t *) data; GUI_PanelSetYOffset(d->panel, GUI_ScrollBarGetPosition(d->scroll)); } static GUI_Widget *parseAppScrollBarElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h) { GUI_Widget *scroll; GUI_Surface *sf; char *onmove; int /*step = 0, */pos = 0; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing ScrollBar: %s\n", name); #endif scroll = GUI_ScrollBarCreate(name, x, y, w, h); if(scroll == NULL) return NULL; onmove = FindXmlAttr("onmove", node, NULL); //step = atoi(FindXmlAttr("step", node, "10")); pos = atoi(FindXmlAttr("pos", node, "0")); if((sf = getElementSurfaceTheme(app, node, "knob")) != NULL) { GUI_ScrollBarSetKnobImage(scroll, sf); } if((sf = getElementSurfaceTheme(app, node, "background")) != NULL) { GUI_ScrollBarSetBackgroundImage(scroll, sf); } GUI_ScrollBarSetPosition(scroll, pos); //GUI_ScrollBarSetPageStep(scroll, step); if(onmove != NULL) { GUI_Callback *cb = CreateAppElementCallback(app, onmove, scroll); if(cb != NULL) { GUI_ScrollBarSetMovedCallback(scroll, cb); GUI_ObjectDecRef((GUI_Object *) cb); } } return scroll; } static GUI_Widget *parseAppProgressBarElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h) { GUI_Widget *progress; GUI_Surface *sf; double pos = 0.0; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing ProgressBar: %s\n", name); #endif progress = GUI_ProgressBarCreate(name, x, y, w, h); if(progress == NULL) return NULL; pos = atof(FindXmlAttr("pos", node, "0.0")); if((sf = getElementSurfaceTheme(app, node, "bimage")) != NULL) { GUI_ProgressBarSetImage1(progress, sf); } if((sf = getElementSurfaceTheme(app, node, "pimage")) != NULL) { GUI_ProgressBarSetImage2(progress, sf); } GUI_ProgressBarSetPosition(progress, pos); return progress; } static GUI_Widget *parseAppPanelElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h) { GUI_Widget *panel; GUI_Surface *s = NULL; Item_t *res; char *back = NULL, *sbar; int xo = 0, yo = 0; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing Panel: %s\n", name); #endif panel = GUI_PanelCreate(name, x, y, w, h); if(panel == NULL) return NULL; back = FindXmlAttr("background", node, NULL); sbar = FindXmlAttr("scrollbar", node, NULL); xo = atoi(FindXmlAttr("xoffset", node, "0")); yo = atoi(FindXmlAttr("yoffset", node, "0")); if(back != NULL) { if(*back == '#') { SDL_Color c; unsigned int r = 0, g = 0, b = 0; sscanf(back, "#%02x%02x%02x", &r, &g, &b); c.r = r; c.g = g; c.b = b; c.unused = 0; GUI_PanelSetBackgroundColor(app->body, c); } else if((s = getElementSurface(app, back)) != NULL) { GUI_PanelSetBackground(panel, s); } } back = FindXmlAttr("backgroundCenter", node, NULL); if(back != NULL) { s = getElementSurface(app, back); if(s != NULL) { GUI_PanelSetBackgroundCenter(panel, s); } } if(sbar != NULL && (res = listGetItemByName(app->elements, sbar)) != NULL && res->type == LIST_ITEM_GUI_WIDGET) { scrollbar_callback_data_t *d = (scrollbar_callback_data_t*) malloc(sizeof(scrollbar_callback_data_t)); d->scroll = (GUI_Widget *) res->data; d->panel = panel; GUI_Callback *cb = GUI_CallbackCreate(scrollbar_move_callback, free, (void *) d); if(cb != NULL) { GUI_ScrollBarSetMovedCallback(d->scroll, cb); GUI_ObjectDecRef((GUI_Object *) cb); } else { free(d); } } if(node->child && node->child->next) { mxml_node_t *n = node->child->next; GUI_Widget *el; SDL_Rect parent_area = GUI_WidgetGetArea(panel); while(n) { if(n->type == MXML_ELEMENT) { #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing Panel Child: %s\n", n->value.element.name); #endif if(n->value.element.name[0] != '!' && (el = parseAppElement(app, n, &parent_area)) != NULL) { const char *nm = GUI_ObjectGetName((GUI_Object *) el); GUI_ContainerAdd(panel, el); if(nm == NULL) { GUI_ObjectDecRef((GUI_Object *) el); } else { listAddItem(app->elements, LIST_ITEM_GUI_WIDGET, nm, (void *) el, 0); } } } n = n->next; } } GUI_PanelSetXOffset(panel, xo); GUI_PanelSetYOffset(panel, yo); return panel; } static GUI_ListBox *parseAppListBoxElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h) { GUI_ListBox *listbox; GUI_Font *fnt = NULL; char *font, *color; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing ListBox: %s\n", name); #endif font = FindXmlAttr("font", node, NULL); color = FindXmlAttr("fontcolor", node, NULL); if(font != NULL) { if((fnt = getElementFont(app, node, font)) == NULL) { ds_printf("DS_ERROR: Can't find font '%s'\n", font); return NULL; } } else { ds_printf("DS_ERROR: ListBox attr 'font' is undefined\n"); return NULL; } listbox = GUI_CreateListBox(name, x, y, w, h, fnt); if(listbox == NULL) return NULL; if(color != NULL) { unsigned int r = 0, g = 0, b = 0; sscanf(color, "#%02x%02x%02x", &r, &g, &b); GUI_ListBoxSetTextColor(listbox, r, g, b); } if(node->child && node->child->next) { mxml_node_t *n = node->child->next; while(n) { if(n->type == MXML_ELEMENT) { if(!strcmp(n->value.element.name, "item")) { GUI_ListBoxAddItem(listbox, FindXmlAttr("value", node, NULL)); } } n = n->next; } } #ifdef APP_LOAD_DEBUG //ds_printf("ListBox: %s\n", name); #endif return listbox; } static GUI_Widget *parseAppCardStackElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h) { GUI_Widget *cards; GUI_Surface *s = NULL; char *back = NULL; SDL_Color c; unsigned int r = 0, g = 0, b = 0; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing CardStack: %s\n", name); #endif cards = GUI_CardStackCreate(name, x, y, w, h); if(cards == NULL) return NULL; back = FindXmlAttr("background", node, NULL); if(back != NULL) { if(back[0] == '#') { sscanf(back, "#%02x%02x%02x", &r, &g, &b); c.r = r; c.g = g; c.b = b; GUI_CardStackSetBackgroundColor(cards, c); } else if((s = getElementSurface(app, back)) != NULL) { GUI_CardStackSetBackground(cards, s); } } if(node->child && node->child->next) { mxml_node_t *n = node->child->next; GUI_Widget *el; SDL_Rect parent_area = GUI_WidgetGetArea(cards); while(n) { if(n->type == MXML_ELEMENT) { #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing CardStack Child: %s\n", n->value.element.name); #endif if(n->value.element.name[0] != '!' && (el = parseAppElement(app, n, &parent_area)) != NULL) { const char *nm = GUI_ObjectGetName((GUI_Object *) el); GUI_ContainerAdd(cards, el); if(nm == NULL) { GUI_ObjectDecRef((GUI_Object *) el); } else { listAddItem(app->elements, LIST_ITEM_GUI_WIDGET, nm, (void *) el, 0); } } } n = n->next; } } return cards; } #define LIST_ITEM_FM_DATA_OFFSET 1000 static void filemanager_call_lua_func(dirent_fm_t *ent, int index) { Item_t *item; App_t *app = GetCurApp(); if(app) { lua_State *L = app->lua; const char *name = GUI_ObjectGetName(ent->obj); item = listGetItemByNameAndType(app->resources, name, app->id + LIST_ITEM_FM_DATA_OFFSET + index); if(item == NULL) { ds_printf("item not fount\n"); return; } lua_getfield(L, LUA_GLOBALSINDEX, (const char *)item->data); if(lua_type(L, -1) != LUA_TFUNCTION) { ds_printf("DS_ERROR: Can't find function: \"%s\" FileManager events support only global functions.\n", (const char *)item->data); return; } lua_newtable(L); lua_pushstring(L, "name"); lua_pushstring(L, ent->ent.name); lua_settable(L, -3); lua_pushstring(L, "size"); lua_pushnumber(L, ent->ent.size); lua_settable(L, -3); lua_pushstring(L, "time"); lua_pushnumber(L, ent->ent.time); lua_settable(L, -3); lua_pushstring(L, "attr"); lua_pushnumber(L, ent->ent.attr); lua_settable(L, -3); lua_pushstring(L, "index"); lua_pushnumber(L, ent->index); lua_settable(L, -3); lua_pushstring(L, "fmwname"); lua_pushstring(L, name); lua_settable(L, -3); lua_report(L, lua_docall(L, 1, 1)); } } static void filemanager_lua_func_click(dirent_fm_t *ent) { filemanager_call_lua_func(ent, 0); } static void filemanager_lua_func_context_click(dirent_fm_t *ent) { filemanager_call_lua_func(ent, 1); } static void filemanager_lua_func_over(dirent_fm_t *ent) { filemanager_call_lua_func(ent, 2); } static void filemanager_lua_func_out(dirent_fm_t *ent) { filemanager_call_lua_func(ent, 3); } static GUI_CallbackFunction *FileManagerCallbackFunc(App_t *app, const char *event, char *wname, int idx) { if(!strncmp(event, "export:", 7)) { uint32 fa = GetAppExportFuncAddr(event); if(fa > 0 && fa != 0xffffffff) { return (GUI_CallbackFunction *)(void (*)(void*))fa; } } else if(!strncmp(event, "console:", 8)) { return NULL; } else if(app->lua != NULL) { Item_t *l = listAddItem(app->resources, app->id + LIST_ITEM_FM_DATA_OFFSET + idx, wname, (void *)event, 0); if(l) { switch(idx) { case 0: return (GUI_CallbackFunction *)filemanager_lua_func_click; case 1: return (GUI_CallbackFunction *)filemanager_lua_func_context_click; case 2: return (GUI_CallbackFunction *)filemanager_lua_func_over; case 3: return (GUI_CallbackFunction *)filemanager_lua_func_out; default: return NULL; } } } return NULL; } static GUI_Widget *parseAppFileManagerElement(App_t *app, mxml_node_t *node, char *name, int x, int y, int w, int h) { GUI_Widget *fm; GUI_Surface *sn, *sh, *sp, *sd = NULL; GUI_Font *fnt; int r, g, b; char *event; #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing FileManager: %s\n", name); #endif char path[NAME_MAX]; relativeFilePath_wb(path, app->fn, FindXmlAttr("path", node, "/")); fm = GUI_FileManagerCreate(name, path, x, y, w, h); if(fm == NULL) return NULL; sn = getElementSurfaceTheme(app, node, "background"); if(sn != NULL) { GUI_PanelSetBackground(fm, sn); } sn = getElementSurfaceTheme(app, node, "item_normal"); if(sn != NULL) { sh = getElementSurfaceTheme(app, node, "item_highlight"); sp = getElementSurfaceTheme(app, node, "item_pressed"); sd = getElementSurfaceTheme(app, node, "item_disabled"); GUI_FileManagerSetItemSurfaces(fm, sn, sh, sp, sd); } fnt = getElementFont(app, node, FindXmlAttr("item_font", node, NULL)); if(fnt != NULL) { char *color = FindXmlAttr("item_font_color", node, NULL); if(color != NULL) { sscanf(color, "#%02x%02x%02x", &r, &g, &b); } else { r = atoi(FindXmlAttr("item_font_r", node, "0")); g = atoi(FindXmlAttr("item_font_g", node, "0")); b = atoi(FindXmlAttr("item_font_b", node, "0")); } GUI_FileManagerSetItemLabel(fm, fnt, r, g, b); } sn = getElementSurfaceTheme(app, node, "sb_knob"); if(sn) { sh = getElementSurfaceTheme(app, node, "sb_back"); GUI_FileManagerSetScrollbar(fm, sn, sh); } sn = getElementSurfaceTheme(app, node, "sbbup_normal"); if(sn != NULL) { sh = getElementSurfaceTheme(app, node, "sbbup_highlight"); sp = getElementSurfaceTheme(app, node, "sbbup_pressed"); sd = getElementSurfaceTheme(app, node, "sbbup_disabled"); GUI_FileManagerSetScrollbarButtonUp(fm, sn, sh, sp, sd); } sn = getElementSurfaceTheme(app, node, "sbbdown_normal"); if(sn != NULL) { sh = getElementSurfaceTheme(app, node, "sbbdown_highlight"); sp = getElementSurfaceTheme(app, node, "sbbdown_pressed"); sd = getElementSurfaceTheme(app, node, "sbbdown_disabled"); GUI_FileManagerSetScrollbarButtonDown(fm, sn, sh, sp, sd); } event = FindXmlAttr("onclick", node, NULL); if(event != NULL) { GUI_FileManagerSetItemClick(fm, FileManagerCallbackFunc(app, event, name, 0)); } event = FindXmlAttr("oncontextclick", node, NULL); if(event != NULL) { GUI_FileManagerSetItemContextClick(fm, FileManagerCallbackFunc(app, event, name, 1)); } event = FindXmlAttr("onmouseover", node, NULL); if(event != NULL) { GUI_FileManagerSetItemMouseover(fm, FileManagerCallbackFunc(app, event, name, 2)); } event = FindXmlAttr("onmouseout", node, NULL); if(event != NULL) { GUI_FileManagerSetItemMouseout(fm, FileManagerCallbackFunc(app, event, name, 3)); } if(node->child && node->child->next) { mxml_node_t *n = node->child->next; char *iname = NULL; int size = 0, time = 0, attr = 0; while(n) { if(n->type == MXML_ELEMENT) { #ifdef APP_LOAD_DEBUG ds_printf("DS_DEBUG: Parsing Panel Child: %s\n", n->value.element.name); #endif iname = FindXmlAttr("name", n, "item"); size = atoi(FindXmlAttr("size", n, "-3")); time = atoi(FindXmlAttr("time", n, "0")); attr = atoi(FindXmlAttr("attr", n, "0")); GUI_FileManagerAddItem(fm, iname, size, time, attr); } n = n->next; } } return fm; } <file_sep>/modules/aicaos/arm/aica_arm.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../aica_registers.h" #include "../aica_common.h" #include "interrupt.h" #include "spinlock.h" #include "task.h" extern struct io_channel *__io_init; static struct io_channel *io_addr; static spinlock_t call_lock = SPINLOCK_INITIALIZER, fparams_lock = SPINLOCK_INITIALIZER; static AICA_SHARED(get_arm_func_id) { return aica_find_id((unsigned int *)out, (char *)in); } static void __main(void) { extern int main(int, char**) __attribute__((weak)); if (main) { int err = main(0, 0); printf("ARM main terminated with status %i\n", err); } while (1) task_reschedule(); } /* Called from crt0.S */ void __aica_init(void) { struct task *main_task; io_addr = (struct io_channel *) calloc(2, sizeof(*io_addr)); aica_clear_handler_table(); /* That function will be used by the remote processor to get IDs * from the names of the functions to call. */ AICA_SHARE(get_arm_func_id, FUNCNAME_MAX_LENGTH, 4); /* If the AICA_SHARED_LIST is used, we share all * the functions it contains. */ if (__aica_shared_list) { struct __aica_shared_function *ptr; for (ptr = __aica_shared_list; ptr->func; ptr++) __aica_share(ptr->func, ptr->name, ptr->sz_in, ptr->sz_out); } aica_interrupt_init(); __io_init = io_addr; /* We will continue when the SH-4 will decide so. */ while (*(volatile int *) &__io_init != 0); /* Create the main thread, that should start right after aica_init(). */ main_task = task_create(__main, NULL); if (!main_task) printf("Unable to create main task.\n"); task_add_to_runnable(main_task, PRIORITY_MAX); task_select(main_task); } void aica_exit(void) { aica_clear_handler_table(); free(io_addr); } int __aica_call(unsigned int id, void *in, void *out, unsigned short prio) { int return_value; struct function_params *fparams = &io_addr[ARM_TO_SH].fparams[id]; struct call_params *cparams = &io_addr[ARM_TO_SH].cparams; if (id >= NB_MAX_FUNCTIONS) return -EINVAL; /* Wait here if a previous call is pending. */ for (;;) { spinlock_lock(&fparams_lock); if (*(unsigned int *) &fparams->call_status == FUNCTION_CALL_AVAIL) break; spinlock_unlock(&fparams_lock); task_reschedule(); } fparams->call_status = FUNCTION_CALL_PENDING; spinlock_unlock(&fparams_lock); spinlock_lock(&call_lock); cparams->id = id; cparams->prio = prio; cparams->in = in; cparams->out = out; cparams->sync = 1; aica_interrupt(); /* Wait for the sync flag to be cleared by the SH4, * before unlocking the call mutex */ while (*(unsigned char *) &cparams->sync) task_reschedule(); spinlock_unlock(&call_lock); /* We will wait until the call completes. */ while (*(unsigned int *) &fparams->call_status != FUNCTION_CALL_DONE) task_reschedule(); return_value = fparams->return_value; /* Set the 'errno' variable to the value returned by the ARM */ errno = io_addr[ARM_TO_SH].fparams[id].err_no; /* Mark the function as available */ fparams->call_status = FUNCTION_CALL_AVAIL; return return_value; } void aica_interrupt_init(void) { /* Set the FIQ code */ *(unsigned int *) REG_ARM_FIQ_BIT_2 = (SH4_INTERRUPT_INT_CODE & 4) ? MAGIC_CODE : 0; *(unsigned int *) REG_ARM_FIQ_BIT_1 = (SH4_INTERRUPT_INT_CODE & 2) ? MAGIC_CODE : 0; *(unsigned int *) REG_ARM_FIQ_BIT_0 = (SH4_INTERRUPT_INT_CODE & 1) ? MAGIC_CODE : 0; /* Allow the SH4 to raise interrupts on the ARM */ *(unsigned int *) REG_ARM_INT_ENABLE = MAGIC_CODE; /* Allow the ARM to raise interrupts on the SH4 */ *(unsigned int *) REG_SH4_INT_ENABLE = MAGIC_CODE; } void aica_interrupt(void) { *(unsigned int *) REG_SH4_INT_SEND = MAGIC_CODE; } void aica_update_fparams_table(unsigned int id, struct function_params *fparams) { memcpy(&io_addr[SH_TO_ARM].fparams[id], fparams, sizeof(*fparams)); } static void task_birth(aica_funcp_t func, struct function_params *fparams) { fparams->return_value = func(fparams->out.ptr, fparams->in.ptr); /* Return the 'errno' variable to the SH4 */ fparams->err_no = errno; fparams->call_status = FUNCTION_CALL_DONE; } /* Called from crt0.S */ void aica_sh4_fiq_hdl(void) { struct call_params cparams; struct function_params *fparams; struct task *task; aica_funcp_t func; /* Switch back to newlib's reent structure */ _impure_ptr = _global_impure_ptr; /* Retrieve the call parameters */ memcpy(&cparams, &io_addr[SH_TO_ARM].cparams, sizeof(cparams)); /* The call data has been read, clear the sync flag and acknowledge */ io_addr[SH_TO_ARM].cparams.sync = 0; fparams = &io_addr[SH_TO_ARM].fparams[cparams.id]; func = aica_get_func_from_id(cparams.id); if (!func) { /* If the function is not found, we return the code * -EAGAIN, acknowledge the interrupt and reschedule. */ fparams->return_value = -EAGAIN; fparams->call_status = FUNCTION_CALL_DONE; task = current_task; } else { void *params[4] = { func, fparams, 0, 0, }; task = task_create(task_birth, params); task_add_to_runnable(task, cparams.prio); } /* Reset the interrupt raised by the SH-4 */ int_acknowledge(); task_select(task); } <file_sep>/firmware/aica/codec/player.c /* Copyright (C) 2006 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* This is the controller of the player. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <malloc.h> #include "player.h" #include "ff.h" #include "fileinfo.h" #include "dac.h" #include "play_wav.h" #include "play_mp3.h" #include "play_aac.h" #include "keys.h" #include "ir.h" static void next(); static void stop(); static void start(); static void do_playing(); static void do_stopped(); static void do_paused(); static unsigned char buf[2048]; //static SONGINFO songinfo; extern FATFS fs; enum playing_states {PLAYING, STOPPED, PAUSED}; enum user_commands {CMD_START, CMD_STOP, CMD_NEXT}; static enum playing_states state = STOPPED; static FIL file; static SONGLIST songlist; static SONGINFO songinfo; static int current_song_index = -1; enum user_commands get_command(void) { long key0 = get_key_press( 1<<KEY0 ); long key1 = get_key_rpt( 1<<KEY1 ) || get_key_press( 1<<KEY1 ); int ir_cmd = ir_get_cmd(); if ((key0 && state == PLAYING) || ir_cmd == 0x36) { return CMD_STOP; } else if (key0 || ir_cmd == 0x35) { return CMD_START; } else if (key1 || ir_cmd == 0x34) { return CMD_NEXT; } return -1; } // State transition actions static void next() { current_song_index++; if (current_song_index >= songlist.size) { current_song_index = 0; } iprintf("selected file: %.12s\n", songlist.list[current_song_index].filename); } static void stop() { f_close( &file ); puts("File closed."); // wait until both buffers are empty while(dac_busy_buffers() > 0); dac_reset(); mp3_free(); aac_free(); state = STOPPED; } static void start() { memset(&songinfo, 0, sizeof(SONGINFO)); read_song_info_for_song(&(songlist.list[current_song_index]), &songinfo); assert(f_open( &file, get_full_filename(songlist.list[current_song_index].filename), FA_OPEN_EXISTING|FA_READ) == FR_OK); iprintf("title: %s\n", songinfo.title); iprintf("artist: %s\n", songinfo.artist); iprintf("album: %s\n", songinfo.album); iprintf("skipping: %i\n", songinfo.data_start); f_lseek(&file, songinfo.data_start); if (songinfo.type != UNKNOWN) { //assert(f_open( &file, get_full_filename(fileinfo.fname), FA_OPEN_EXISTING|FA_READ) == FR_OK); //puts("File opened."); switch(songinfo.type) { case AAC: aac_alloc(); aac_reset(); break; case MP4: aac_alloc(); aac_reset(); aac_setup_raw(); break; case MP3: mp3_alloc(); mp3_reset(); break; } puts("playing"); malloc_stats(); state = PLAYING; } else { puts("unknown file type"); stop(); } } static void pause() { // wait until both buffers are empty while(dac_busy_buffers() > 0); dac_disable_dma(); state = PAUSED; } static void cont() { dac_enable_dma(); state = PLAYING; } // State loop actions static void do_playing() { enum user_commands cmd = get_command(); switch(songinfo.type) { case MP3: if(mp3_process(&file) != 0) { stop(); next(); start(); } break; case MP4: if (aac_process(&file, 1) != 0) { stop(); next(); start(); } break; case AAC: if (aac_process(&file, 0) != 0) { stop(); next(); start(); } break; case WAV: if (wav_process(&file) != 0) { stop(); next(); start(); } break; default: stop(); break; } switch(cmd) { case CMD_STOP: pause(); iprintf("underruns: %u\n", underruns); break; case CMD_NEXT: iprintf("underruns: %u\n", underruns); stop(); next(); start(); break; } } static void do_stopped() { enum user_commands cmd = get_command(); switch(cmd) { case CMD_START: start(); break; case CMD_NEXT: next(); break; } } void do_paused() { enum user_commands cmd = get_command(); switch(cmd) { case CMD_START: cont(); break; case CMD_NEXT: stop(); next(); break; } } void player_init(void) { dac_init(); wav_init(buf, sizeof(buf)); mp3_init(buf, sizeof(buf)); aac_init(buf, sizeof(buf)); songlist_build(&songlist); songlist_sort(&songlist); for (int i = 0; i < songlist.size; i++) { read_song_info_for_song(&(songlist.list[i]), &songinfo); iprintf("%s\n", songinfo.artist); } } void play(void) { //dac_enable_dma(); //iprintf("f_open: %i\n", f_open(&file, "/04TUYY~1.MP3", FA_OPEN_EXISTING|FA_READ)); //infile_type = MP3; next(); state = STOPPED; //mp3_alloc(); // clear command buffer get_command(); while(1) { switch(state) { case STOPPED: do_stopped(); break; case PLAYING: do_playing(); break; case PAUSED: do_paused(); break; } } } <file_sep>/modules/mp3/libmp3/xingmp3/protos.h /*====================================================================*/ int hybrid(MPEG *m, void *xin, void *xprev, float *y, int btype, int nlong, int ntot, int nprev); int hybrid_sum(MPEG *m, void *xin, void *xin_left, float *y, int btype, int nlong, int ntot); void sum_f_bands(void *a, void *b, int n); void FreqInvert(float *y, int n); void antialias(MPEG *m, void *x, int n); void ms_process(void *x, int n); /* sum-difference stereo */ void is_process_MPEG1(MPEG *m, void *x, /* intensity stereo */ SCALEFACT * sf, CB_INFO cb_info[2], /* [ch] */ int nsamp, int ms_mode); void is_process_MPEG2(MPEG *m, void *x, /* intensity stereo */ SCALEFACT * sf, CB_INFO cb_info[2], /* [ch] */ IS_SF_INFO * is_sf_info, int nsamp, int ms_mode); void unpack_huff(MPEG *m, void *xy, int n, int ntable); int unpack_huff_quad(MPEG *m, void *vwxy, int n, int nbits, int ntable); void dequant(MPEG *m, SAMPLE sample[], int *nsamp, SCALEFACT * sf, GR * gr, CB_INFO * cb_info, int ncbl_mixed); void unpack_sf_sub_MPEG1(MPEG *m, SCALEFACT * scalefac, GR * gr, int scfsi, /* bit flag */ int igr); void unpack_sf_sub_MPEG2(MPEG *m, SCALEFACT sf[], /* return intensity scale */ GR * grdat, int is_and_ch, IS_SF_INFO * is_sf_info); /*---------- quant ---------------------------------*/ /* 8 bit lookup x = pow(2.0, 0.25*(global_gain-210)) */ float *quant_init_global_addr(MPEG *m); /* x = pow(2.0, -0.5*(1+scalefact_scale)*scalefac + preemp) */ typedef float LS[4][32]; LS *quant_init_scale_addr(MPEG *m); float *quant_init_pow_addr(MPEG *m); float *quant_init_subblock_addr(MPEG *m); typedef int iARRAY22[22]; iARRAY22 *quant_init_band_addr(MPEG *m); /*---------- antialias ---------------------------------*/ typedef float PAIR[2]; PAIR *alias_init_addr(MPEG *m); <file_sep>/modules/sqlite3/Makefile # # sqlite3 module for DreamShell # Copyright (C) 2011-2022 SWAT # http://www.dc-swat.ru # TARGET_NAME = sqlite3 OBJS = sqlite3.o module.o DBG_LIBS = -lds EXPORTS_FILE = exports.txt VER_MAJOR = 3 VER_MINOR = 8 VER_MICRO = 1 VER_BUILD = 0 KOS_LIB_PATHS += -L../../lib KOS_CFLAGS += -DSTDC_HEADERS=1 \ -DHAVE_SYS_TYPES_H=1 \ -DHAVE_SYS_STAT_H=1 \ -DHAVE_STDLIB_H=1 \ -DHAVE_STRING_H=1 \ -DHAVE_INTTYPES_H=1 \ -DHAVE_STDINT_H=1 \ -DHAVE_UNISTD_H=1 \ -DHAVE_USLEEP=1 \ -DHAVE_LOCALTIME_R=1 \ -DHAVE_GMTIME_R=1 \ -DSQLITE_OMIT_WAL=1 \ -DSQLITE_NO_SYNC=1 \ -DSQLITE_DISABLE_DIRSYNC=1 \ -DSQLITE_DISABLE_LFS=1 \ -DSQLITE_OMIT_LOAD_EXTENSION=1 \ -DSQLITE_THREADSAFE=0 all: rm-elf install include ../../sdk/Makefile.loadable rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/applications/main/modules/module.c /* DreamShell ##version## module.c - Main app module Copyright (C)2011-2016 SWAT */ #include <ds.h> #include <drivers/rtc.h> DEFAULT_MODULE_EXPORTS(app_main); #define ICON_CELL_PADDING 10 static struct { App_t *app; GUI_Font *font; GUI_Widget *panel; SDL_Rect panel_area; int x; int y; int cur_x; int col_width; struct tm datetime; GUI_Widget *dateWidget; GUI_Widget *timeWidget; } self; typedef struct script_item { char name[64]; char file[NAME_MAX]; } script_item_t; static GUI_Surface *CreateHighlight(GUI_Surface *src, int w, int h) { SDL_Surface *screen = GetScreen(); GUI_Surface *s = GUI_SurfaceCreate("icon", screen->flags, w + 4, h + 4, screen->format->BitsPerPixel, screen->format->Rmask, screen->format->Gmask, screen->format->Bmask, screen->format->Amask); GUI_SurfaceSetAlpha(s, SDL_SRCALPHA, 100); GUI_SurfaceFill(s, NULL, GUI_SurfaceMapRGB(s, 0, 0, 0)); //GUI_SurfaceBoxRouded(s, 0, 0, w, h, 10, 0xEEEEEE44); SDL_Rect dst; dst.x = dst.y = 2; dst.w = w; dst.h = h; GUI_SurfaceBlit(src, NULL, s, &dst); return s; } static void OpenAppCB(void *param) { App_t *app = GetAppById((int)param); if(app != NULL) { OpenApp(app, NULL); } } static void RunScriptCB(void *param) { script_item_t *si = (script_item_t *)param; int c = si->file[strlen(si->file) - 3]; switch(c) { case 'l': LuaDo(LUA_DO_FILE, si->file, GetLuaState()); break; case 'd': default: dsystem_script(si->file); break; } } static void AddToList(const char *name, const char *icon, GUI_CallbackFunction *callback, GUI_CallbackFunction *free_data, void *callback_data) { SDL_Rect ts; if(name) { ts = GUI_FontGetTextSize(self.font, name); ts.w += 4; } else { ts.w = 0; } GUI_Surface *s = GUI_SurfaceLoad(icon); int w = ts.w + GUI_SurfaceGetWidth(s); int h = GUI_SurfaceGetHeight(s); int dpad = ICON_CELL_PADDING * 2; if((self.y + h + dpad) > self.panel_area.h) { self.x += self.col_width + ICON_CELL_PADDING; self.y = dpad; self.col_width = 0; if((self.x % self.panel_area.w) + w + ICON_CELL_PADDING > self.panel_area.w) { self.x += (self.panel_area.w - (self.x % self.panel_area.w)) + dpad; } } GUI_Widget *b = GUI_ButtonCreate(name ? name : "icon", self.x, self.y, w + 4, h + 4); if(s != NULL) { GUI_Surface *sh = CreateHighlight(s, w, h); GUI_ButtonSetNormalImage(b, s); GUI_ButtonSetHighlightImage(b, sh); GUI_ButtonSetPressedImage(b, s); GUI_ButtonSetDisabledImage(b, s); GUI_ObjectDecRef((GUI_Object *) s); GUI_ObjectDecRef((GUI_Object *) sh); } GUI_Callback *c = GUI_CallbackCreate(callback, free_data, callback_data); GUI_ButtonSetClick(b, c); GUI_ObjectDecRef((GUI_Object *) c); if(name) { GUI_Widget *l = GUI_LabelCreate(name, 0, 0, w, h, self.font, name); GUI_LabelSetTextColor(l, 0, 0, 0); GUI_WidgetSetAlign(l, WIDGET_HORIZ_RIGHT | WIDGET_VERT_CENTER); GUI_ButtonSetCaption(b, l); GUI_ObjectDecRef((GUI_Object *) l); } GUI_ContainerAdd(self.panel, b); GUI_ObjectDecRef((GUI_Object *) b); self.y += (h + ICON_CELL_PADDING); if(self.col_width < w) { self.col_width = w; } } static void BuildAppList() { file_t fd; dirent_t *ent; char path[NAME_MAX]; int plen, elen, type; App_t *app; Item_list_t *applist = GetAppList(); const char *app_name = lib_get_name() + 4; if(applist != NULL) { Item_t *item = listGetItemFirst(applist); while(item != NULL) { app = (App_t*)item->data; if(strncasecmp(app->name, app_name, sizeof(app->name))) { AddToList(app->name, app->icon, (GUI_CallbackFunction *)OpenAppCB, NULL, (void*)app->id); } item = listGetItemNext(item); } } snprintf(path, NAME_MAX, "%s/apps/%s/scripts", getenv("PATH"), app_name); fd = fs_open(path, O_RDONLY | O_DIR); if(fd == FILEHND_INVALID) return; while((ent = fs_readdir(fd)) != NULL) { if(ent->name[0] == '.') continue; elen = strlen(ent->name); type = elen > 3 ? ent->name[elen - 3] : 'd'; if(!ent->attr && (type == 'l' || type == 'd')) { script_item_t *si = (script_item_t *) calloc(1, (sizeof(script_item_t))); if(si == NULL) break; snprintf(si->file, NAME_MAX, "%s/apps/%s/scripts/%s", getenv("PATH"), app_name, ent->name); snprintf(path, NAME_MAX, "%s/apps/%s/images/%s", getenv("PATH"), app_name, ent->name); plen = strlen(path); path[plen - 3] = 'p'; path[plen - 2] = 'n'; path[plen - 1] = 'g'; if(!FileExists(path)) { path[plen - 3] = 'p'; path[plen - 2] = 'v'; path[plen - 1] = 'r'; if(!FileExists(path)) { path[plen - 3] = 'b'; path[plen - 2] = 'm'; path[plen - 1] = 'p'; if(!FileExists(path)) { snprintf(path, NAME_MAX, "%s/gui/icons/normal/%s.png", getenv("PATH"), (type == 'l' ? "lua" : "script")); } } } elen -= 4; if(elen > sizeof(si->name)) elen = sizeof(si->name); strncpy(si->name, ent->name, elen); si->name[elen] = '\0'; AddToList((si->name[0] != '_' ? si->name : NULL), path, RunScriptCB, free, (void *)si); } } fs_close(fd); } static void ShowVersion(GUI_Widget *widget) { if(!widget) { return; } char vers[32]; snprintf(vers, sizeof(vers), "%s %s", getenv("OS"), getenv("VERSION")); GUI_LabelSetText(widget, vers); } static void ShowDateTime(int force) { char str[32]; struct timeval tv; struct tm *datetime; rtc_gettimeofday(&tv); datetime = localtime(&tv.tv_sec); if(force || datetime->tm_mday != self.datetime.tm_mday) { switch(flashrom_get_region_only()) { case FLASHROM_REGION_JAPAN: snprintf(str, sizeof(str), "%04d-%02d-%02d", datetime->tm_year + 1900, datetime->tm_mon + 1, datetime->tm_mday); break; case FLASHROM_REGION_US: snprintf(str, sizeof(str), "%02d/%02d/%04d", datetime->tm_mon + 1, datetime->tm_mday, datetime->tm_year + 1900); break; case FLASHROM_REGION_EUROPE: default: snprintf(str, sizeof(str), "%02d.%02d.%04d", datetime->tm_mday, datetime->tm_mon + 1, datetime->tm_year + 1900); break; } GUI_LabelSetText(self.dateWidget, str); } if(force || datetime->tm_min != self.datetime.tm_min) { snprintf(str, sizeof(str), "%02d:%02d", datetime->tm_hour, datetime->tm_min); GUI_LabelSetText(self.timeWidget, str); } memcpy(&self.datetime, datetime, sizeof(*datetime)); } static void *ClockThread() { while(self.app->state & APP_STATE_OPENED) { ShowDateTime(0); thd_sleep(250); } return NULL; } /** * Global functions */ void MainApp_SlideLeft() { if(self.cur_x > 0) { self.cur_x -= self.panel_area.w; GUI_PanelSetXOffset(self.panel, self.cur_x); } } void MainApp_SlideRight() { if(self.x > self.cur_x) { self.cur_x += self.panel_area.w; GUI_PanelSetXOffset(self.panel, self.cur_x); } } void MainApp_Init(App_t *app) { if(app != NULL) { memset(&self, 0, sizeof(self)); self.x = self.y = (ICON_CELL_PADDING * 2); self.app = app; self.font = APP_GET_FONT("arial"); self.panel = APP_GET_WIDGET("app-list"); if(self.font && self.panel) { self.panel_area = GUI_WidgetGetArea(self.panel); BuildAppList(); } else { ds_printf("DS_ERROR: Couldt'n find font and app-list panel\n"); return; } ShowVersion(APP_GET_WIDGET("version")); self.dateWidget = APP_GET_WIDGET("date"); self.timeWidget = APP_GET_WIDGET("time"); if(self.dateWidget && self.timeWidget) { ShowDateTime(1); self.app->thd = thd_create(0, ClockThread, NULL); } } } <file_sep>/include/lua.h /** * \file lua.h * \brief DreamShell LUA * \date 2006-2014 * \author SWAT www.dc-swat.ru */ #ifndef _DS_LUA_H #define _DS_LUA_H #include "lua/lua.h" #include "lua/lauxlib.h" #include "lua/lualib.h" void luaB_set_fputs(void (*f)(const char *)); #define LUA_DO_FILE 0 #define LUA_DO_STRING 1 #define LUA_DO_LIBRARY 2 int lua_packlibopen(lua_State *L); int InitLua(); void ShutdownLua(); void ResetLua(); lua_State *GetLuaState(); void SetLuaState(lua_State *L); lua_State *NewLuaThread(); typedef void LuaRegLibOpen(lua_State *); int RegisterLuaLib(const char *name, LuaRegLibOpen *func); int UnregisterLuaLib(const char *name); void LuaOpenlibs(lua_State *L); void RegisterLuaFunctions(lua_State *L); void LuaPushArgs(lua_State *L, char *argv[]); void LuaAddArgs(lua_State *L, char *argv[]); int lua_traceback(lua_State *L); int lua_docall(lua_State *L, int narg, int clear); int lua_report(lua_State *L, int status); int LuaDo(int type, const char *str_or_file, lua_State *lu); int RunLuaScript(char *fn, char *argv[]); #endif <file_sep>/include/exceptions.h /** * \file exceptions.h * \brief Exception handling for DreamShell * \date 2007-2014 * \author SWAT www.dc-swat.ru */ #ifndef _DS_EXECEPTIONS_H_ #define _DS_EXECEPTIONS_H_ #include <kos/thread.h> #include "setjmp.h" #if !defined(DS_DEBUG) || DS_DEBUG < 2 # define USE_DS_EXCEPTIONS 1 #endif #define EXPT_GUARD_STACK_SIZE 16 #define EXPT_GUARD_ST_DYNAMIC -1 #define EXPT_GUARD_ST_STATIC_FREE 0 typedef struct expt_guard_stack { int pos; jmp_buf jump[EXPT_GUARD_STACK_SIZE]; /** * If equal to EXPT_GUARD_ST_DYNAMIC, then dynamic. * If equal to EXPT_GUARD_ST_STATIC_FREE, then static and not used * Otherwise index in static */ int type; } expt_quard_stack_t; /** * Initialize the exception system. */ int expt_init(); /** * Shutdown the exception system. */ void expt_shutdown(); /** * Get guard stack from current thread. */ expt_quard_stack_t *expt_get_stack(); /** * Print catched exception place */ void expt_print_place(char *file, int line, const char *func); /** \name Protected section. * * To protect a code from exception : * \code * char * buffer = malloc(32); * EXPT_GUARD_BEGIN; * // Run code to protect here. This instruction makes a bus error or * // something like that on most machine. * *(int *) (buffer+1) = 0xDEADBEEF; * * EXPT_GUARD_CATCH; * // Things to do if hell happen * printf("Error\n"); * free(buffer); * return -1; * * EXPT_GUARD_END; * // Life continue ... * memset(buffer,0,32); * // ... * \endcode * */ #ifdef USE_DS_EXCEPTIONS /** * Throw exception. */ #define EXPT_GUARD_THROW *(int *)(0xdeadbeef) = 0xdeadbeef /** * Get exceptions stack from current thread. */ #define EXPT_GUARD_INIT expt_quard_stack_t *__expt = expt_get_stack() /** * Start a protected section. * \warning : it is FORBIDEN to do "return" inside a guarded section, * use EXPT_GUARD_RETURN instead. */ #define EXPT_GUARD_BEGIN_NEXT \ do { \ __expt->pos++; \ if (__expt->pos >= EXPT_GUARD_STACK_SIZE) \ EXPT_GUARD_THROW; \ if (!setjmp(__expt->jump[__expt->pos])) { \ /** * Get stack and start a protected section. */ #define EXPT_GUARD_BEGIN \ EXPT_GUARD_INIT; \ EXPT_GUARD_BEGIN_NEXT /** * Catch a protected section. */ #define EXPT_GUARD_CATCH \ } else { \ expt_print_place(__FILE__, __LINE__, __FUNCTION__) /** * End of protected section. */ #define EXPT_GUARD_END \ } \ __expt->pos--; \ } while(0) /** * Return in middle of a guarded section. * \warning : to be used exclusively inbetween EXPT_GUARD_BEGIN and * EXPT_GUARD_END. Never use normal "return" in this case. */ #define EXPT_GUARD_RETURN __expt->pos--; return #define EXPT_GUARD_ASSIGN(dst, src, catched) \ EXPT_GUARD_BEGIN; \ dst = src; \ EXPT_GUARD_CATCH; \ catched; \ EXPT_GUARD_END #else /* ifdef USE_DS_EXCEPTIONS */ #define EXPT_GUARD_THROW #define EXPT_GUARD_BEGIN \ if (1) { \ #define EXPT_GUARD_CATCH \ } else { \ #define EXPT_GUARD_END } #define EXPT_GUARD_RETURN \ return #define EXPT_GUARD_ASSIGN(dst, src, errval) dst = src #endif /* ifdef USE_DS_EXCEPTIONS */ #endif /* ifndef _DS_EXECEPTIONS_H_*/ <file_sep>/modules/ini/module.c /* DreamShell ##version## module.c - ini module Copyright (C)2013 SWAT */ #include "ds.h" DEFAULT_MODULE_EXPORTS(ini); <file_sep>/lib/SDL_gui/FastFont.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_FastFont::GUI_FastFont(const char *fn) : GUI_Font(fn) { image = new GUI_Surface(fn); char_width = image->GetWidth() / 256; char_height = image->GetHeight(); } GUI_FastFont::~GUI_FastFont() { image->DecRef(); } void GUI_FastFont::DrawText(GUI_Surface *surface, const char *s, int x, int y) { SDL_Rect sr, dr; int n, i, max; assert(s != 0); if (x > surface->GetWidth() || y > surface->GetHeight()) return; n = strlen(s); max = (surface->GetWidth() - x) / char_width; if (n > max) n = max; dr.x = x; dr.y = y; dr.w = char_width; dr.h = char_height; sr = dr; sr.y = 0; for (i=0; i<n; i++) { sr.x = s[i] * char_width; image->Blit(&sr, surface, &dr); dr.x += char_width; } } GUI_Surface *GUI_FastFont::RenderFast(const char *s, SDL_Color fg) { assert(s != 0); GUI_Surface *surface = new GUI_Surface("text", SDL_HWSURFACE, strlen(s) * char_width, char_height, 16, 0, 0, 0, 0); DrawText(surface, s, 0, 0); return surface; } GUI_Surface *GUI_FastFont::RenderQuality(const char *s, SDL_Color fg) { return RenderFast(s, fg); } SDL_Rect GUI_FastFont::GetTextSize(const char *s) { assert(s != 0); SDL_Rect r = { 0, 0, 0, 0 }; r.w = strlen(s) * char_width; r.h = char_height; return r; } GUI_Surface *GUI_FastFont::GetFontImage(void) { return image; } extern "C" GUI_Font *GUI_FontLoadBitmap(char *fn) { return new GUI_FastFont(fn); } <file_sep>/lib/SDL_gui/Container.cc #include <assert.h> #include <stdlib.h> #include <string.h> #include "SDL_gui.h" #define WIDGET_LIST_SIZE 16 #define WIDGET_LIST_INCR 16 GUI_Container::GUI_Container(const char *aname, int x, int y, int w, int h) : GUI_Widget(aname, x, y, w, h) { SetFlags(WIDGET_TRANSPARENT); n_widgets = 0; s_widgets = WIDGET_LIST_SIZE; widgets = new GUI_Widget *[s_widgets]; x_offset = 0; y_offset = 0; background = 0; bgcolor.r = bgcolor.g = bgcolor.b = 0; wtype = WIDGET_TYPE_CONTAINER; } GUI_Container::~GUI_Container(void) { if (background) background->DecRef(); RemoveAllWidgets(); } int GUI_Container::ContainsWidget(GUI_Widget *widget) { if (!widget) return 0; int i; for (i=0; i<n_widgets; i++) if (widgets[i] == widget) return 1; return 0; } int GUI_Container::IsVisibleWidget(GUI_Widget *widget) { if (!widget) return 0; SDL_Rect r = widget->GetArea(); if(r.x < (area.w + x_offset) && r.y < (area.h + y_offset) && r.x + r.w > x_offset && r.y + r.h > y_offset) { return 1; } return 0; } void GUI_Container::AddWidget(GUI_Widget *widget) { if (!widget || ContainsWidget(widget)) return; // IncRef early, to prevent reparenting from freeing the child widget->IncRef(); // reparent if necessary GUI_Drawable *parent = widget->GetParent(); if (parent) parent->RemoveWidget(widget); widget->SetParent(this); // expand the array if necessary if (n_widgets >= s_widgets) { int i; GUI_Widget **new_widgets; s_widgets += WIDGET_LIST_INCR; new_widgets = new GUI_Widget *[s_widgets]; for (i=0; i<n_widgets; i++) new_widgets[i] = widgets[i]; delete [] widgets; widgets = new_widgets; } // TODO: make new method with auto positioning SDL_Rect warea = widget->GetArea(); if(wtype == WIDGET_TYPE_CONTAINER && !warea.x && !warea.y) { int changed_pos = 0; if(n_widgets > 0) { SDL_Rect parea = widgets[n_widgets - 1]->GetArea(); if((parea.x + parea.w + warea.w) > area.w) { warea.y = parea.y + parea.h; } else { warea.x = parea.x + parea.w; warea.y = parea.y; } changed_pos = 1; } if(((GUI_Drawable*)widget)->GetWType() != WIDGET_TYPE_OTHER) { int wflags = widget->GetFlags(); if(wflags & WIDGET_ALIGN_MASK) { changed_pos = 1; } switch (wflags & WIDGET_HORIZ_MASK) { case WIDGET_HORIZ_CENTER: warea.x = area.x + (area.w - warea.w) / 2; break; case WIDGET_HORIZ_LEFT: warea.x = area.x; break; case WIDGET_HORIZ_RIGHT: warea.x = area.x + area.w - warea.w; break; default: break; } switch (wflags & WIDGET_VERT_MASK) { case WIDGET_VERT_CENTER: warea.y = area.y + (area.h - warea.h) / 2; break; case WIDGET_VERT_TOP: warea.y = area.y; break; case WIDGET_VERT_BOTTOM: warea.y = area.y + area.h - warea.h; break; default: break; } } if(changed_pos) { widget->SetPosition(warea.x, warea.y); } } widgets[n_widgets++] = widget; UpdateLayout(); } void GUI_Container::RemoveWidget(GUI_Widget *widget) { int i, j; //assert(widget->GetParent() == this); if(widget->GetParent() != this) { return; } widget->SetParent(0); for (i=0, j=0; i<n_widgets; i++) { if (widgets[i] == widget) widget->DecRef(); else widgets[j++] = widgets[i]; } n_widgets = j; UpdateLayout(); } void GUI_Container::RemoveAllWidgets() { int i; for (i = 0; i < n_widgets; i++) { widgets[i]->SetParent(0); widgets[i]->DecRef(); } n_widgets = 0; UpdateLayout(); } void GUI_Container::UpdateLayout(void) { } int GUI_Container::GetWidgetCount() { return n_widgets; } GUI_Widget *GUI_Container::GetWidget(int index) { if (index <0 || index >= n_widgets) return NULL; return widgets[index]; } void GUI_Container::Draw(GUI_Surface *image, const SDL_Rect *sr, const SDL_Rect *dr) { if (parent) { SDL_Rect dest = Adjust(dr); SDL_Rect src; if (sr != NULL) src = *sr; else { src.x = src.y = 0; src.w = image->GetWidth(); src.h = image->GetHeight(); } dest.x -= x_offset; dest.y -= y_offset; if (GUI_ClipRect(&src, &dest, &area)) parent->Draw(image, &src, &dest); } } void GUI_Container::Fill(const SDL_Rect *dr, SDL_Color c) { if (parent) { SDL_Rect dest = Adjust(dr); dest.x -= x_offset; dest.y -= y_offset; if (GUI_ClipRect(NULL, &dest, &area)) parent->Fill(&dest, c); } } void GUI_Container::Erase(const SDL_Rect *rp) { if (parent && rp != NULL) { //assert(rp != NULL); SDL_Rect dest = Adjust(rp); dest.x -= x_offset; dest.y -= y_offset; if (GUI_ClipRect(NULL, &dest, &area)) { if (flags & WIDGET_TRANSPARENT) parent->Erase(&dest); if (background) { if(!bg_center) parent->TileImage(background, &dest, x_offset, y_offset); else parent->CenterImage(background, &dest, x_offset, y_offset); } else if ((flags & WIDGET_TRANSPARENT) == 0) parent->Fill(&dest, bgcolor); } } } void GUI_Container::SetBackground(GUI_Surface *surface) { bg_center = 0; SetFlags(WIDGET_TRANSPARENT); if (GUI_ObjectKeep((GUI_Object **) &background, surface)) MarkChanged(); } void GUI_Container::SetBackgroundCenter(GUI_Surface *surface) { bg_center = 1; SetFlags(WIDGET_TRANSPARENT); if (GUI_ObjectKeep((GUI_Object **) &background, surface)) MarkChanged(); } void GUI_Container::SetBackgroundColor(SDL_Color c) { bgcolor = c; ClearFlags(WIDGET_TRANSPARENT); MarkChanged(); } void GUI_Container::SetXOffset(int value) { x_offset = value; MarkChanged(); } void GUI_Container::SetYOffset(int value) { y_offset = value; MarkChanged(); } int GUI_Container::GetXOffset() { return x_offset; } int GUI_Container::GetYOffset() { return y_offset; } void GUI_Container::SetEnabled(int flag) { int i; for (i = 0; i < n_widgets; i++) widgets[i]->SetEnabled(flag); if (flag) ClearFlags(WIDGET_DISABLED); else SetFlags(WIDGET_DISABLED); MarkChanged(); } extern "C" { int GUI_ContainerContains(GUI_Widget *container, GUI_Widget *widget) { return ((GUI_Container *) container)->ContainsWidget(widget); } void GUI_ContainerAdd(GUI_Widget *container, GUI_Widget *widget) { ((GUI_Container *) container)->AddWidget(widget); } void GUI_ContainerRemove(GUI_Widget *container, GUI_Widget *widget) { ((GUI_Container *) container)->RemoveWidget(widget); } void GUI_ContainerRemoveAll(GUI_Widget *container) { ((GUI_Container *) container)->RemoveAllWidgets(); } int GUI_ContainerGetCount(GUI_Widget *container) { return ((GUI_Container *) container)->GetWidgetCount(); } GUI_Widget *GUI_ContainerGetChild(GUI_Widget *container, int index) { return ((GUI_Container *) container)->GetWidget(index); } void GUI_ContainerSetEnabled(GUI_Widget *container, int flag) { ((GUI_Container *) container)->SetEnabled(flag); } int GUI_ContainerIsVisibleWidget(GUI_Widget *container, GUI_Widget *widget) { return ((GUI_Container *) container)->IsVisibleWidget(widget); } } <file_sep>/firmware/isoldr/syscalls/include/syscalls.h /** * This file is part of DreamShell ISO Loader * Copyright (C)2019 megavolt85 * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef __uint32_t_defined typedef unsigned int uint32_t; # define __uint32_t_defined #endif #ifndef __uint16_t_defined typedef unsigned short uint16_t; # define __uint16_t_defined #endif #ifndef __uint8_t_defined typedef unsigned char uint8_t; # define __uint8_t_defined #endif /* Macros to access the ATA registers */ #define OUT32(addr, data) *((volatile uint32_t *)addr) = data #define OUT16(addr, data) *((volatile uint16_t *)addr) = data #define OUT8(addr, data) *((volatile uint8_t *)addr) = data #define IN32(addr) *((volatile uint32_t *)addr) #define IN16(addr) *((volatile uint16_t *)addr) #define IN8(addr) *((volatile uint8_t *)addr) /* ATA-related registers. Some of these serve very different purposes when read than they do when written (hence why some addresses are duplicated). */ #define G1_ATA_ALTSTATUS 0xA05F7018 /* Read */ #define G1_ATA_CTL 0xA05F7018 /* Write */ #define G1_ATA_DATA 0xA05F7080 /* Read/Write */ #define G1_ATA_ERROR 0xA05F7084 /* Read */ #define G1_ATA_FEATURES 0xA05F7084 /* Write */ #define G1_ATA_IRQ_REASON 0xA05F7088 /* Read */ #define G1_ATA_SECTOR_COUNT 0xA05F7088 /* Write */ #define G1_ATA_LBA_LOW 0xA05F708C /* Read/Write */ #define G1_ATA_LBA_MID 0xA05F7090 /* Read/Write */ #define G1_ATA_LBA_HIGH 0xA05F7094 /* Read/Write */ #define G1_ATA_DEVICE_SELECT 0xA05F7098 /* Read/Write */ #define G1_ATA_STATUS_REG 0xA05F709C /* Read */ #define G1_ATA_COMMAND_REG 0xA05F709C /* Write */ /* DMA-related registers. */ #define G1_ATA_DMA_ADDRESS 0xA05F7404 /* Read/Write */ #define G1_ATA_DMA_LENGTH 0xA05F7408 /* Read/Write */ #define G1_ATA_DMA_DIRECTION 0xA05F740C /* Read/Write */ #define G1_ATA_DMA_ENABLE 0xA05F7414 /* Read/Write */ #define G1_ATA_DMA_STATUS 0xA05F7418 /* Read/Write */ #define G1_ATA_DMA_STARD 0xA05F74F4 /* Read-only */ #define G1_ATA_DMA_LEND 0xA05F74F8 /* Read-only */ #define G1_ATA_DMA_PRO 0xA05F74B8 /* Write-only */ #define G1_ATA_DMA_PRO_SYSMEM 0x8843407F #define ASIC_BASE (0xa05f6900) #define ASIC_IRQ_STATUS ((volatile uint32_t *) (ASIC_BASE + 0x00)) #define ASIC_IRQ13_MASK ((volatile uint32_t *) (ASIC_BASE + 0x10)) #define ASIC_IRQ11_MASK ((volatile uint32_t *) (ASIC_BASE + 0x20)) #define ASIC_IRQ9_MASK ((volatile uint32_t *) (ASIC_BASE + 0x30)) #define ASIC_MASK_NRM_INT 0 #define ASIC_MASK_EXT_INT 1 #define ASIC_MASK_ERR_INT 2 /* status of the external interrupts * bit 3 = External Device interrupt * bit 2 = Modem interrupt * bit 1 = AICA interrupt * bit 0 = GD-ROM interrupt */ #define EXT_INT_STAT 0xA05F6904 /* Read */ /* status of the nonmal interrupts */ #define NORMAL_INT_STAT 0xA05F6900 /* Read/Write */ /* Bitmasks for the STATUS_REG/ALT_STATUS registers. */ #define G1_ATA_SR_ERR 0x01 #define G1_ATA_SR_IDX 0x02 #define G1_ATA_SR_CORR 0x04 #define G1_ATA_SR_DRQ 0x08 #define G1_ATA_SR_DSC 0x10 #define G1_ATA_SR_DF 0x20 #define G1_ATA_SR_DRDY 0x40 #define G1_ATA_SR_BSY 0x80 /* Bitmasks for the G1_ATA_ERROR registers. */ #define G1_ATA_ER_BBK 0x80 #define G1_ATA_ER_UNC 0x40 #define G1_ATA_ER_MC 0x20 #define G1_ATA_ER_IDNF 0x10 #define G1_ATA_ER_MCR 0x08 #define G1_ATA_ER_ABRT 0x04 #define G1_ATA_ER_TK0NF 0x02 #define G1_ATA_ER_AMNF 0x01 /* ATA Commands we might like to send. */ #define ATA_CMD_READ_SECTORS 0x20 #define ATA_CMD_READ_SECTORS_EXT 0x24 #define ATA_CMD_READ_DMA_EXT 0x25 #define ATA_CMD_READ_DMA 0xC8 #define g1_ata_wait_status(n) \ do {} while((IN8(G1_ATA_ALTSTATUS) & (n))) /* Values for CMD_GETSCD command */ #define SCD_REQ_ALL_SUBCODE 0x0 #define SCD_REQ_Q_SUBCODE 0x1 #define SCD_REQ_MEDIA_CATALOG 0x2 #define SCD_REQ_ISRC 0x3 #define SCD_REQ_RESERVED 0x4 #define SCD_AUDIO_STATUS_INVALID 0x00 #define SCD_AUDIO_STATUS_PLAYING 0x11 #define SCD_AUDIO_STATUS_PAUSED 0x12 #define SCD_AUDIO_STATUS_ENDED 0x13 #define SCD_AUDIO_STATUS_ERROR 0x14 #define SCD_AUDIO_STATUS_NO_INFO 0x15 #define SCD_DATA_SIZE_INDEX 3 typedef enum { CMD_STAT_FAILED =-1, CMD_STAT_NO_ACTIVE = 0, CMD_STAT_PROCESSING = 1, CMD_STAT_COMPLETED = 2, CMD_STAT_ABORTED = 3, CMD_STAT_WAITING = 4, CMD_STAT_ERROR = 5 } gd_cmd_stat_t; typedef enum { GDCMD_OK = 0, GDCMD_HW_ERR = 2, GDCMD_INVALID_CMD = 5, GDCMD_NOT_INITED = 6, GDCMD_GDSYS_LOCKED = 32, } gd_cmd_err_t; /* GD status */ typedef enum { STAT_BUSY = 0, STAT_PAUSE = 1, STAT_STANDBY = 2, STAT_PLAY = 3, STAT_SEEK = 4, STAT_SCAN = 5, STAT_OPEN = 6, STAT_NODISK = 7, STAT_RETRY = 8, STAT_ERROR = 9 } gd_drv_stat_t; /* Different media types */ typedef enum { TYPE_CDDA = 0x00, TYPE_CDROM = 0x10, TYPE_CDROMXA = 0x20, TYPE_CDI = 0x30, TYPE_GDROM = 0x80 } gd_media_t; typedef struct { uint32_t entry[99]; uint32_t first; uint32_t last; uint32_t leadout_sector; } toc_t; typedef struct { int gd_cmd; int gd_cmd_stat; int gd_cmd_err; int gd_cmd_err2; uint32_t param[4]; void *gd_hw_base; uint32_t transfered; int ata_status; int drv_stat; int drv_media; int cmd_abort; uint32_t requested; int gd_chn; int dma_in_progress; int need_reinit; void *callback; int callback_param; short *pioaddr; int piosize; char cmdp[28]; toc_t TOC; uint32_t dtrkLBA[3]; uint32_t dsLBA; uint32_t dsseccnt; uint32_t currentLBA; } GDS; extern short disc_type; extern uint32_t disc_id[5]; extern uint32_t gd_vector2; extern uint8_t display_cable; extern int gd_gdrom_syscall(int, uint32_t*, int, int); extern void Exit_to_game(void); extern int allocate_GD(void); extern void release_GD(void); extern GDS *get_GDS(void); extern int lock_gdsys(int lock); extern void gd_do_cmd(uint32_t *param, GDS *my_gds, int cmd); extern uint32_t irq_disable(); extern void irq_restore(uint32_t old); extern void flush_cache(void); extern int flashrom_lock(void); extern void flashrom_unlock(void); #ifdef LOG int scif_init(); int WriteLog(const char *fmt, ...); int WriteLogFunc(const char *func, const char *fmt, ...); #define LOGF(...) WriteLog(__VA_ARGS__) #define LOGFF(...) WriteLogFunc(__func__, __VA_ARGS__) #endif <file_sep>/firmware/isoldr/loader/include/reader.h /** * DreamShell ISO Loader * ISO, CSO, CDI and GDI reader * (c)2009-2022 SWAT <http://www.dc-swat.ru> */ #include "main.h" #include "isofs/ciso.h" int InitReader(); int ReadSectors(uint8 *buf, int sec, int num, fs_callback_f *cb); int PreReadSectors(int sec, int num); void switch_gdi_data_track(uint32 lba, gd_state_t *GDS); extern int iso_fd; <file_sep>/modules/sqlite3/module.c /* DreamShell ##version## module.c - sqlite3 module Copyright (C)2011-2014 SWAT */ #include "ds.h" #include "sqlite3.h" DEFAULT_MODULE_EXPORTS(sqlite3); <file_sep>/src/drivers/asic.c /* DreamShell ##version## asic.c Copyright (C) 2014-2015 SWAT */ #include <arch/types.h> #include <errno.h> #include <dc/asic.h> #include <kos/dbglog.h> #include <drivers/asic.h> void asic_sys_reset(void) { ASIC_SYS_RESET = 0x00007611; while(1); } void asic_ide_enable(void) { uint32 p; volatile uint32 *bios = (uint32*)0xa0000000; /* * Send the BIOS size and then read each word * across the bus so the controller can verify it. */ if((*(uint16 *)0xa0000000) == 0xe6ff) { // Initiate BIOS checking for 1KB ASIC_BIOS_PROT = 0x3ff; for(p = 0; p < 0x400 / sizeof(bios[0]); p++) { (void)bios[p]; } } else { // Initiate BIOS checking for 2MB ASIC_BIOS_PROT = 0x1fffff; for(p = 0; p < 0x200000 / sizeof(bios[0]); p++) { (void)bios[p]; } } } void asic_ide_disable(void) { ASIC_BIOS_PROT = 0x000042FE; } <file_sep>/modules/mp3/libmp3/xingmp3/port.h /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ #ifndef O_BINARY #define O_BINARY 0 #endif /*--- no kb function unless DOS ---*/ #ifndef KB_OK #ifdef __MSDOS__ #define KB_OK #endif #ifdef _CONSOLE #define KB_OK #endif #endif #ifdef NEED_KBHIT #ifdef KB_OK #ifdef _MSC_VER #pragma warning(disable: 4032) #endif #include <conio.h> #else static int kbhit() { return 0; } static int getch() { return 0; } #endif #endif /*-- no pcm conversion to wave required if short = 16 bits and little endian ---*/ /* mods 1/9/97 LITTLE_SHORT16 detect */ #ifndef LITTLE_SHORT16 #ifdef __MSDOS__ #undef LITTLE_SHORT16 #define LITTLE_SHORT16 #endif #ifdef WIN32 #undef LITTLE_SHORT16 #define LITTLE_SHORT16 #endif #ifdef _M_IX86 #undef LITTLE_SHORT16 #define LITTLE_SHORT16 #endif #endif // JDW // //#ifdef LITTLE_SHORT16 //#define cvt_to_wave_init(a) //#define cvt_to_wave(a, b) b //#else //void cvt_to_wave_init(int bits); //unsigned int cvt_to_wave(void *a, unsigned int b); // //#endif #ifdef LITTLE_SHORT16 #define cvt_to_wave_init(a) #define cvt_to_wave(a, b) b #else void cvt_to_wave_init(int); unsigned int cvt_to_wave(unsigned char *,unsigned int); #endif int cvt_to_wave_test(void); <file_sep>/firmware/aica/codec/buffertest.rb require 'test/unit/assertions' include Test::Unit::Assertions def get_read_available() return @n_readable end def get_write_available() (MAX_BUFFERS - @n_readable - @n_busy) end def get_writable_buffer() # if @buffers[@wp] == :busy # # check if buffer is really busy # @buffers[@wp] = :empty # end if get_write_available > 0 buffer = @wp @wp = (@wp + 1) % MAX_BUFFERS @n_readable += 1 return buffer else return false end end def get_readable_buffer() if get_read_available > 0 buffer = @rp @rp = (@rp + 1) % MAX_BUFFERS @n_readable -= 1 return buffer else return false end end def show() puts "wp: #{@wp}" puts "rp: #{@rp}" puts "n_readable: #{@n_readable}" puts "n_busy: #{@n_busy}" puts "wa: #{get_write_available()}" puts "ra: #{get_read_available()}" puts end MAX_BUFFERS = 4 @buffers = [:empty] * MAX_BUFFERS @wp = 0 @rp = 0 @n_readable = 0 @n_busy = 0 puts "START" show buffer = get_writable_buffer() show buffer = get_writable_buffer() show buffer = get_readable_buffer() show buffer = get_readable_buffer() show buffer = get_readable_buffer() show assert_equal(false, buffer) buffer = get_writable_buffer() show buffer = get_writable_buffer() show buffer = get_writable_buffer() show buffer = get_writable_buffer() show buffer = get_writable_buffer() show assert_equal(false, buffer) get_readable_buffer() @n_busy = 1 show get_readable_buffer() @n_busy = 2 show @n_busy = 0 show <file_sep>/Makefile # # DreamShell Makefile # Copyright (C) 2004-2023 SWAT # http://www.dc-swat.ru # # This makefile can build CDI image (type "make cdi"), # launch DS on DC through dc-tool-ip (type "make run") # or launch DS on emulators nullDC and lxdream # (type "make nulldc" or "make lxdream"). # Scroll down to see other options. # TARGET = DS TARGET_NAME = DreamShell_v4.0.0_RC5 TARGET_BIN = $(TARGET)_CORE.BIN TARGET_BIN_CD = 1$(TARGET_BIN) TRAGET_VERSION = -DVER_MAJOR=4 -DVER_MINOR=0 -DVER_MICRO=0 -DVER_BUILD=0x25 #RC 5 # TARGET_DEBUG = 1 # or 2 for GDB # TARGET_EMU = 1 # TARGET_PROF = 1 all: rm-elf $(TARGET) include sdk/Makefile.cfg INC_DIR = $(DS_BASE)/include SRC_DIR = $(DS_BASE)/src LIB_DIR = $(DS_BASE)/lib KOS_LDFLAGS += -L$(LIB_DIR) KOS_CFLAGS += -I$(INC_DIR) -I$(INC_DIR)/SDL -I$(INC_DIR)/fatfs \ -DHAVE_SDLIMAGE $(TRAGET_VERSION) ifdef TARGET_DEBUG KOS_CFLAGS += -g -DDS_DEBUG=$(TARGET_DEBUG) endif ifdef TARGET_EMU KOS_CFLAGS += -DDS_EMU=1 endif SDL_VER = 1.2.13 SDL_GFX_VER = 2.0.25 SDL_IMAGE_VER = 1.2.12 SDL_TTF_VER = 2.0.11 SDL_RTF_VER = 0.1.1 LUA_VER = 5.1.4-2 EXTRA_LIBS = -lcfg -lmxml -lparallax SDL_LIBS = -lSDL_$(SDL_VER) \ -lSDL_image_$(SDL_IMAGE_VER) \ -lSDL_ttf_$(SDL_TTF_VER) \ -lSDL_rtf_$(SDL_RTF_VER) \ -lSDL_gfx_$(SDL_GFX_VER) \ -lfreetype IMAGE_LIBS = -lkmg -ljpeg -lpng -lz LUA_LIBS = -llua_$(LUA_VER) KLIBS = -lkosext2fs -lkosutils -lstdc++ -lm CORE_LIBS = $(EXTRA_LIBS) $(SDL_LIBS) $(IMAGE_LIBS) $(LUA_LIBS) $(KLIBS) SDL_GUI = $(LIB_DIR)/SDL_gui SDL_CONSOLE = $(LIB_DIR)/SDL_Console/src GUI_OBJS = $(SDL_GUI)/SDL_gui.o $(SDL_GUI)/Exception.o $(SDL_GUI)/Object.o \ $(SDL_GUI)/Surface.o $(SDL_GUI)/Font.o $(SDL_GUI)/Callback.o \ $(SDL_GUI)/Drawable.o $(SDL_GUI)/Screen.o $(SDL_GUI)/Widget.o \ $(SDL_GUI)/Container.o $(SDL_GUI)/FastFont.o $(SDL_GUI)/TrueTypeFont.o \ $(SDL_GUI)/Layout.o $(SDL_GUI)/Panel.o $(SDL_GUI)/CardStack.o \ $(SDL_GUI)/FastLabel.o $(SDL_GUI)/Label.o $(SDL_GUI)/Picture.o \ $(SDL_GUI)/TextEntry.o $(SDL_GUI)/AbstractButton.o $(SDL_GUI)/Button.o \ $(SDL_GUI)/ToggleButton.o $(SDL_GUI)/ProgressBar.o $(SDL_GUI)/ScrollBar.o \ $(SDL_GUI)/AbstractTable.o $(SDL_GUI)/ListBox.o $(SDL_GUI)/VBoxLayout.o \ $(SDL_GUI)/RealScreen.o $(SDL_GUI)/ScrollPanel.o $(SDL_GUI)/RTF.o \ $(SDL_GUI)/Window.o $(SDL_GUI)/FileManager.o CONSOLE_OBJ = $(SDL_CONSOLE)/SDL_console.o $(SDL_CONSOLE)/DT_drawtext.o \ $(SDL_CONSOLE)/internal.o DRIVERS_OBJ = $(SRC_DIR)/drivers/spi.o $(SRC_DIR)/drivers/sd.o \ $(SRC_DIR)/drivers/enc28j60.o $(SRC_DIR)/drivers/asic.o \ $(SRC_DIR)/drivers/rtc.o FATFS_DIR = $(SRC_DIR)/fs/fat FATFS = $(FATFS_DIR)/utils.o $(FATFS_DIR)/option/ccsbcs.o \ $(FATFS_DIR)/option/syscall.o $(FATFS_DIR)/ff.o \ $(FATFS_DIR)/dc.o UTILS_DIR = $(SRC_DIR)/utils UTILS_OBJ = $(SRC_DIR)/utils.o $(UTILS_DIR)/gmtime.o $(UTILS_DIR)/strftime.o \ $(UTILS_DIR)/debug_console.o $(UTILS_DIR)/memcpy.op \ $(UTILS_DIR)/memset.op $(UTILS_DIR)/memmove.op OBJS = $(SRC_DIR)/main.o $(SRC_DIR)/video.o $(SRC_DIR)/console.o \ $(SRC_DIR)/gui/gui.o $(SRC_DIR)/commands.o \ $(SRC_DIR)/module.o $(SRC_DIR)/events.o $(SRC_DIR)/fs/fs.o \ $(SRC_DIR)/lua/lua.o $(SRC_DIR)/lua/lua_ds.o $(SRC_DIR)/lua/packlib.o \ $(SRC_DIR)/app/app.o $(SRC_DIR)/app/load.o $(SRC_DIR)/list.o \ $(SRC_DIR)/img/pvr.o $(SRC_DIR)/cmd_elf.o $(SRC_DIR)/vmu/vmu.o \ $(SRC_DIR)/irq/exceptions.o $(SRC_DIR)/irq/setjmp.o \ $(SRC_DIR)/settings.o $(DRIVERS_OBJ) $(GUI_OBJS) $(CONSOLE_OBJ) \ $(UTILS_OBJ) $(FATFS) $(SRC_DIR)/exports.o $(SRC_DIR)/exports_gcc.o \ romdisk.o ifdef TARGET_PROF OBJS += $(SRC_DIR)/profiler.o KOS_CFLAGS += -DDS_PROF=$(TARGET_PROF) endif %.op: %.S kos-cc $(CFLAGS) -c $< -o $@ $(SRC_DIR)/exports.o: $(SRC_DIR)/exports.c $(SRC_DIR)/exports.c: exports.txt $(KOS_BASE)/utils/genexports/genexports.sh exports.txt $(SRC_DIR)/exports.c ds_symtab $(KOS_BASE)/utils/genexports/genexportstubs.sh exports.txt $(SRC_DIR)/exports_stubs.c $(KOS_MAKE) -f Makefile.stubs $(SRC_DIR)/exports_gcc.o: $(SRC_DIR)/exports_gcc.c $(SRC_DIR)/exports_gcc.c: exports_gcc.txt $(KOS_BASE)/utils/genexports/genexports.sh exports_gcc.txt $(SRC_DIR)/exports_gcc.c gcc_symtab $(KOS_BASE)/utils/genexports/genexportstubs.sh exports_gcc.txt $(SRC_DIR)/exports_gcc_stubs.c $(KOS_MAKE) -f Makefile.gcc_stubs romdisk.img: romdisk/logo.kmg.gz $(KOS_GENROMFS) -f romdisk.img -d romdisk -v romdisk.o: romdisk.img $(KOS_BASE)/utils/bin2o/bin2o romdisk.img romdisk romdisk.o logo: romdisk/logo.kmg.gz romdisk/logo.kmg.gz: $(DS_RES)/logo_sq.png $(KOS_BASE)/utils/kmgenc/kmgenc -v $(DS_RES)/logo_sq.png mv $(DS_RES)/logo_sq.kmg logo.kmg gzip -9 logo.kmg mv logo.kmg.gz romdisk/logo.kmg.gz make-build: $(DS_BUILD)/lua/startup.lua $(DS_BUILD)/lua/startup.lua: $(DS_RES)/lua/startup.lua @echo Creating build directory... @mkdir -p $(DS_BUILD) @mkdir -p $(DS_BUILD)/apps @mkdir -p $(DS_BUILD)/cmds @mkdir -p $(DS_BUILD)/modules @mkdir -p $(DS_BUILD)/screenshot @mkdir -p $(DS_BUILD)/vmu @cp -R $(DS_RES)/doc $(DS_BUILD) @cp -R $(DS_RES)/firmware $(DS_BUILD) @cp -R $(DS_RES)/fonts $(DS_BUILD) @cp -R $(DS_RES)/gui $(DS_BUILD) @cp -R $(DS_RES)/lua $(DS_BUILD) @mkdir -p $(DS_BUILD)/firmware/aica @cp ../kernel/arch/dreamcast/sound/arm/stream.drv $(DS_BUILD)/firmware/aica/kos_stream.drv libs: $(LIB_DIR)/libSDL_$(SDL_VER).a $(LIB_DIR)/libSDL_$(SDL_VER).a: cd $(LIB_DIR) && make build: $(TARGET) @echo Building modules, commands, applications and firmwares... cd $(DS_BASE)/modules && make && make install cd $(DS_BASE)/commands && make && make install cd $(DS_BASE)/applications && make && make install cd $(DS_BASE)/firmware/isoldr && make && make install cd $(DS_BASE)/firmware/bootloader && make && make install # cd $(DS_BASE)/firmware/aica && make && make install release: build cdi @echo Creating a full release... @-rm -rf $(DS_BUILD)/.* 2> /dev/null @-rm -rf $(DS_BASE)/release @mkdir -p $(DS_BASE)/release/$(TARGET) @cp -R $(DS_BUILD)/* $(DS_BASE)/release/$(TARGET) @cp $(TARGET_BIN) $(DS_BASE)/release/$(TARGET) @cd $(DS_BASE)/firmware/bootloader && make && make release @mv $(DS_BASE)/firmware/bootloader/*.cdi $(DS_BASE)/release @mv $(TARGET).cdi $(DS_BASE)/release/$(TARGET_NAME).cdi @echo Compressing... @cd $(DS_BASE)/release && zip -q -r $(TARGET_NAME).zip * 2> /dev/null @echo @echo "\033[42m Complete $(DS_BASE)/release \033[0m" $(TARGET): libs $(TARGET_BIN) make-build $(TARGET).elf: $(OBJS) $(KOS_CC) $(KOS_CFLAGS) $(KOS_LDFLAGS) -o $(TARGET).elf \ $(OBJS) $(OBJEXTRA) $(CORE_LIBS) $(KOS_LIBS) $(TARGET_BIN): $(TARGET).elf @echo Copy elf for debug... @cp $(TARGET).elf $(TARGET)-DBG.elf @echo Strip target... @$(KOS_STRIP) $(TARGET).elf @echo Creating binary file... @$(KOS_OBJCOPY) -R .stack -O binary $(TARGET).elf $(TARGET_BIN) $(TARGET_BIN_CD): $(TARGET_BIN) @echo Scramble binary file... @./sdk/bin/scramble $(TARGET_BIN) $(TARGET_BIN_CD) cdi: $(TARGET).cdi $(TARGET).cdi: $(TARGET_BIN_CD) make-build @echo Creating ISO... @-rm -f $(DS_BUILD)/$(TARGET_BIN) @-rm -f $(DS_BUILD)/$(TARGET_BIN_CD) @cp $(TARGET_BIN_CD) $(DS_BUILD)/$(TARGET_BIN_CD) @-rm -rf $(DS_BUILD)/.* 2> /dev/null @dd if=/dev/zero of=$(DS_BUILD)/0.0 bs=1024k count=450 @$(DS_SDK)/bin/mkisofs -V DreamShell -C 0,11702 -G $(DS_RES)/IP.BIN -joliet -rock -l -x .DS_Store -o $(TARGET).iso $(DS_BUILD) @echo Convert ISO to CDI... @-rm -f $(TARGET).cdi @$(DS_SDK)/bin/cdi4dc $(TARGET).iso $(TARGET).cdi >/dev/null @-rm -f $(TARGET).iso @-rm -f $(DS_BUILD)/$(TARGET_BIN_CD) @-rm -f $(DS_BUILD)/0.0 # If you have problems with mkisofs try data/data image: # $(DS_SDK)/bin/mkisofs -V DreamShell -G $(DS_RES)/IP.BIN -joliet -rock -l -x .DS_Store -o $(TARGET).iso $(DS_BUILD) # @$(DS_SDK)/bin/cdi4dc $(TARGET).iso $(TARGET).cdi -d >/dev/null nulldc: $(TARGET).cdi @echo Running DreamShell... @./emu/nullDC.exe -serial "debug.log" nulldcl: $(TARGET).cdi @echo Running DreamShell with log... @run ./emu/nullDC.exe -serial "debug.log" > emu.log run: $(TARGET).elf sudo $(DS_SDK)/bin/dc-tool-ip -c $(DS_BUILD) -t $(DC_LAN_IP) -x $(TARGET).elf run-serial: $(TARGET).elf sudo $(DS_SDK)/bin/dc-tool-ser -c $(DS_BUILD) -t $(DC_SERIAL_PORT) -b $(DC_SERIAL_BAUD) -x $(TARGET).elf debug: $(TARGET).elf sudo $(DS_SDK)/bin/dc-tool-ip -g -c $(DS_BUILD) -t $(DC_LAN_IP) -x $(TARGET).elf debug-serial: $(TARGET).elf sudo $(DS_SDK)/bin/dc-tool-ser -g -c $(DS_BUILD) -t $(DC_SERIAL_PORT) -b $(DC_SERIAL_BAUD) -x $(TARGET).elf gdb: $(TARGET)-DBG.elf $(KOS_CC_BASE)/bin/$(KOS_CC_PREFIX)-gdb $(TARGET)-DBG.elf --eval-command "target remote localhost:2159" lxdream: $(TARGET).cdi lxdream -d -p $(TARGET).cdi lxdelf: $(TARGET).elf lxdream -u -p -e $(TARGET).elf lxdgdb: $(TARGET).cdi lxdream -g 2000 -n $(TARGET).cdi & sleep 2 $(KOS_CC_BASE)/bin/$(KOS_CC_PREFIX)-gdb $(TARGET)-DBG.elf --eval-command "target remote localhost:2000" gprof: @sh-elf-gprof $(TARGET)-DBG.elf $(DS_BUILD)/kernel_gmon.out > gprof.out @cat gprof.out | gprof2dot | dot -Tpng -o $(TARGET)-kernel.png @sh-elf-gprof $(TARGET)-DBG.elf $(DS_BUILD)/video_gmon.out > gprof.out @cat gprof.out | gprof2dot | dot -Tpng -o $(TARGET)-video.png @-rm -rf gprof.out @echo "\033[42m Profiling data saved to $(TARGET)-*.png \033[0m" TARGET_CLEAN_BIN = 1$(TARGET)_CORE.BIN $(TARGET)_CORE.BIN $(TARGET).elf $(TARGET).cdi clean: -rm -f $(TARGET_CLEAN_BIN) $(OBJS) $(SRC_DIR)/exports.c $(SRC_DIR)/exports_gcc.c rm-elf: -rm -f $(TARGET_CLEAN_BIN) -rm -f $(SRC_DIR)/main.o <file_sep>/applications/region_changer/lua/main.lua ----------------------------------------- -- -- -- @name: Region Changer -- -- @version: 1.8.5 -- -- @author: SWAT -- -- @url: http://www.dc-swat.ru -- -- -- ----------------------------------------- --if not RegionChanger then RegionChanger = { app = nil, pages = nil, progress = nil, swirl = nil, broadcast = {}, country = {}, lang = {}, clear = { sys = nil, game = nil }, data = nil, values = nil } function RegionChanger:ShowPage(index) DS.ScreenFadeOut(); Sleep(500); GUI.CardStackShowIndex(self.pages, index); DS.ScreenFadeIn(); end function RegionChanger:isFileExists(file) local f = io.open(file); if f ~= nil then f:close(); return true; end return false; end function RegionChanger:SelectBroadcast(index) for i = 1, table.getn(self.broadcast) do if i == index then --if not GUI.WidgetGetState(self.broadcast[i]) then GUI.WidgetSetState(self.broadcast[i], 1); RC.flash_factory_set_broadcast(self.data, index); --end else GUI.WidgetSetState(self.broadcast[i], 0); end end end function RegionChanger:SelectCountry(index) for i = 1, table.getn(self.country) do if i == index then --if not GUI.WidgetGetState(self.country[i]) then GUI.WidgetSetState(self.country[i], 1); RC.flash_factory_set_country(self.data, index, GUI.WidgetGetState(self.swirl)); --end else GUI.WidgetSetState(self.country[i], 0); end end end function RegionChanger:SelectLang(index) for i = 1, table.getn(self.lang) do if i == index then --if not GUI.WidgetGetState(self.lang[i]) then GUI.WidgetSetState(self.lang[i], 1); RC.flash_factory_set_lang(self.data, index); --end else GUI.WidgetSetState(self.lang[i], 0); end end end function RegionChanger:Read() if self.data then RC.flash_factory_free_data(self.data); RC.flash_factory_free_values(self.values); end self.data = RC.flash_read_factory(); self.values = RC.flash_factory_get_values(self.data); GUI.WidgetSetState(self.swirl, self.values.black_swirl); self:SelectCountry(self.values.country); self:SelectBroadcast(self.values.broadcast); self:SelectLang(self.values.lang); end function RegionChanger:Write() RC.flash_write_factory(self.data); end function RegionChanger:ClearFlashrom() if GUI.WidgetGetState(self.clear.sys) then RC.flash_clear(KOS.FLASHROM_PT_SETTINGS); end if GUI.WidgetGetState(self.clear.game) then RC.flash_clear(KOS.FLASHROM_PT_BLOCK_1); end end function RegionChanger:ChangeProgress(p) GUI.ProgressBarSetPosition(self.progress, p); end function RegionChanger:CreateBackup() self:ChangeProgress(0.1); local file = os.getenv("PATH").."/firmware/flash/factory_backup.bin"; if self:isFileExists(file) then os.remove(file); end local f = KOS.fs_open(file, KOS.O_WRONLY); self:ChangeProgress(0.2); local data = RC.flash_read_factory(); self:ChangeProgress(0.4); if f > -1 then KOS.fs_write(f, data, 8192); self:ChangeProgress(0.6); KOS.fs_close(f); RC.flash_factory_free_data(data); self:ChangeProgress(0.8); else file = "/ram/flash_backup.bin"; f = KOS.fs_open(file, KOS.O_WRONLY); if self:isFileExists("/vmu/a1/FLASHBKP.BIN") then os.remove("/vmu/a1/FLASHBKP.BIN"); elseif self:isFileExists("/vmu/a2/FLASHBKP.BIN") then os.remove("/vmu/a2/FLASHBKP.BIN"); end KOS.fs_write(f, data, 8192); self:ChangeProgress(0.6); KOS.fs_close(f); RC.flash_factory_free_data(data); self:ChangeProgress(0.8); if os.execute("vmu -c -n -f "..file.." -o /vmu/a1/FLASHBKP.BIN -i Region Changer Backup") ~= DS.CMD_OK then os.execute("vmu -c -n -f "..file.." -o /vmu/a2/FLASHBKP.BIN -i Region Changer Backup"); end os.remove(file); end self:ChangeProgress(1.0); end function RegionChanger:RestoreBackup() self:ChangeProgress(0.1); local file = os.getenv("PATH").."/firmware/flash/factory_backup.bin"; local f = KOS.fs_open(file, KOS.O_RDONLY); local data = RC.flash_read_factory(); self:ChangeProgress(0.2); if f > -1 then self:ChangeProgress(0.4); KOS.fs_read(f, data, 8192); self:ChangeProgress(0.6); KOS.fs_close(f); RC.flash_write_factory(data); self:ChangeProgress(0.8); RC.flash_factory_free_data(data); self:Read(); else file = "/ram/flash_backup.bin"; if not os.execute("vmu -c -v -f "..file.." -o /vmu/a1/FLASHBKP.BIN") then os.execute("vmu -c -v -f "..file.." -o /vmu/a2/FLASHBKP.BIN"); end self:ChangeProgress(0.4); f = KOS.fs_open(file, KOS.O_RDONLY); self:ChangeProgress(0.6); KOS.fs_read(f, data, 8192); self:ChangeProgress(0.8); KOS.fs_close(f); RC.flash_write_factory(data); self:ChangeProgress(0.9); RC.flash_factory_free_data(data); os.remove(file); self:Read(); end self:ChangeProgress(1.0); end function RegionChanger:GetElement(name) local el = DS.listGetItemByName(self.app.elements, name); if el ~= nil then return GUI.AnyToWidget(el.data); end return nil; end function RegionChanger:Initialize() if self.app == nil then self.app = DS.GetAppById(THIS_APP_ID); if self.app ~= nil then self.pages = self:GetElement("pages"); self.progress = self:GetElement("backup-progress"); self.swirl = self:GetElement("change-swirl-checkbox"); self.clear.sys = self:GetElement("clear-sys-checkbox"); self.clear.game = self:GetElement("clear-game-checkbox"); table.insert(self.country, self:GetElement("change-country-japan-checkbox")); table.insert(self.country, self:GetElement("change-country-usa-checkbox")); table.insert(self.country, self:GetElement("change-country-europe-checkbox")); table.insert(self.broadcast, self:GetElement("change-ntsc-checkbox")); table.insert(self.broadcast, self:GetElement("change-pal-checkbox")); table.insert(self.broadcast, self:GetElement("change-palm-checkbox")); table.insert(self.broadcast, self:GetElement("change-paln-checkbox")); table.insert(self.lang, self:GetElement("change-lang-japan-checkbox")); table.insert(self.lang, self:GetElement("change-lang-english-checkbox")); table.insert(self.lang, self:GetElement("change-lang-german-checkbox")); table.insert(self.lang, self:GetElement("change-lang-french-checkbox")); table.insert(self.lang, self:GetElement("change-lang-spanish-checkbox")); table.insert(self.lang, self:GetElement("change-lang-italian-checkbox")); self:Read(); return true; end end end --end<file_sep>/src/list.c /**************************** * DreamShell ##version## * * list.c * * DreamShell list manager * * Created by SWAT * * http://www.dc-swat.ru * ***************************/ #include <kos.h> #include <stdlib.h> #include "list.h" Item_list_t *listMake() { Item_list_t *l; l = (Item_list_t *) calloc(1, sizeof(Item_list_t)); if(l == NULL) return NULL; SLIST_INIT(l); return l; } void listDestroy(Item_list_t *lst, listFreeItemFunc *ifree) { Item_t *c, *n; c = SLIST_FIRST(lst); while(c) { n = SLIST_NEXT(c, list); if(ifree != NULL) ifree(c->data); free(c); c = n; } SLIST_INIT(lst); free(lst); } static uint32 listLastId = 0; uint32 listGetLastId(Item_list_t *lst) { return listLastId; } Item_t *listAddItem(Item_list_t *lst, ListItemType type, const char *name, void *data, uint32 size) { Item_t *i = NULL; i = (Item_t *) calloc(1, sizeof(Item_t)); if(i == NULL) return NULL; i->name = name; i->type = type; i->id = ++listLastId; i->data = data; i->size = size; //printf("List added item with id=%d\n", i->id); SLIST_INSERT_HEAD(lst, i, list); return i; } void listRemoveItem(Item_list_t *lst, Item_t *i, listFreeItemFunc *ifree) { SLIST_REMOVE(lst, i, Item, list); if(ifree != NULL) ifree(i->data); free(i); } Item_t *listGetItemByName(Item_list_t *lst, const char *name) { Item_t *i; SLIST_FOREACH(i, lst, list) { if(!strcmp(name, i->name)) return i; } return NULL; } Item_t *listGetItemByNameAndType(Item_list_t *lst, const char *name, ListItemType type) { Item_t *i; SLIST_FOREACH(i, lst, list) { if(i->type == type && !strcmp(name, i->name)) return i; } return NULL; } Item_t *listGetItemByType(Item_list_t *lst, ListItemType type) { Item_t *i; SLIST_FOREACH(i, lst, list) { if(i->type == type) return i; } return NULL; } Item_t *listGetItemById(Item_list_t *lst, uint32 id) { Item_t *i; SLIST_FOREACH(i, lst, list) { if(id == i->id) return i; } return NULL; } Item_t *listGetItemFirst(Item_list_t *lst) { return SLIST_FIRST(lst); } Item_t *listGetItemNext(Item_t *i) { return SLIST_NEXT(i, list); } <file_sep>/firmware/isoldr/loader/reader.c /** * DreamShell ISO Loader * ISO, CSO, CDI and GDI reader * (c)2009-2022 SWAT <http://www.dc-swat.ru> */ #include <main.h> #include <mmu.h> #ifdef HAVE_LZO #include <minilzo.h> #endif #define MAX_OPEN_TRACKS 3 int iso_fd = FILEHND_INVALID; static int _iso_fd[MAX_OPEN_TRACKS] = {FILEHND_INVALID, FILEHND_INVALID, FILEHND_INVALID}; static uint16 b_seek = 0, a_seek = 0; #ifdef HAVE_LZO static int _open_ciso(); static int _read_ciso_sectors(uint8 *buff, uint sector, uint cnt); #endif static int _read_data_sectors(uint8 *buff, uint sector, uint cnt, fs_callback_f *cb); static void _open_iso() { gd_state_t *GDS = get_GDS(); if(IsoInfo->image_type == ISOFS_IMAGE_TYPE_GDI) { DBGFF("track=%d fd=%d fd[0]=%d fd[1]=%d fd[2]=%d\n", GDS->data_track, iso_fd, _iso_fd[0], _iso_fd[1], _iso_fd[2]); /** * This magic for GDI with 2 data tracks (keep open both). * Also keep open first track if we can use additional fd. */ if(GDS->data_track < 3 && _iso_fd[0] > -1) { iso_fd = _iso_fd[0]; return; } else if(GDS->data_track == 3 && _iso_fd[1] > -1) { iso_fd = _iso_fd[1]; if(IsoInfo->emu_cdda && _iso_fd[0] > -1) { close(_iso_fd[0]); _iso_fd[0] = -1; } return; } else if(GDS->data_track > 3 && _iso_fd[2] > -1) { iso_fd = _iso_fd[2]; if(IsoInfo->emu_cdda && _iso_fd[0] > -1) { close(_iso_fd[0]); _iso_fd[0] = -1; } return; } } LOGF("Opening file: %s\n", IsoInfo->image_file); iso_fd = open(IsoInfo->image_file, O_RDONLY); if(IsoInfo->image_type == ISOFS_IMAGE_TYPE_GDI) { if(GDS->data_track < 3) { _iso_fd[0] = iso_fd; } else if(GDS->data_track == 3) { _iso_fd[1] = iso_fd; } else if(GDS->data_track > 3) { _iso_fd[2] = iso_fd; } } } int InitReader() { iso_fd = FILEHND_INVALID; for(int i = 0; i < MAX_OPEN_TRACKS; ++i) { _iso_fd[i] = FILEHND_INVALID; } if(fs_init() < 0) { return 0; } gd_state_t *GDS = get_GDS(); GDS->lba = 150; if(IsoInfo->image_type == ISOFS_IMAGE_TYPE_GDI) { int len = strlen(IsoInfo->image_file); IsoInfo->image_file[len - 6] = '0'; IsoInfo->image_file[len - 5] = '3'; GDS->data_track = 3; } else { GDS->data_track = 1; } _open_iso(); if(iso_fd < 0) { #ifdef LOG printf("Error %d, can't open:\n%s\n", iso_fd, IsoInfo->image_file); #else printf("Error, can't open: \n"); printf(IsoInfo->image_file); printf("\n"); #endif return 0; } #ifdef HAVE_LZO if(IsoInfo->image_type == ISOFS_IMAGE_TYPE_ZSO || IsoInfo->image_type == ISOFS_IMAGE_TYPE_CSO) { LOGF("Opening CISO...\n"); if(_open_ciso() < 0) { printf("Error, can't open CISO image\n"); return 0; } } #endif /* Setup sector info of image */ switch(IsoInfo->sector_size) { case 2324: /* MODE2_FORM2 */ b_seek = 16; a_seek = 260; break; case 2336: /* SEMIRAW_MODE2 */ b_seek = 8; a_seek = 280; break; case 2352: /* RAW_XA */ b_seek = 16; a_seek = 288; break; default: b_seek = 0; a_seek = 0; break; } return 1; } void switch_gdi_data_track(uint32 lba, gd_state_t *GDS) { if(lba < IsoInfo->track_lba[0] && GDS->data_track != 1) { int len = strlen(IsoInfo->image_file); IsoInfo->image_file[len - 6] = '0'; IsoInfo->image_file[len - 5] = '1'; GDS->data_track = 1; _open_iso(); } else if((IsoInfo->track_lba[0] == IsoInfo->track_lba[1] || lba < IsoInfo->track_lba[1]) && GDS->data_track != 3) { int len = strlen(IsoInfo->image_file); IsoInfo->image_file[len - 6] = '0'; IsoInfo->image_file[len - 5] = '3'; GDS->data_track = 3; _open_iso(); } else if(lba >= IsoInfo->track_lba[1] && GDS->data_track <= 3) { int len = strlen(IsoInfo->image_file); IsoInfo->image_file[len - 6] = IsoInfo->image_second[5]; IsoInfo->image_file[len - 5] = IsoInfo->image_second[6]; uint8 n = (IsoInfo->image_second[5] - '0') & 0xf; GDS->data_track = n * 10; n = (IsoInfo->image_second[6] - '0'); GDS->data_track += n; _open_iso(); } DBGFF("%d\n", GDS->data_track); } int ReadSectors(uint8 *buf, int sec, int num, fs_callback_f *cb) { DBGFF("%d from %d\n", num, sec); int rv; gd_state_t *GDS = get_GDS(); GDS->lba = sec + num; switch(IsoInfo->image_type) { #ifdef HAVE_LZO case ISOFS_IMAGE_TYPE_CSO: case ISOFS_IMAGE_TYPE_ZSO: rv = _read_ciso_sectors(buf, sec - IsoInfo->track_lba[0], num); break; #endif /* HAVE_LZO */ case ISOFS_IMAGE_TYPE_CDI: rv = _read_data_sectors(buf, sec - IsoInfo->track_lba[0], num, cb); break; case ISOFS_IMAGE_TYPE_GDI: { uint32 lba = 0; if(sec) { switch_gdi_data_track(sec, GDS); lba = sec - ( (uint32)sec < IsoInfo->track_lba[0] ? 150 : IsoInfo->track_lba[(GDS->data_track == 3 ? 0 : 1)] ); /* Check for data exists */ if(GDS->data_track > 3 && lba > IsoInfo->track_lba[1] + (total(iso_fd) / IsoInfo->sector_size)) { LOGFF("ERROR! Track %d LBA %d\n", GDS->data_track, sec); return COMPLETED; } } rv = _read_data_sectors(buf, lba, num, cb); break; } case ISOFS_IMAGE_TYPE_ISO: default: { size_t offset = (sec - IsoInfo->track_lba[0]) * IsoInfo->sector_size; size_t len = num * IsoInfo->sector_size; lseek(iso_fd, offset, SEEK_SET); if(cb != NULL) { #ifdef _FS_ASYNC if(read_async(iso_fd, buf, len, cb) < 0) { rv = FAILED; } else { rv = PROCESSING; } #else rv = FAILED; #endif /* _FS_ASYNC */ } else { if(read(iso_fd, buf, len) < 0) { rv = FAILED; } else { rv = COMPLETED; } } break; } } return rv; } int PreReadSectors(int sec, int num) { DBGFF("%d from %d\n", num, sec); gd_state_t *GDS = get_GDS(); GDS->lba = sec + num; uint32 lba = IsoInfo->track_lba[0]; if(IsoInfo->image_type == ISOFS_IMAGE_TYPE_GDI) { switch_gdi_data_track(sec, GDS); lba = ( (uint32)sec < IsoInfo->track_lba[0] ? 150 : IsoInfo->track_lba[(GDS->data_track == 3 ? 0 : 1)] ); } lseek(iso_fd, (sec - lba) * IsoInfo->sector_size, SEEK_SET); if(pre_read(iso_fd, num * IsoInfo->sector_size) < 0) { return FAILED; } return PROCESSING; } static int _read_sector_by_sector(uint8 *buff, uint cnt, uint sec_size #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) , int old_dma #endif ) { while(cnt-- > 0) { lseek(iso_fd, b_seek, SEEK_CUR); #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) if(!cnt && old_dma) { fs_enable_dma(old_dma); } #endif if(read(iso_fd, buff, sec_size) < 0) { return FAILED; } lseek(iso_fd, a_seek, SEEK_CUR); buff += sec_size; } return COMPLETED; } static int _read_data_sectors(uint8 *buff, uint sector, uint cnt, fs_callback_f *cb) { const uint sec_size = 2048; int tmps = sec_size * cnt; lseek(iso_fd, IsoInfo->track_offset + (sector * IsoInfo->sector_size), SEEK_SET); /* Reading normal data sectors (2048) */ if(IsoInfo->sector_size == sec_size) { if(cb != NULL) { #ifdef _FS_ASYNC if(read_async(iso_fd, buff, tmps, cb) < 0) { return FAILED; } return PROCESSING; #else return FAILED; #endif } else { if(read(iso_fd, buff, tmps) < 0) { return FAILED; } } return COMPLETED; } /* Reading not optimized GDI or CDI */ uint8 *tmpb; #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) int old_dma = fs_dma_enabled(); if(old_dma) { fs_enable_dma(FS_DMA_HIDDEN); } // if(mmu_enabled()) { // return _read_sector_by_sector(buff, cnt, sec_size, old_dma); // } #endif while(cnt > 2) { tmpb = buff; tmps = (tmps / IsoInfo->sector_size); if(read(iso_fd, tmpb, tmps * IsoInfo->sector_size) < 0) { return FAILED; } while(tmps--) { memmove(buff, tmpb + b_seek, sec_size); tmpb += IsoInfo->sector_size; buff += sec_size; cnt--; } tmps = sec_size * cnt; } #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) return _read_sector_by_sector(buff, cnt, sec_size, old_dma); #else return _read_sector_by_sector(buff, cnt, sec_size); #endif } #ifdef HAVE_LZO #define isCompressed(block) ((block & 0x80000000) == 0) #define getPosition(block) ((block & 0x7FFFFFFF) << IsoInfo->ciso.align) static struct { uint cnt; uint pkg; uint8 *p_buff; uint32 p_buff_size; uint8 *c_buff; uint32 c_buff_addr; uint32 c_buff_size; void *c_buff_alloc; uint *blocks; fs_callback_f *cb; } cst; static int _open_ciso() { DBGF("Magic: %c%c%c%c\n", IsoInfo->ciso.magic[0], IsoInfo->ciso.magic[1], IsoInfo->ciso.magic[2], IsoInfo->ciso.magic[3]); DBGF("Hdr size: %u\n", IsoInfo->ciso.header_size); DBGF("Total bytes: %u\n", IsoInfo->ciso.total_bytes); DBGF("Block size: %u\n", IsoInfo->ciso.block_size); DBGF("Version: %02x\n", IsoInfo->ciso.ver); DBGF("Align: %d\n", 1 << IsoInfo->ciso.align); if(IsoInfo->ciso.magic[0] == 'C') { ; } else if(IsoInfo->ciso.magic[0] == 'Z') { if(lzo_init() != LZO_E_OK) { LOGFF("lzo init failed\n"); return -1; } cst.c_buff_size = 0x4000; cst.c_buff_alloc = malloc(cst.c_buff_size); if (!cst.c_buff_alloc) { return -1; } } else { return -1; } return 0; } static inline uint _ciso_calc_read(uint *blocks, uint cnt, size_t size, size_t *rsize) { lseek(iso_fd, getPosition(blocks[0]), SEEK_SET); if(cnt <= 1) { *rsize = getPosition(blocks[cnt]) - getPosition(blocks[0]); return cnt; } uint i; for(i = 1; i < cnt + 1; i++) { size_t len = getPosition(blocks[i]) - getPosition(blocks[0]); if(len > size) { break; } else { *rsize = len; } } i--; LOGFF("%ld --> %ld %ld\n", cnt, i, *rsize); return i; } static inline size_t _ciso_dec_sector(uint *blocks, uint8 *src, uint8 *dst) { uint32 rv = 0; uint32 len = getPosition(blocks[1]) - getPosition(blocks[0]); if(isCompressed(blocks[0])) { #ifdef LOG_DEBUG DBGFF("%d %d\n", len, lzo1x_decompress(src, len, dst, &rv, NULL)); #else lzo1x_decompress(src, len, dst, &rv, NULL); #endif } else { DBGFF("%d copy\n", len); memcpy(dst, src, len); } return len; } static int ciso_read_init(uint8 *buff, uint sector, uint cnt, fs_callback_f *cb) { cst.p_buff = buff; cst.cb = cb; cst.cnt = cnt; cst.pkg = 0; cst.c_buff_addr = (uint32)cst.c_buff_alloc; cst.c_buff_size = 0x4000; cst.p_buff_size = cnt << 2; uint blocks_size = cnt * sizeof(uint); blocks_size = ((blocks_size / 32) + 1) * 32; cst.blocks = (uint *)(cst.c_buff_addr); cst.c_buff_size -= blocks_size; cst.c_buff_addr += blocks_size; cst.c_buff = (uint8 *)cst.c_buff_addr; LOGFF("[0x%08lx %ld %ld] [0x%08lx %ld %ld]\n", (uint32)buff, sector, cnt, cst.c_buff_addr, cst.c_buff_size, blocks_size); cnt++; lseek(iso_fd, sizeof(CISO_header_t) + (sector << 2), SEEK_SET); if(read(iso_fd, cst.blocks, cnt << 2) < 0) { return -1; } return 0; } static int _read_ciso_sectors(uint8 *buff, uint sector, uint cnt) { if(ciso_read_init(buff, sector, cnt, NULL) < 0) { return FAILED; } while(cst.cnt) { if(!cst.pkg) { uint len = 0; cst.c_buff = (uint8 *)cst.c_buff_addr; cst.pkg = _ciso_calc_read(cst.blocks, cst.cnt, cst.c_buff_size, &len); if(read(iso_fd, cst.c_buff, len) < 0) { return FAILED; } } cst.c_buff += _ciso_dec_sector(cst.blocks, cst.c_buff, cst.p_buff); cst.p_buff += IsoInfo->ciso.block_size; --cst.pkg; --cst.cnt; ++cst.blocks; } return COMPLETED; } #endif /* HAVE_LZO */ <file_sep>/firmware/aica/main.c /* DreamShell ##version## main.c Copyright (C) 2000-2002 <NAME> Copyright (C) 2009-2014 SWAT Generic sound driver with streaming capabilities This slightly more complicated version allows for sound effect channels, and full sampling rate, panning, and volume control for each. */ #include "drivers/aica_cmd_iface.h" #include "aica.h" #include "dec.h" /****************** Timer *******************************************/ #define timer (*((volatile uint32 *)AICA_MEM_CLOCK)) void timer_wait(int jiffies) { int fin = timer + jiffies; while (timer <= fin) ; } /****************** Tiny Libc ***************************************/ #include <stddef.h> void *memcpy(void *dest, const void *src, size_t count) { unsigned char *tmp = (unsigned char *) dest; unsigned char *s = (unsigned char *) src; while (count--) *tmp++ = *s++; return dest; } void *memset(void *dest, int c, size_t count) { unsigned char *tmp = (unsigned char *) dest; while (count--) *tmp++ = c; return dest; } void *memmove (void *dest0, void const *source0, size_t length) { char *dest = dest0; char const *source = source0; if (source < dest) /* Moving from low mem to hi mem; start at end. */ for (source += length, dest += length; length; --length) *--dest = *--source; else if (source != dest) { /* Moving from hi mem to low mem; start at beginning. */ for (; length; --length) *dest++ = *source++; } return dest0; } static void *memptr = (void*)AICA_RAM_START; void *malloc(size_t size) { void *ptr = memptr; memset(ptr, 0, size); memptr += size + 4; return ptr; } void free(void *p) { return; } /****************** Main Program ************************************/ /* Our SH-4 interface (statically placed memory structures) */ volatile aica_queue_t *q_cmd = (volatile aica_queue_t *)AICA_MEM_CMD_QUEUE; volatile aica_queue_t *q_resp = (volatile aica_queue_t *)AICA_MEM_RESP_QUEUE; volatile aica_channel_t *chans = (volatile aica_channel_t *)AICA_MEM_CHANNELS; /* Process a CHAN command */ void process_chn(uint32 chn, aica_channel_t *chndat) { switch(chndat->cmd & AICA_CH_CMD_MASK) { case AICA_CH_CMD_NONE: break; case AICA_CH_CMD_START: if (chndat->cmd & AICA_CH_START_SYNC) { aica_sync_play(chn); } else { memcpy((void*)(chans+chn), chndat, sizeof(aica_channel_t)); chans[chn].pos = 0; aica_play(chn, chndat->cmd & AICA_CH_START_DELAY); } break; case AICA_CH_CMD_STOP: aica_stop(chn); break; case AICA_CH_CMD_UPDATE: if (chndat->cmd & AICA_CH_UPDATE_SET_FREQ) { chans[chn].freq = chndat->freq; aica_freq(chn); } if (chndat->cmd & AICA_CH_UPDATE_SET_VOL) { chans[chn].vol = chndat->vol; aica_vol(chn); } if (chndat->cmd & AICA_CH_UPDATE_SET_PAN) { chans[chn].pan = chndat->pan; aica_pan(chn); } break; default: /* error */ break; } } void process_decoder(aica_decoder_t *dat) { switch(dat->cmd & AICA_DECODER_CMD_MASK) { case AICA_DECODER_CMD_NONE: break; case AICA_DECODER_CMD_INIT: memptr = (void*)dat->base; if(dat->codec & AICA_CODEC_MP3) { init_mp3(); } if(dat->codec & AICA_CODEC_AAC) { //init_aac(); } break; case AICA_DECODER_CMD_SHUTDOWN: if(dat->codec & AICA_CODEC_MP3) { shutdown_mp3(); } if(dat->codec & AICA_CODEC_AAC) { //shutdown_aac(); } break; case AICA_DECODER_CMD_DECODE: switch(dat->codec) { case AICA_CODEC_MP3: decode_mp3(dat); break; case AICA_CODEC_AAC: break; default: break; } break; default: /* error */ break; } } /* Process one packet of queue data */ uint32 process_one(uint32 tail) { uint32 pktdata[AICA_CMD_MAX_SIZE], *pdptr, size, i; volatile uint32 * src; aica_cmd_t * pkt; src = (volatile uint32 *)(q_cmd->data + tail); pkt = (aica_cmd_t *)pktdata; pdptr = pktdata; /* Get the size field */ size = *src; if (size > AICA_CMD_MAX_SIZE) size = AICA_CMD_MAX_SIZE; /* Copy out the packet data */ for (i=0; i<size; i++) { *pdptr++ = *src++; if ((uint32)src >= (q_cmd->data + q_cmd->size)) src = (volatile uint32 *)q_cmd->data; } /* Figure out what type of packet it is */ switch (pkt->cmd) { case AICA_CMD_NONE: break; case AICA_CMD_CPU_CLOCK: /* // 0x28a8 - ARMClock - GUESS +--------------+ | 31-8 | 7-0 | | n/a | mhz | +--------------+ mhz: sets the speed of the ARM7 CPU in MHz steps. 00 = 1 MHz, 24 = 25 MHz don't try to overclock the ARM7 it may get burned or something. */ SNDREG32(0x28a8) = pkt->cmd_id; //0x0019 break; case AICA_CMD_DECODER: process_decoder((aica_decoder_t *)pkt->cmd_data); break; case AICA_CMD_PING: /* Not implemented yet */ break; case AICA_CMD_CHAN: process_chn(pkt->cmd_id, (aica_channel_t *)pkt->cmd_data); break; case AICA_CMD_SYNC_CLOCK: /* Reset our timer clock to zero */ timer = 0; break; default: /* error */ break; } return size; } /* Look for an available request in the command queue; if one is there then process it and move the tail pointer. */ void process_cmd_queue() { uint32 head, tail, tsloc, ts; /* Grab these values up front in case SH-4 changes head */ head = q_cmd->head; tail = q_cmd->tail; /* Do we have anything to process? */ while (head != tail) { /* Look at the next packet. If our clock isn't there yet, then we won't process anything yet either. */ tsloc = tail + offsetof(aica_cmd_t, timestamp); if (tsloc >= q_cmd->size) tsloc -= q_cmd->size; ts = *((volatile uint32*)(q_cmd->data + tsloc)); if (ts > 0 && ts >= timer) return; /* Process it */ ts = process_one(tail); /* Ok, skip over the packet */ tail += ts * 4; if (tail >= q_cmd->size) tail -= q_cmd->size; q_cmd->tail = tail; } } int arm_main() { int i; /* Setup our queues */ q_cmd->head = q_cmd->tail = 0; q_cmd->data = AICA_MEM_CMD_QUEUE + sizeof(aica_queue_t); q_cmd->size = AICA_MEM_RESP_QUEUE - q_cmd->data; q_cmd->process_ok = 1; q_cmd->valid = 1; q_resp->head = q_resp->tail = 0; q_resp->data = AICA_MEM_RESP_QUEUE + sizeof(aica_queue_t); q_resp->size = AICA_MEM_CHANNELS - q_resp->data; q_resp->process_ok = 1; q_resp->valid = 1; /* Initialize the AICA part of the SPU */ aica_init(); /* Wait for a command */ for( ; ; ) { /* Update channel position counters */ for (i=0; i<64; i++) aica_get_pos(i); /* Check for a command */ if (q_cmd->process_ok) process_cmd_queue(); /* Little delay to prevent memory lock */ timer_wait(10); } } <file_sep>/modules/tolua++/module.c /* DreamShell ##version## module.c - tolua++ module Copyright (C)2009-2014 SWAT */ #include "ds.h" DEFAULT_MODULE_EXPORTS(tolua_2plus); <file_sep>/firmware/isoldr/loader/kos/dc/controller.h /* This file is part of the libdream Dreamcast function library. * Please see libdream.c for further details. * * (c)2000 <NAME> Thanks to <NAME> for information on the controller. Ported from KallistiOS (Dreamcast OS) for libdream by <NAME> */ #include <sys/cdefs.h> #include <arch/types.h> #ifndef __CONTROLLER_H #define __CONTROLLER_H /* Buttons bitfield defines */ #define CONT_C (1<<0) #define CONT_B (1<<1) #define CONT_A (1<<2) #define CONT_START (1<<3) #define CONT_DPAD_UP (1<<4) #define CONT_DPAD_DOWN (1<<5) #define CONT_DPAD_LEFT (1<<6) #define CONT_DPAD_RIGHT (1<<7) #define CONT_Z (1<<8) #define CONT_Y (1<<9) #define CONT_X (1<<10) #define CONT_D (1<<11) #define CONT_DPAD2_UP (1<<12) #define CONT_DPAD2_DOWN (1<<13) #define CONT_DPAD2_LEFT (1<<14) #define CONT_DPAD2_RIGHT (1<<15) /* controller condition structure */ typedef struct { uint16 buttons; /* buttons bitfield */ uint8 rtrig; /* right trigger */ uint8 ltrig; /* left trigger */ uint8 joyx; /* joystick X */ uint8 joyy; /* joystick Y */ uint8 joy2x; /* second joystick X */ uint8 joy2y; /* second joystick Y */ } cont_cond_t; int cont_get_cond(uint8 addr, cont_cond_t *cond); #endif <file_sep>/modules/ogg/module.c /* DreamShell ##version## module.c - oggvorbis module Copyright (C)2009-2014 SWAT */ #include "ds.h" #include <oggvorbis/sndoggvorbis.h> DEFAULT_MODULE_HEADER(oggvorbis); static int oggvorbis_inited = 0; static int builtin_oggvorbis(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: %s option args...\n\n" "Options: \n" " -p, --play -Start playing\n" " -s, --stop -Stop playing\n\n", argv[0]); ds_printf("Arguments: \n" " -l, --loop -Loop N times\n" " -i, --info -Show song info\n" " -v, --volume -Set volume\n" " -f, --file -File for playing\n\n" "Examples: %s --play --file /cd/file.ogg\n" " %s -s", argv[0], argv[0]); return CMD_NO_ARG; } int start = 0, stop = 0, loop = 0, volume = 0, info = 0; char *file = NULL; struct cfg_option options[] = { {"play", 'p', NULL, CFG_BOOL, (void *) &start, 0}, {"stop", 's', NULL, CFG_BOOL, (void *) &stop, 0}, {"info", 'i', NULL, CFG_BOOL, (void *) &info, 0}, {"loop", 'l', NULL, CFG_INT, (void *) &loop, 0}, {"volume", 'v', NULL, CFG_INT, (void *) &volume, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(!oggvorbis_inited) { //snd_stream_init(); sndoggvorbis_init(); oggvorbis_inited = 1; } if(volume) sndoggvorbis_volume(volume); if(start) { if(file == NULL) { ds_printf("DS_ERROR: Need file for playing\n"); return CMD_ERROR; } sndoggvorbis_stop(); if(sndoggvorbis_start(file, loop) < 0) { ds_printf("DS_ERROR: Can't play file: %s\n", file); return CMD_ERROR; } } if(stop) sndoggvorbis_stop(); if(info) { long bitrate = sndoggvorbis_getbitrate(); ds_printf(" Artist: %s\n", sndoggvorbis_getartist()); ds_printf(" Title: %s\n", sndoggvorbis_gettitle()); ds_printf(" Genre: %s\n", sndoggvorbis_getgenre()); ds_printf(" Bitrate: %ld\n", bitrate); } if(!start && !stop && !volume) { ds_printf("DS_ERROR: There is no option.\n"); return CMD_NO_ARG; } else { return CMD_OK; } } int lib_open(klibrary_t *lib) { AddCmd(lib_get_name(), "Oggvorbis player", (CmdHandler *) builtin_oggvorbis); return nmmgr_handler_add(&ds_oggvorbis_hnd.nmmgr); } int lib_close(klibrary_t *lib) { RemoveCmd(GetCmdByName(lib_get_name())); if(oggvorbis_inited) sndoggvorbis_shutdown(); return nmmgr_handler_remove(&ds_oggvorbis_hnd.nmmgr); } <file_sep>/modules/tolua/module.c /* DreamShell ##version## module.c - tolua module Copyright (C)2009-2014 SWAT */ #include "ds.h" DEFAULT_MODULE_EXPORTS(tolua); <file_sep>/applications/gd_ripper/modules/app_module.h /* DreamShell ##version## app_module.h - GD Ripper app module header Copyright (C)2014 megavolt85 */ #include "ds.h" void gd_ripper_toggleSavedevice(GUI_Widget *widget); void gd_ripper_Number_read(); void gd_ripper_Gamename(); void gd_ripper_Delname(GUI_Widget *widget); void gd_ripper_ipbin_name(); void gd_ripper_Init(App_t *app, const char* fileName); void gd_ripper_StartRip(); int gdfiles(char *dst_folder,char *dst_file,char *text); void gd_ripper_Exit(); <file_sep>/firmware/aica/aac.c #include <stddef.h> #include "drivers/aica_cmd_iface.h" #include "aica.h" #include "aacdec.h" static HAACDecoder *hAACDecoder; static AACFrameInfo aacFrameInfo; int init_aac() { if(!hAACDecoder) hAACDecoder = (HAACDecoder *)AACInitDecoder(); return 0; } void shutdown_aac() { AACFreeDecoder(hAACDecoder); } int decode_aac(aica_decoder_t *dat) { return 0; } <file_sep>/modules/ogg/liboggvorbis/liboggvorbisplay/Makefile # KallistiOS Ogg/Vorbis Decoder Library # # Library Makefile # (c)2001 <NAME> # Based on KOS Makefiles by <NAME> OBJS = sndoggvorbis.o main.o SUBDIRS = POSTDIRS = test BUILD_TARGET = build KOS_CFLAGS += -I. -I../liboggvorbis/libvorbis/include -I../liboggvorbis/libogg/include all: subdirs liboggvorbisplay.a libvorbisplay.a:$(OBJS) -cp $(OBJS) ./build/ # $(KOS_AR) rcs ./lib/libvorbisplay.a build/main.o build/sndoggvorbis.o liboggvorbisplay.a:$(OBJS) -cp $(OBJS) ./build/ -cp ../liboggvorbis/build/*.o ./build/ $(KOS_AR) rcs ./lib/liboggvorbisplay.a ./build/*.o clean: clean_subdirs -rm -f $(OBJS) *.bck -rm -f ./build/*.o -rm -f ./lib/*.a include ../../../../sdk/Makefile.library <file_sep>/sdk/bin/src/raw2wav/raw2wav.c /* Written by rofl0r. LICENSE: GPL v2 gcc -Wall -Wextra raw2wav.c -o raw2wav */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <sys/stat.h> #include "wave_format.h" size_t getfilesize(char *filename) { struct stat st; if(!stat(filename, &st)) { return st.st_size; } else return 0; } static WAVE_HEADER_COMPLETE wave_hdr = { { { 'R', 'I', 'F', 'F'}, 0, { 'W', 'A', 'V', 'E'}, }, { { 'f', 'm', 't', ' '}, 16, {1, 0}, 0, 44100, 0, 0, 16, }, { { 'd', 'a', 't', 'a' }, 0 }, }; #define MUSIC_BUF_SIZE 4096 #include <assert.h> int raw2wav(char *rawname, char* wavname, int channels, int hz, int bitrate) { FILE* fd, *outfd; int len, kb = 0; char *p, *artist, *title; unsigned int size = getfilesize(rawname); unsigned char in[MUSIC_BUF_SIZE]; unsigned char out[MUSIC_BUF_SIZE]; fd = fopen(rawname, "r"); outfd = fopen(wavname, "w"); assert(channels == 1 || channels == 2); assert(hz == 48000 || hz == 44100 || hz == 22050 || hz == 11025); assert(bitrate == 32 || bitrate == 24 || bitrate == 16 || bitrate == 8); wave_hdr.wave_hdr.channels = channels; wave_hdr.wave_hdr.samplerate = hz; wave_hdr.wave_hdr.bitwidth = bitrate; wave_hdr.wave_hdr.blockalign = channels * (wave_hdr.wave_hdr.bitwidth / 8); wave_hdr.wave_hdr.bytespersec = wave_hdr.wave_hdr.samplerate * channels * (wave_hdr.wave_hdr.bitwidth / 8); wave_hdr.riff_hdr.filesize_minus_8 = sizeof(WAVE_HEADER_COMPLETE) + (size * 4) - 8; wave_hdr.sub2.data_size = size * 4; fwrite(&wave_hdr, 1, sizeof(wave_hdr), outfd); while(size && (len = fread(in, 1, MUSIC_BUF_SIZE, fd))) { if(size < len) len = size; size -= len; fwrite(in, 1, len, outfd); } fclose(outfd); fclose(fd); return 0; } int syntax(void) { puts("raw2wav 1.0 by rofl0r\nsyntax: raw2wav rawfile wavfile channels(1/2) frequency(44100/22050/11025) bitrate(8/16)"); return 1; } int main(int argc, char** argv) { if(argc != 6) return syntax(); return !!raw2wav(argv[1], argv[2], atoi(argv[3]), atoi(argv[4]), atoi(argv[5])); } <file_sep>/lib/SDL_gui/FileManager.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" extern "C" { void SDL_DC_EmulateMouse(SDL_bool value); } GUI_FileManager::GUI_FileManager(const char *aname, const char *path, int x, int y, int w, int h) : GUI_Container(aname, x, y, w, h) { strncpy(cur_path, path != NULL ? path : "/", NAME_MAX); rescan = 1; item_area.w = w - 20; item_area.h = 20; item_area.x = 0; item_area.y = 0; item_normal = new GUI_Surface("normal", SDL_HWSURFACE, item_area.w, item_area.h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); item_highlight = new GUI_Surface("highlight", SDL_HWSURFACE, item_area.w, item_area.h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); item_disabled = new GUI_Surface("disabled", SDL_HWSURFACE, item_area.w, item_area.h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); item_pressed = new GUI_Surface("pressed", SDL_HWSURFACE, item_area.w, item_area.h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); item_normal->Fill(NULL, 0xFF000000); item_highlight->Fill(NULL, 0x00FFFFFF); item_pressed->Fill(NULL, 0x00FFFFFF); item_disabled->Fill(NULL, 0xFF000000); item_click = NULL; item_context_click = NULL; item_mouseover = NULL; item_mouseout = NULL; item_label_font = NULL; item_label_clr.r = 0; item_label_clr.g = 0; item_label_clr.b = 0; Build(); } GUI_FileManager::~GUI_FileManager() { item_normal->DecRef(); item_highlight->DecRef(); item_pressed->DecRef(); item_disabled->DecRef(); if(item_label_font) item_label_font->DecRef(); if(scrollbar) scrollbar->DecRef(); if(button_up) button_up->DecRef(); if(button_down) button_down->DecRef(); } void GUI_FileManager::Build() { panel = new GUI_Panel("panel", 0, 0, item_area.w, area.h); if(panel) { AddWidget(panel); panel->DecRef(); } GUI_EventHandler < GUI_FileManager > *cb; scrollbar = new GUI_ScrollBar("scrollbar", item_area.w, 20, 20, area.h - 40); if(scrollbar) { cb = new GUI_EventHandler < GUI_FileManager > (this, &GUI_FileManager::AdjustScrollbar); scrollbar->SetMovedCallback(cb); cb->DecRef(); AddWidget(scrollbar); } button_up = new GUI_Button("button_up", item_area.w, 0, 20, 20); if(button_up) { cb = new GUI_EventHandler < GUI_FileManager > (this, &GUI_FileManager::ScrollbarButtonEvent); button_up->SetClick(cb); cb->DecRef(); AddWidget(button_up); } button_down = new GUI_Button("button_down", item_area.w, area.h - 20, 20, 20); if(button_down) { cb = new GUI_EventHandler < GUI_FileManager > (this, &GUI_FileManager::ScrollbarButtonEvent); button_down->SetClick(cb); cb->DecRef(); AddWidget(button_down); } } void GUI_FileManager::Resize(int w, int h) { area.w = w; area.h = h; item_area.w = w - scrollbar->GetWidth(); if(panel) panel->SetSize(item_area.w, area.h); if(button_up) button_up->SetPosition(item_area.w, 0); if(button_down) button_down->SetPosition(item_area.w, area.h - button_down->GetHeight()); if(scrollbar) { scrollbar->SetPosition(item_area.w, button_up->GetHeight()); scrollbar->SetHeight(area.h - (button_up->GetHeight() + button_down->GetHeight())); } ReScan(); } void GUI_FileManager::AdjustScrollbar(GUI_Object * sender) { int cont_height = (panel->GetWidgetCount() * item_area.h) - panel->GetHeight(); if(cont_height <= 0) { return; } int scroll_pos = scrollbar->GetVerticalPosition(); int scroll_height = scrollbar->GetHeight() - scrollbar->GetKnobImage()->GetHeight(); panel->SetYOffset(scroll_pos * ((cont_height / scroll_height) + 1)); if (scroll_pos <= 0) { button_up->SetEnabled(0); } else { button_up->SetEnabled(1); } if (scroll_pos >= scroll_height) { button_down->SetEnabled(0); } else { button_down->SetEnabled(1); } } void GUI_FileManager::ScrollbarButtonEvent(GUI_Object * sender) { int scroll_pos, scroll_height, cont_height; cont_height = (panel->GetWidgetCount() * item_area.h) - panel->GetHeight(); if(cont_height <= 0) { return; } scroll_pos = scrollbar->GetVerticalPosition(); scroll_height = scrollbar->GetHeight() - scrollbar->GetKnobImage()->GetHeight(); if(sender == button_up) { scroll_pos -= scroll_height / panel->GetWidgetCount(); if(button_down->GetFlags() & WIDGET_DISABLED) { button_down->SetEnabled(1); } if(scroll_pos < 0) { scroll_pos = 0; button_up->SetEnabled(0); } } else if(sender == button_down) { scroll_pos += scroll_height / panel->GetWidgetCount(); if(button_up->GetFlags() & WIDGET_DISABLED) { button_up->SetEnabled(1); } if(scroll_pos > scroll_height) { scroll_pos = scroll_height; button_down->SetEnabled(0); } } scrollbar->SetVerticalPosition(scroll_pos); panel->SetYOffset(scroll_pos * ((cont_height / scroll_height) + 1)); } void GUI_FileManager::SetPath(const char *path) { strncpy(cur_path, path, NAME_MAX); ReScan(); } const char *GUI_FileManager::GetPath() { return (const char*)cur_path; } void GUI_FileManager::ChangeDir(const char *name, int size) { char *b, path[NAME_MAX]; int s; file_t fd; if(name/* && size < 0*/) { if(size == -2 && name[0] == '.' && name[1] == '.') { b = strrchr(cur_path, '/'); if(b) { s = b - cur_path; if(s > 0) cur_path[s] = '\0'; else cur_path[1] = '\0'; ReScan(); } } else { memset(path, 0, NAME_MAX); if(strlen(cur_path) > 1) { snprintf(path, NAME_MAX, "%s/%s", cur_path, name); } else { snprintf(path, NAME_MAX, "%s%s", cur_path, name); } s = strlen(cur_path) + strlen(name) + 1; path[s > NAME_MAX-1 ? NAME_MAX-1 : s] = '\0'; fd = fs_open(path, O_RDONLY | O_DIR); if(fd != FILEHND_INVALID) { fs_close(fd); strncpy(cur_path, path, NAME_MAX); ReScan(); } else { printf("GUI_FileManager: Can't open dir: %s\n", path); } } } } static int alpha_sort(dirent_t *a, dirent_t *b) { const char *s1 = a->name, *s2 = b->name; while (toupper(*s1) == toupper(*s2)) { if (*s1 == 0) return 0; s1++; s2++; } return toupper(*(unsigned const char *)s1) - toupper(*(unsigned const char *)(s2)); } void GUI_FileManager::Scan() { file_t f; dirent_t *ent; dirent_t *sorts = (dirent_t *) malloc(sizeof(dirent_t)); int n = 0; f = fs_open(cur_path, O_RDONLY | O_DIR); if(f == FILEHND_INVALID) { printf("GUI_FileManager: Can't open dir: %s\n", cur_path); free(sorts); return; } panel->RemoveAllWidgets(); panel->SetYOffset(0); if(strlen(cur_path) > 1) { AddItem("..", -2, 0, O_DIR); } while ((ent = fs_readdir(f)) != NULL) { if(ent->name[0] != '.' && strncasecmp(ent->name, "RECYCLER", NAME_MAX) && strncasecmp(ent->name, "$RECYCLE.BIN", NAME_MAX) && strncasecmp(ent->name, "System Volume Information", NAME_MAX) ) { if (n) { sorts = (dirent_t *) realloc((void *) sorts, (sizeof(dirent_t)*(n+1))); } memcpy(&sorts[n], ent, sizeof(dirent_t)); n++; } } qsort((void *) sorts, n, sizeof(dirent_t), (int (*)(const void*, const void*)) alpha_sort); for (int i = 0; i < n; i++) { if (sorts[i].attr) { AddItem(sorts[i].name, sorts[i].size, sorts[i].time, sorts[i].attr); } } for (int i = 0; i < n; i++) { if (!sorts[i].attr) { AddItem(sorts[i].name, sorts[i].size, sorts[i].time, sorts[i].attr); } } free(sorts); fs_close(f); rescan = 0; } void GUI_FileManager::ReScan() { rescan = 1; MarkChanged(); } void GUI_FileManager::AddItem(const char *name, int size, int time, int attr) { GUI_Button *bt; GUI_Callback *cb; // GUI_EventHandler < GUI_FileManager > *cb; GUI_Label *lb; dirent_fm_t *prm; int need_free = 1; int cnt = panel->GetWidgetCount(); bt = new GUI_Button(name, item_area.x, item_area.y + (cnt * item_area.h), item_area.w, item_area.h); bt->SetNormalImage(item_normal); bt->SetHighlightImage(item_highlight); bt->SetPressedImage(item_pressed); bt->SetDisabledImage(item_disabled); if(item_click || item_context_click || item_mouseover || item_mouseout) { prm = (dirent_fm_t *) malloc(sizeof(dirent_fm_t)); if(prm != NULL) { strncpy(prm->ent.name, name, NAME_MAX); prm->ent.size = size; prm->ent.time = time; prm->ent.attr = attr; prm->obj = this; prm->index = cnt; } if(item_click) { // cb = new GUI_EventHandler < GUI_FileManager > (this, &GUI_FileManager::ItemClickEvent, (GUI_CallbackFunction*)free, (void*)prm); cb = new GUI_Callback_C(item_click, (GUI_CallbackFunction*)free, (void*)prm); bt->SetClick(cb); cb->DecRef(); need_free = 0; } if(item_context_click) { if(need_free) { cb = new GUI_Callback_C(item_context_click, (GUI_CallbackFunction*)free, (void*)prm); need_free = 0; } else { cb = new GUI_Callback_C(item_context_click, NULL, (void*)prm); } bt->SetContextClick(cb); cb->DecRef(); } if(item_mouseover) { if(need_free) { cb = new GUI_Callback_C(item_mouseover, (GUI_CallbackFunction*)free, (void*)prm); need_free = 0; } else { cb = new GUI_Callback_C(item_mouseover, NULL, (void*)prm); } bt->SetMouseover(cb); cb->DecRef(); } if(item_mouseout) { cb = new GUI_Callback_C(item_mouseout, (need_free ? (GUI_CallbackFunction*)free : NULL), (void*)prm); bt->SetMouseout(cb); cb->DecRef(); } } if(item_label_font) { // SDL_Rect ts = item_label_font->GetTextSize(name); lb = new GUI_Label(name, 2, 0, item_area.w-4, item_area.h, item_label_font, name); lb->SetTextColor(item_label_clr.r, item_label_clr.g, item_label_clr.b); lb->SetAlign(WIDGET_HORIZ_LEFT | WIDGET_VERT_CENTER); bt->SetCaption(lb); lb->DecRef(); /* if(size > 0) { char inf[64]; sprintf(inf, "%d Kb", size / 1024); SDL_Rect ts2 = item_label_font->GetTextSize(inf); lb = new GUI_Label(inf, (item_area.w - (ts2.w + 10)), 0, 100, item_area.h, item_label_font, inf); lb->SetTextColor(item_label_clr.r, item_label_clr.g, item_label_clr.b); lb->SetAlign(WIDGET_HORIZ_RIGHT | WIDGET_VERT_CENTER); bt->SetCaption2(lb); lb->DecRef(); }*/ } panel->AddWidget(bt); bt->DecRef(); } GUI_Button *GUI_FileManager::GetItem(int index) { return (GUI_Button *)panel->GetWidget(index); } GUI_Panel *GUI_FileManager::GetItemPanel() { return panel; } void GUI_FileManager::SetItemLabel(GUI_Font *font, int r, int g, int b) { GUI_ObjectKeep((GUI_Object **) &item_label_font, font); item_label_clr.r = r; item_label_clr.g = g; item_label_clr.b = b; ReScan(); } void GUI_FileManager::SetItemSurfaces(GUI_Surface *normal, GUI_Surface *highlight, GUI_Surface *pressed, GUI_Surface *disabled) { if(normal) { item_area.w = normal->GetWidth(); item_area.h = normal->GetHeight(); } GUI_ObjectKeep((GUI_Object **) &item_normal, normal); GUI_ObjectKeep((GUI_Object **) &item_highlight, highlight); GUI_ObjectKeep((GUI_Object **) &item_pressed, pressed); GUI_ObjectKeep((GUI_Object **) &item_disabled, disabled); ReScan(); } void GUI_FileManager::SetItemSize(const SDL_Rect *item_r) { item_area.w = item_r->w; item_area.h = item_r->h; item_area.x = item_r->x; item_area.y = item_r->y; ReScan(); } void GUI_FileManager::SetItemClick(GUI_CallbackFunction *func) { item_click = func; ReScan(); } void GUI_FileManager::SetItemContextClick(GUI_CallbackFunction *func) { item_context_click = func; ReScan(); } void GUI_FileManager::SetItemMouseover(GUI_CallbackFunction *func) { item_mouseover = func; ReScan(); } void GUI_FileManager::SetItemMouseout(GUI_CallbackFunction *func) { item_mouseout = func; ReScan(); } void GUI_FileManager::SetScrollbar(GUI_Surface *knob, GUI_Surface *background) { if(knob) { scrollbar->SetKnobImage(knob); scrollbar->SetWidth(knob->GetWidth()); } if(background) { scrollbar->SetBackgroundImage(background); scrollbar->SetHeight(background->GetHeight()); } MarkChanged(); } void GUI_FileManager::SetScrollbarButtonUp(GUI_Surface *normal, GUI_Surface *highlight, GUI_Surface *pressed, GUI_Surface *disabled) { button_up->SetNormalImage(normal); button_up->SetHighlightImage(highlight); button_up->SetPressedImage(pressed); button_up->SetDisabledImage(disabled); MarkChanged(); } void GUI_FileManager::SetScrollbarButtonDown(GUI_Surface *normal, GUI_Surface *highlight, GUI_Surface *pressed, GUI_Surface *disabled) { button_down->SetNormalImage(normal); button_down->SetHighlightImage(highlight); button_down->SetPressedImage(pressed); button_down->SetDisabledImage(disabled); MarkChanged(); } void GUI_FileManager::RemoveScrollbar() { RemoveWidget(button_down); RemoveWidget(button_up); RemoveWidget(scrollbar); } void GUI_FileManager::RestoreScrollbar() { AddWidget(button_down); AddWidget(button_up); AddWidget(scrollbar); } void GUI_FileManager::Update(int force) { if (flags & WIDGET_DISABLED) return; int i; if (flags & WIDGET_CHANGED) { force = 1; flags &= ~WIDGET_CHANGED; } if (force) { SDL_Rect r = area; r.x = x_offset; r.y = y_offset; Erase(&r); } if(rescan) { panel->RemoveAllWidgets(); panel->SetYOffset(0); for (i = 0; i < n_widgets; i++) { widgets[i]->DoUpdate(force); } Scan(); } else { for (i = 0; i < n_widgets; i++) { widgets[i]->DoUpdate(force); } } } int GUI_FileManager::Event(const SDL_Event *event, int xoffset, int yoffset) { if (flags & WIDGET_DISABLED) return 0; int i; xoffset += area.x - x_offset; yoffset += area.y - y_offset; switch (event->type) { case SDL_JOYBUTTONDOWN: switch(event->jbutton.button) { case 5: // Y case 6: // X SetFlags(WIDGET_PRESSED); SDL_DC_EmulateMouse(SDL_FALSE); GUI_GetScreen()->SetJoySelectState(0); break; default: break; } break; case SDL_JOYBUTTONUP: switch(event->jbutton.button) { case 5: // Y case 6: // X ClearFlags(WIDGET_PRESSED); thd_sleep(150); SDL_DC_EmulateMouse(SDL_TRUE); GUI_GetScreen()->SetJoySelectState(1); MarkChanged(); break; default: break; } break; case SDL_JOYAXISMOTION: switch(event->jaxis.axis) { case 1: // Analog joystick if(flags & WIDGET_PRESSED) { int scroll_height = scrollbar->GetHeight() - scrollbar->GetKnobImage()->GetHeight(); int sp = (scroll_height / 2) + ((event->jaxis.value / (256 / 100)) * (scroll_height / 100)); if(sp > scroll_height) { sp = scroll_height; } if(sp < 0) { sp = 0; } if (abs(scrollbar->GetVerticalPosition() - sp) > 2) { scrollbar->SetVerticalPosition(sp); AdjustScrollbar(NULL); } } break; default: break; } break; case SDL_JOYHATMOTION: if(flags & WIDGET_PRESSED) { int scroll_height = scrollbar->GetHeight() - scrollbar->GetKnobImage()->GetHeight(); int sp = scrollbar->GetVerticalPosition(); int step = (scroll_height / panel->GetWidgetCount()) * 2; switch(event->jhat.value) { case 0x0E: // UP sp -= step; break; case 0x0B: // DOWN sp += step; break; case 0x07: // LEFT sp -= step * ((panel->GetHeight() / item_area.h) - 1); break; case 0x0D: // RIGHT sp += step * ((panel->GetHeight() / item_area.h) - 1); break; default: break; } if(sp > scroll_height) { sp = scroll_height; } if(sp < 0) { sp = 0; } scrollbar->SetVerticalPosition(sp); AdjustScrollbar(NULL); } default: break; } for (i = 0; i < n_widgets; i++) { if (widgets[i]->Event(event, xoffset, yoffset)) return 1; } return GUI_Drawable::Event(event, xoffset, yoffset); } extern "C" { GUI_Widget *GUI_FileManagerCreate(const char *name, const char *path, int x, int y, int w, int h) { return new GUI_FileManager(name, path, x, y, w, h); } void GUI_FileManagerResize(GUI_Widget *widget, int w, int h) { ((GUI_FileManager *) widget)->Resize(w, h); } void GUI_FileManagerSetPath(GUI_Widget *widget, const char *path) { ((GUI_FileManager *) widget)->SetPath(path); } const char *GUI_FileManagerGetPath(GUI_Widget *widget) { return ((GUI_FileManager *) widget)->GetPath(); } void GUI_FileManagerChangeDir(GUI_Widget *widget, const char *name, int size) { ((GUI_FileManager *) widget)->ChangeDir(name, size); } void GUI_FileManagerScan(GUI_Widget *widget) { ((GUI_FileManager *) widget)->ReScan(); } void GUI_FileManagerAddItem(GUI_Widget *widget, const char *name, int size, int time, int attr) { ((GUI_FileManager *) widget)->AddItem(name, size, time, attr); } GUI_Widget *GUI_FileManagerGetItem(GUI_Widget *widget, int index) { return (GUI_Widget *)((GUI_FileManager *) widget)->GetItem(index); } GUI_Widget *GUI_FileManagerGetItemPanel(GUI_Widget *widget) { return (GUI_Widget *)((GUI_FileManager *) widget)->GetItemPanel(); } void GUI_FileManagerSetItemSurfaces(GUI_Widget *widget, GUI_Surface *normal, GUI_Surface *highlight, GUI_Surface *pressed, GUI_Surface *disabled) { ((GUI_FileManager *) widget)->SetItemSurfaces(normal, highlight, pressed, disabled); } void GUI_FileManagerSetItemLabel(GUI_Widget *widget, GUI_Font *font, int r, int g, int b) { ((GUI_FileManager *) widget)->SetItemLabel(font, r, g, b); } void GUI_FileManagerSetItemSize(GUI_Widget *widget, const SDL_Rect *item_r) { ((GUI_FileManager *) widget)->SetItemSize(item_r); } void GUI_FileManagerSetItemClick(GUI_Widget *widget, GUI_CallbackFunction *func) { ((GUI_FileManager *) widget)->SetItemClick(func); } void GUI_FileManagerSetItemContextClick(GUI_Widget *widget, GUI_CallbackFunction *func) { ((GUI_FileManager *) widget)->SetItemContextClick(func); } void GUI_FileManagerSetItemMouseover(GUI_Widget *widget, GUI_CallbackFunction *func) { ((GUI_FileManager *) widget)->SetItemMouseover(func); } void GUI_FileManagerSetItemMouseout(GUI_Widget *widget, GUI_CallbackFunction *func) { ((GUI_FileManager *) widget)->SetItemMouseout(func); } void GUI_FileManagerSetScrollbar(GUI_Widget *widget, GUI_Surface *knob, GUI_Surface *background) { ((GUI_FileManager *) widget)->SetScrollbar(knob, background); } void GUI_FileManagerSetScrollbarButtonUp(GUI_Widget *widget, GUI_Surface *normal, GUI_Surface *highlight, GUI_Surface *pressed, GUI_Surface *disabled) { ((GUI_FileManager *) widget)->SetScrollbarButtonUp(normal, highlight, pressed, disabled); } void GUI_FileManagerSetScrollbarButtonDown(GUI_Widget *widget, GUI_Surface *normal, GUI_Surface *highlight, GUI_Surface *pressed, GUI_Surface *disabled) { ((GUI_FileManager *) widget)->SetScrollbarButtonDown(normal, highlight, pressed, disabled); } int GUI_FileManagerEvent(GUI_Widget *widget, const SDL_Event *event, int xoffset, int yoffset) { return ((GUI_FileManager *) widget)->Event(event, xoffset, yoffset); } void GUI_FileManagerUpdate(GUI_Widget *widget, int force) { ((GUI_FileManager *) widget)->Update(force); } void GUI_FileManagerRemoveScrollbar(GUI_Widget *widget) { ((GUI_FileManager *) widget)->RemoveScrollbar(); } void GUI_FileManagerRestoreScrollbar(GUI_Widget *widget) { ((GUI_FileManager *) widget)->RestoreScrollbar(); } } <file_sep>/modules/mp3/libmp3/xingmp3/mhead.h /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /* portable copy of eco\mhead.h */ /* mpeg audio header */ #include "L3.h" typedef struct { int sync; /* 1 if valid sync */ int id; int option; int prot; int br_index; int sr_index; int pad; int private_bit; int mode; int mode_ext; int cr; int original; int emphasis; } MPEG_HEAD; /* portable mpeg audio decoder, decoder functions */ typedef struct { int in_bytes; int out_bytes; } IN_OUT; typedef struct { int channels; int outvalues; long samprate; int bits; int framebytes; int type; } DEC_INFO; typedef IN_OUT(*AUDIO_DECODE_ROUTINE) (void *mv, unsigned char *bs, signed short *pcm); typedef IN_OUT(*DECODE_FUNCTION) (void *mv, unsigned char *bs, unsigned char *pcm); struct _mpeg; typedef struct _mpeg MPEG; typedef void (*SBT_FUNCTION_F) (MPEG *m, float *sample, short *pcm, int n); /* main data bit buffer */ #define NBUF (8*1024) #define BUF_TRIGGER (NBUF-1500) typedef void (*XFORM_FUNCTION) (void *mv, void *pcm, int igr); typedef struct { int enableEQ; float equalizer[32]; float EQ_gain_adjust; } eq_info; struct _mpeg { struct { float look_c_value[18]; /* built by init */ unsigned char *bs_ptr; unsigned long bitbuf; int bits; long bitval; int outbytes; int framebytes; int outvalues; int pad; int stereo_sb; DEC_INFO decinfo; /* global for Layer III */ int max_sb; int nsb_limit; int first_pass; int first_pass_L1; int bit_skip; int nbat[4]; int bat[4][16]; int ballo[64]; /* set by unpack_ba */ unsigned int samp_dispatch[66]; /* set by unpack_ba */ float c_value[64]; /* set by unpack_ba */ unsigned int sf_dispatch[66]; /* set by unpack_ba */ float sf_table[64]; float cs_factor[3][64]; float *sample; /* global for use by Later 3 */ signed char group3_table[32][3]; signed char group5_table[128][3]; signed short group9_table[1024][3]; SBT_FUNCTION_F sbt; AUDIO_DECODE_ROUTINE audio_decode_routine ; float *cs_factorL1; float look_c_valueL1[16]; int nbatL1; } cup; struct { /* cupl3.c */ int nBand[2][22]; /* [long/short][cb] */ int sfBandIndex[2][22]; /* [long/short][cb] */ int mpeg25_flag; int iframe; int band_limit; int band_limit21; int band_limit12; int band_limit_nsb; int nsb_limit; int gaim_adjust; int id; int ncbl_mixed; int gain_adjust; int sr_index; int outvalues; int outbytes; int half_outbytes; int framebytes; int padframebytes; int crcbytes; int pad; int stereo_flag; int nchan; int ms_mode; int is_mode; unsigned int zero_level_pcm; CB_INFO cb_info[2][2]; IS_SF_INFO is_sf_info; /* MPEG-2 intensity stereo */ unsigned char buf[NBUF]; int buf_ptr0; int buf_ptr1; int main_pos_bit; SIDE_INFO side_info; SCALEFACT sf[2][2]; /* [gr][ch] */ int nsamp[2][2]; /* must start = 0, for nsamp[igr_prev] */ float yout[576]; /* hybrid out, sbt in */ SAMPLE sample[2][2][576]; SBT_FUNCTION_F sbt_L3; XFORM_FUNCTION Xform; DECODE_FUNCTION decode_function; /* msis.c */ /*-- windows by block type --*/ float win[4][36]; float csa[8][2]; /* antialias */ float lr[2][8][2]; /* [ms_mode 0/1][sf][left/right] */ float lr2[2][2][64][2]; /* l3dq.c */ float look_global[256 + 2 + 4]; float look_scale[2][4][32]; #define ISMAX 32 float look_pow[2 * ISMAX]; float look_subblock[8]; float re_buf[192][3]; BITDAT bitdat; } cupl; struct { signed int vb_ptr; signed int vb2_ptr; float vbuf[512]; float vbuf2[512]; int first_pass; } csbt; struct { float coef32[31]; /* 32 pt dct coefs */ } cdct; // This needs to be last in this struct! eq_info eq; }; typedef int (*CVT_FUNCTION_8) (void *mv, unsigned char *pcm); typedef struct { struct { unsigned char look_u[8192]; short pcm[2304]; int ncnt; int ncnt1; int nlast; int ndeci; int kdeci; int first_pass; short xsave; CVT_FUNCTION_8 convert_routine; } dec; MPEG cupper; } MPEG8; #include "itype.h" typedef void (*SBT_FUNCTION) (SAMPLEINT * sample, short *pcm, int n); typedef void (*UNPACK_FUNCTION) (); typedef struct { struct { DEC_INFO decinfo; int pad; int look_c_value[18]; /* built by init */ int look_c_shift[18]; /* built by init */ int outbytes; int framebytes; int outvalues; int max_sb; int stereo_sb; int nsb_limit; int bit_skip; int nbat[4]; int bat[4][16]; int ballo[64]; /* set by unpack_ba */ unsigned int samp_dispatch[66]; /* set by unpack_ba */ int c_value[64]; /* set by unpack_ba */ int c_shift[64]; /* set by unpack_ba */ unsigned int sf_dispatch[66]; /* set by unpack_ba */ int sf_table[64]; INT32 cs_factor[3][64]; SAMPLEINT sample[2304]; signed char group3_table[32][3]; signed char group5_table[128][3]; signed short group9_table[1024][3]; int nsbt; SBT_FUNCTION sbt; UNPACK_FUNCTION unpack_routine; unsigned char *bs_ptr; UINT32 bitbuf; int bits; INT32 bitval; int first_pass; int first_pass_L1; int nbatL1; INT32 *cs_factorL1; int look_c_valueL1[16]; /* built by init */ int look_c_shiftL1[16]; /* built by init */ } iup; } MPEGI; #ifdef __cplusplus extern "C" { #endif void mpeg_init(MPEG *m); void mpeg_eq_init(MPEG *m); int head_info(unsigned char *buf, unsigned int n, MPEG_HEAD * h); int head_info2(unsigned char *buf, unsigned int n, MPEG_HEAD * h, int *br); int head_info3(unsigned char *buf, unsigned int n, MPEG_HEAD *h, int*br, unsigned int *searchForward); /* head_info returns framebytes > 0 for success */ /* audio_decode_init returns 1 for success, 0 for fail */ /* audio_decode returns in_bytes = 0 on sync loss */ int audio_decode_init(MPEG *m, MPEG_HEAD * h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); void audio_decode_info(MPEG *m, DEC_INFO * info); IN_OUT audio_decode(MPEG *m, unsigned char *bs, short *pcm); void mpeg8_init(MPEG8 *m); int audio_decode8_init(MPEG8 *m, MPEG_HEAD * h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); void audio_decode8_info(MPEG8 *m, DEC_INFO * info); IN_OUT audio_decode8(MPEG8 *m, unsigned char *bs, short *pcmbuf); /*-- integer decode --*/ void i_mpeg_init(MPEGI *m); int i_audio_decode_init(MPEGI *m, MPEG_HEAD * h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); void i_audio_decode_info(MPEGI *m, DEC_INFO * info); IN_OUT i_audio_decode(MPEGI *m, unsigned char *bs, short *pcm); #ifdef __cplusplus } #endif <file_sep>/firmware/isoldr/loader/include/exception-lowlevel.h /** * DreamShell ISO Loader * Low-level of exception handling * (c)2014-2020 SWAT <http://www.dc-swat.ru> * Based on Netplay VOOT code by <NAME> <<EMAIL>> */ #ifndef __EXCEPTION_LOWLEVEL_H__ #define __EXCEPTION_LOWLEVEL_H__ #include <arch/types.h> #include <arch/irq.h> #define REGISTER(x) (volatile x *) /* Exception/Interrupt registers */ #define REG_EXPEVT (REGISTER(vuint32) (0xff000024)) #define REG_INTEVT (REGISTER(vuint32) (0xff000028)) #define REG_TRA (REGISTER(vuint32) (0xff000020)) /* Exception types from the lowlevel handler. */ #define EXP_TYPE_GEN 1 #define EXP_TYPE_CACHE 2 #define EXP_TYPE_INT 3 #define EXP_TYPE_ALL 255 /* SH4 exception codes */ #define EXP_CODE_INT9 0x320 #define EXP_CODE_INT11 0x360 #define EXP_CODE_INT13 0x3A0 #define EXC_CODE_TMU0 0x400 #define EXC_CODE_TMU1 0x420 #define EXC_CODE_TMU2 0x440 #define EXP_CODE_TRAP 0x160 #define EXP_CODE_UBC 0x1E0 #define EXP_CODE_RXI 0x720 #define EXP_CODE_ALL 0xFFE #define EXP_CODE_BAD 0xFFF /* VBR vectors */ #define VBR_GEN(tab) ((void *) ((unsigned int) tab) + 0x100) #define VBR_CACHE(tab) ((void *) ((unsigned int) tab) + 0x400) #define VBR_INT(tab) ((void *) ((unsigned int) tab) + 0x600) /* CPU context */ typedef struct { uint32 pr; uint32 mach; uint32 macl; uint32 spc; uint32 ssr; uint32 vbr; uint32 gbr; uint32 sr; uint32 dbr; uint32 r7_bank; uint32 r6_bank; uint32 r5_bank; uint32 r4_bank; uint32 r3_bank; uint32 r2_bank; uint32 r1_bank; uint32 r0_bank; #if 0//defined(__SH_FPU_ANY__) // FPU not used by ISO Loader for now float fr0_b; float fr1_b; float fr2_b; float fr3_b; float fr4_b; float fr5_b; float fr6_b; float fr7_b; float fr8_b; float fr9_b; float fr10_b; float fr11_b; float fr12_b; float fr13_b; float fr14_b; float fr15_b; float fr0_a; float fr1_a; float fr2_a; float fr3_a; float fr4_a; float fr5_a; float fr6_a; float fr7_a; float fr8_a; float fr9_a; float fr10_a; float fr11_a; float fr12_a; float fr13_a; float fr14_a; float fr15_a; uint32 fpscr; uint32 fpul; #endif uint32 r14; uint32 r13; uint32 r12; uint32 r11; uint32 r10; uint32 r9; uint32 r8; uint32 r7; uint32 r6; uint32 r5; uint32 r4; uint32 r3; uint32 r2; uint32 r1; uint32 exception_type; uint32 r0; } register_stack; /* System regs control */ extern void *dbr(void); extern void dbr_set(const void *set); extern void *sgr(void); extern void *r15(void); extern void *vbr(void); /* External definitions and buffers */ extern uint8 general_sub_handler[]; extern uint8 general_sub_handler_base[]; extern uint8 general_sub_handler_end[]; //extern uint8 cache_sub_handler[]; //extern uint8 cache_sub_handler_base[]; //extern uint8 cache_sub_handler_end[]; extern uint8 interrupt_sub_handler[]; extern uint8 interrupt_sub_handler_base[]; extern uint8 interrupt_sub_handler_end[]; extern void ubc_handler_lowlevel(void); extern void my_exception_finish(void); #endif <file_sep>/firmware/isoldr/loader/include/cdda.h /** * DreamShell ISO Loader * CDDA audio playback * (c)2014-2023 SWAT <http://www.dc-swat.ru> */ #ifndef _CDDA_H #define _CDDA_H #include <arch/types.h> typedef enum CDDA_status { CDDA_STAT_IDLE = 0, CDDA_STAT_FILL, CDDA_STAT_PREP, CDDA_STAT_POS, CDDA_STAT_SNDL, CDDA_STAT_SNDR, CDDA_STAT_WAIT, CDDA_STAT_END } CDDA_status_t; typedef enum PCM_buff { PCM_TMP_BUFF = 0, PCM_DMA_BUFF = 1 } PCM_buff_t; typedef struct cdda_ctx { char *filename; /* Track file name */ size_t fn_len; /* Track file name length */ file_t fd; /* Track file FD */ uint32 offset; /* Track file offset */ uint32 cur_offset; /* Track current offset */ uint32 track_size; /* Track size */ uint32 lba; /* Track LBA */ uint8 *alloc_buff; /* Dynamic PCM buffer from malloc */ uint8 *buff[2]; /* PCM buffer in main RAM */ uint32 aica_left[2]; /* First/second buffer for channel in sound RAM */ uint32 aica_right[2]; /* First/second buffer for channel in sound RAM */ uint32 cur_buff; /* AICA channel buffer */ size_t size; /* Full buffer size */ uint32 dma; /* Use DMA for transfer to AICA memory */ /* Format info */ uint16 wav_format; uint16 aica_format; uint16 chn; uint16 bitsize; uint32 freq; /* End pos for channel */ uint32 end_pos; uint32 end_tm; /* Check status value for normalize playback */ uint32 check_status; uint32 check_freq; uint32 restore_count; /* AICA channels index */ uint32 right_channel; uint32 left_channel; /* Mutex for G2 bus */ uint32 g2_lock; /* SH4 timer for checking playback position */ uint32 timer; /* Exception code for AICA DMA IRQ */ uint32 irq_code; /* Volume for both channels */ uint32 volume; /* CDDA status (internal) */ uint32 stat; /* CDDA syscall request data */ uint32 loop; uint32 first_track; uint32 last_track; uint32 first_lba; uint32 last_lba; } cdda_ctx_t; /* PCM stereo splitters, optimized for SH4 */ void pcm16_split(int16 *all, int16 *left, int16 *right, uint32 size); void pcm8_split(uint8 *all, uint8 *left, uint8 *right, uint32 size); void adpcm_split(uint8 *all, uint8 *left, uint8 *right, uint32 size); int lock_cdda(void); void unlock_cdda(void); cdda_ctx_t *get_CDDA(void); int CDDA_Init(void); void CDDA_MainLoop(void); int CDDA_Play(uint32 first, uint32 last, uint32 loop); int CDDA_Play2(uint32 first, uint32 last, uint32 loop); int CDDA_Pause(void); int CDDA_Release(); int CDDA_Stop(void); int CDDA_Seek(uint32 offset); void CDDA_Test(); #endif /* _CDDA_H */ <file_sep>/modules/mp3/libmp3/libmp3/sndmp3_mpglib.c /* Tryptonite sndmp3.c (c)2000 <NAME> An MP3 player using sndstream and MPGLIB DOES NOT CURRENTLY WORK. Updated 2011 by SWAT This is work =) */ /* This library is designed to be called from another program in a thread. It expects an input filename, and it will do all the setup and playback work. This requires a working math library for m4-single-only (such as newlib). */ #include <kos.h> #include <mp3/sndserver.h> #include <mp3/sndmp3.h> /************************************************************************/ //#include "mpg123.h" /* From mpglib */ //#include "mpglib.h" #include "mpglib_config.h" #include "mpg123.h" #include "interface.h" #include "decode_i386.h" /* Bitstream buffer: this is for input data */ #define BS_SIZE (64*1024) #define BS_WATER (16*1024) /* 8 sectors */ static uint8 *bs_buffer = NULL, *bs_ptr; static int bs_count; /* PCM buffer: for storing data going out to the SPU */ #define PCM_WATER 65536 /* Amt to send to the SPU */ #define PCM_SIZE (PCM_WATER+16384) /* Total buffer size */ static char *pcm_buffer = NULL, *pcm_ptr; static int pcm_count, pcm_discard; /* MPEG file */ static uint32 mp3_fd; //static struct mpstr mp; static struct mpstr_tag mp; static int frame_bytes; /* Name of last played MP3 file */ static char mp3_last_fn[256]; static snd_stream_hnd_t stream_hnd = -1; /* Checks to make sure we have some data available in the bitstream buffer; if there's less than a certain "water level", shift the data back and bring in some more. */ #if 0 static int bs_fill() { int n; /* Make sure we don't underflow */ if (bs_count < 0) bs_count = 0; /* Pull in some more data if we need it */ if (bs_count < BS_WATER) { /* Shift everything back */ memcpy(bs_buffer, bs_ptr, bs_count); /* Read in some more data */ // printf("fs_read(%d,%x,%d)\r\n", mp3_fd, bs_buffer+bs_count, BS_SIZE - bs_count); n = fs_read(mp3_fd, bs_buffer+bs_count, BS_SIZE - bs_count); // printf("==%d\r\n", n); if (n <= 0) return -1; /* Shift pointers back */ bs_count += n; bs_ptr = bs_buffer; } return 0; } #else static int bs_fill() { int n; /* Read in some more data */ n = fs_read(mp3_fd, bs_buffer, BS_SIZE); if (n <= 0) return -1; return 0; } #endif /* Empties out the last (now-used) frame of data from the PCM buffer */ static int pcm_empty(int size) { if (pcm_count >= size) { /* Shift everything back */ memcpy(pcm_buffer, pcm_buffer + size, pcm_count - size); /* Shift pointers back */ pcm_count -= size; pcm_ptr = pcm_buffer + pcm_count; } return 0; } static void* mpglib_callback(snd_stream_hnd_t hnd, int size, int * actual) { //static int frames = 0; int ret, rsize; /* Check for file not started or file finished */ if (mp3_fd == 0) return NULL; /* Dump the last PCM packet */ pcm_empty(pcm_discard); /* Loop decoding until we have a full buffer */ while (pcm_count < size) { //printf("decoding previously loaded frame into %08x, %d bytes possible\n", pcm_ptr, PCM_WATER - pcm_count); ret = decodeMP3(&mp, NULL, 0, pcm_ptr, PCM_WATER - pcm_count, &rsize); //ret = decodeMP3_clipchoice(&mp, NULL, 0, pcm_ptr, &rsize, synth_1to1_mono, synth_1to1); //printf("ret was %s, size is %d\n", ret == MP3_OK ? "OK" : "ERROR", rsize); if (ret != MP3_OK) { //printf("Refilling the buffer\n"); // Pull in some more data (and check for EOF) if (bs_fill() < 0) { printf("Decode completed\r\n"); goto errorout; } //printf("trying decode again...\n"); ret = decodeMP3(&mp, bs_buffer, BS_SIZE, pcm_ptr, PCM_WATER - pcm_count, &rsize); //ret = decodeMP3_clipchoice(&mp, bs_ptr, BS_SIZE, pcm_ptr, &size, synth_1to1_mono, synth_1to1); //printf("ret was %s, size is %d\n", ret == MP3_OK ? "OK" : "ERROR", rsize); //bs_ptr += (8*1024); bs_count -= (8*1024); } pcm_ptr += rsize; pcm_count += rsize; //frames++; /*if (!(frames % 64)) { printf("Decoded %d frames \r", frames); }*/ } pcm_discard = *actual = size; /* Got it successfully */ return pcm_buffer; errorout: fs_close(mp3_fd); mp3_fd = 0; return NULL; } /* Open an MPEG stream and prepare for decode */ static int mpglib_init(const char *fn) { uint32 fd; int size; /* Open the file */ mp3_fd = fd = fs_open(fn, O_RDONLY); if (fd < 0) { printf("Can't open input file %s\r\n", fn); printf("getwd() returns '%s'\r\n", fs_getwd()); return -1; } if (fn != mp3_last_fn) { if (fn[0] != '/') { strcpy(mp3_last_fn, fs_getwd()); strcat(mp3_last_fn, "/"); strcat(mp3_last_fn, fn); } else { strcpy(mp3_last_fn, fn); } } /* Allocate buffers */ if (bs_buffer == NULL) bs_buffer = malloc(BS_SIZE); bs_ptr = bs_buffer; bs_count = 0; if (pcm_buffer == NULL) pcm_buffer = malloc(PCM_SIZE); pcm_ptr = pcm_buffer; pcm_count = pcm_discard = 0; /* Fill bitstream buffer */ if (bs_fill() < 0) { printf("Can't read file header\r\n"); goto errorout; } /* Are we looking at a RIFF file? (stupid Windows encoders) */ if (bs_ptr[0] == 'R' && bs_ptr[1] == 'I' && bs_ptr[2] == 'F' && bs_ptr[3] == 'F') { /* Found a RIFF header, scan through it until we find the data section */ printf("Skipping stupid RIFF header\r\n"); while (bs_ptr[0] != 'd' || bs_ptr[1] != 'a' || bs_ptr[2] != 't' || bs_ptr[3] != 'a') { bs_ptr++; if (bs_ptr >= (bs_buffer + BS_SIZE)) { printf("Indeterminately long RIFF header\r\n"); goto errorout; } } /* Skip 'data' and length */ bs_ptr += 8; bs_count -= (bs_ptr - bs_buffer); printf("Final index is %d\r\n", (bs_ptr - bs_buffer)); } if (((uint8)bs_ptr[0] != 0xff) && (!((uint8)bs_ptr[1] & 0xe0))) { printf("Definitely not an MPEG file\r\n"); goto errorout; } /* Initialize MPEG engines */ InitMP3(&mp); /* Decode the first frame */ printf("decoding first frame:\n"); decodeMP3(&mp, bs_buffer, BS_SIZE, pcm_ptr, PCM_WATER - pcm_count, &size); printf("decoded size was %d\n", size); pcm_ptr += size; pcm_count += size; printf("mpglib initialized successfully\r\n"); return 0; errorout: printf("Exiting on error\r\n"); if (bs_buffer) { free(bs_buffer); bs_buffer = NULL; } if (pcm_buffer) { free(pcm_buffer); pcm_buffer = NULL; } fs_close(fd); mp3_fd = 0; return -1; } static void mpglib_shutdown() { if (bs_buffer) { free(bs_buffer); bs_buffer = NULL; } if (pcm_buffer) { free(pcm_buffer); pcm_buffer = NULL; } if (mp3_fd) { fs_close(mp3_fd); mp3_fd = 0; } } /************************************************************************/ #include <dc/sound/stream.h> /* Status flag */ #define STATUS_INIT 0 #define STATUS_READY 1 #define STATUS_STARTING 2 #define STATUS_PLAYING 3 #define STATUS_STOPPING 4 #define STATUS_QUIT 5 #define STATUS_ZOMBIE 6 #define STATUS_REINIT 7 static volatile int sndmp3_status; /* Wait until the MP3 thread is started and ready */ void sndmp3_wait_start() { while (sndmp3_status != STATUS_READY) ; } /* Semaphore to halt sndmp3 until a command comes in */ static semaphore_t *sndmp3_halt_sem; /* Loop flag */ static volatile int sndmp3_loop; /* Call this function as a thread to handle playback. Playback will stop and this thread will return when you call sndmp3_shutdown(). */ static void sndmp3_thread() { int sj; stream_hnd = snd_stream_alloc(NULL, SND_STREAM_BUFFER_MAX); //assert( stream_hnd != -1 ); /* Main command loop */ while(sndmp3_status != STATUS_QUIT) { switch(sndmp3_status) { case STATUS_INIT: sndmp3_status = STATUS_READY; break; case STATUS_READY: printf("sndserver: waiting on semaphore\r\n"); sem_wait(sndmp3_halt_sem); printf("sndserver: released from semaphore\r\n"); break; case STATUS_STARTING: /* Initialize streaming driver */ if (snd_stream_reinit(stream_hnd, mpglib_callback) < 0) { sndmp3_status = STATUS_READY; } else { //snd_stream_start(stream_hnd, decinfo.samprate, decinfo.channels - 1); //snd_stream_start(stream_hnd, 44100, 1); snd_stream_start(stream_hnd, freqs[mp.fr.sampling_frequency], mp.fr.stereo); sndmp3_status = STATUS_PLAYING; } break; case STATUS_REINIT: /* Re-initialize streaming driver */ snd_stream_reinit(stream_hnd, NULL); sndmp3_status = STATUS_READY; break; case STATUS_PLAYING: { sj = jiffies; if (snd_stream_poll(stream_hnd) < 0) { if (sndmp3_loop) { printf("sndserver: restarting '%s'\r\n", mp3_last_fn); if (mpglib_init(mp3_last_fn) < 0) { sndmp3_status = STATUS_STOPPING; mp3_last_fn[0] = 0; } } else { printf("sndserver: not restarting\r\n"); snd_stream_stop(stream_hnd); sndmp3_status = STATUS_READY; mp3_last_fn[0] = 0; } // stream_start(); } else thd_sleep(50); break; } case STATUS_STOPPING: snd_stream_stop(stream_hnd); sndmp3_status = STATUS_READY; break; } } /* Done: clean up */ mpglib_shutdown(); snd_stream_stop(stream_hnd); snd_stream_destroy(stream_hnd); sndmp3_status = STATUS_ZOMBIE; } /* Start playback (implies song load) */ int sndmp3_start(const char *fn, int loop) { /* Can't start again if already playing */ if (sndmp3_status == STATUS_PLAYING) return -1; /* Initialize MP3 engine */ if (fn) { if (mpglib_init(fn) < 0) return -1; /* Set looping status */ sndmp3_loop = loop; } /* Wait for player thread to be ready */ while (sndmp3_status != STATUS_READY) thd_pass(); /* Tell it to start */ if (fn) sndmp3_status = STATUS_STARTING; else sndmp3_status = STATUS_REINIT; sem_signal(sndmp3_halt_sem); return 0; } /* Stop playback (implies song unload) */ void sndmp3_stop() { if (sndmp3_status == STATUS_READY) return; sndmp3_status = STATUS_STOPPING; while (sndmp3_status != STATUS_READY) thd_pass(); mpglib_shutdown(); mp3_last_fn[0] = 0; } /* Shutdown the player */ void sndmp3_shutdown() { sndmp3_status = STATUS_QUIT; sem_signal(sndmp3_halt_sem); while (sndmp3_status != STATUS_ZOMBIE) thd_pass(); spu_disable(); } /* Adjust the MP3 volume */ void sndmp3_volume(int vol) { snd_stream_volume(stream_hnd, vol); } /* The main loop for the sound server */ void sndmp3_mainloop() { /* Allocate a semaphore for temporarily halting sndmp3 */ sndmp3_halt_sem = sem_create(0); /* Setup an ABI for other programs */ /* sndmp3_svc_init(); */ /* Initialize sound program for apps that don't need music */ // snd_stream_init(NULL); /* Go into the main thread wait loop */ sndmp3_status=STATUS_INIT; sndmp3_thread(); /* Free the semaphore */ sem_destroy(sndmp3_halt_sem); /* Thread exited, so we were requested to quit */ /* svcmpx->remove_handler("sndsrv"); */ } <file_sep>/modules/mp3/libmp3/xingmp3/iupini.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /*========================================================= initialization for iup.c - include to iup.c mpeg audio decoder portable "c" integer mods 11/15/95 for Layer I mods 1/8/97 warnings =========================================================*/ #include <limits.h> /* Read only */ static long steps[18] = { 0, 3, 5, 7, 9, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535}; /* Read only */ static int stepbits[18] = { 0, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; /* ABCD_INDEX = lookqt[mode][sr_index][br_index] */ /* -1 = invalid */ /* Read only */ static signed char lookqt[4][3][16] = { {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks stereo */ {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks joint stereo */ {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks dual chan */ {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ {{1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}, /* 44ks single chan */ {0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1}, /* 48ks */ {1, 3, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}}, /* 32ks */ }; /* Read only */ static long sr_table[8] = {22050L, 24000L, 16000L, 1L, 44100L, 48000L, 32000L, 1L}; /* bit allocation table look up */ /* table per mpeg spec tables 3b2a/b/c/d /e is mpeg2 */ /* look_bat[abcd_index][4][16] */ /* Read only */ static unsigned char look_bat[5][4][16] = { /* LOOK_BATA */ {{0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17}, {0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* LOOK_BATB */ {{0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17}, {0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* LOOK_BATC */ {{0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* LOOK_BATD */ {{0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* LOOK_BATE */ {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, }; /* look_nbat[abcd_index]][4] */ /* Read only */ static unsigned char look_nbat[5][4] = { {3, 8, 12, 4}, {3, 8, 12, 7}, {2, 0, 6, 0}, {2, 0, 10, 0}, {4, 0, 7, 19}, }; void i_sbt_mono(SAMPLEINT * sample, short *pcm, int n); void i_sbt_dual(SAMPLEINT * sample, short *pcm, int n); void i_sbt_dual_mono(SAMPLEINT * sample, short *pcm, int n); void i_sbt_dual_left(SAMPLEINT * sample, short *pcm, int n); void i_sbt_dual_right(SAMPLEINT * sample, short *pcm, int n); void i_sbt16_mono(SAMPLEINT * sample, short *pcm, int n); void i_sbt16_dual(SAMPLEINT * sample, short *pcm, int n); void i_sbt16_dual_mono(SAMPLEINT * sample, short *pcm, int n); void i_sbt16_dual_left(SAMPLEINT * sample, short *pcm, int n); void i_sbt16_dual_right(SAMPLEINT * sample, short *pcm, int n); void i_sbt8_mono(SAMPLEINT * sample, short *pcm, int n); void i_sbt8_dual(SAMPLEINT * sample, short *pcm, int n); void i_sbt8_dual_mono(SAMPLEINT * sample, short *pcm, int n); void i_sbt8_dual_left(SAMPLEINT * sample, short *pcm, int n); void i_sbt8_dual_right(SAMPLEINT * sample, short *pcm, int n); /*--- 8 bit output ---*/ void i_sbtB_mono(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB_dual(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB_dual_mono(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB_dual_left(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB_dual_right(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB16_mono(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB16_dual(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB16_dual_mono(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB16_dual_left(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB16_dual_right(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB8_mono(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB8_dual(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB8_dual_mono(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB8_dual_left(SAMPLEINT * sample, unsigned char *pcm, int n); void i_sbtB8_dual_right(SAMPLEINT * sample, unsigned char *pcm, int n); /* Read Only */ static SBT_FUNCTION sbt_table[2][3][5] = { {{i_sbt_mono, i_sbt_dual, i_sbt_dual_mono, i_sbt_dual_left, i_sbt_dual_right}, {i_sbt16_mono, i_sbt16_dual, i_sbt16_dual_mono, i_sbt16_dual_left, i_sbt16_dual_right}, {i_sbt8_mono, i_sbt8_dual, i_sbt8_dual_mono, i_sbt8_dual_left, i_sbt8_dual_right}}, {{(SBT_FUNCTION) i_sbtB_mono, (SBT_FUNCTION) i_sbtB_dual, (SBT_FUNCTION) i_sbtB_dual_mono, (SBT_FUNCTION) i_sbtB_dual_left, (SBT_FUNCTION) i_sbtB_dual_right}, {(SBT_FUNCTION) i_sbtB16_mono, (SBT_FUNCTION) i_sbtB16_dual, (SBT_FUNCTION) i_sbtB16_dual_mono, (SBT_FUNCTION) i_sbtB16_dual_left, (SBT_FUNCTION) i_sbtB16_dual_right}, {(SBT_FUNCTION) i_sbtB8_mono, (SBT_FUNCTION) i_sbtB8_dual, (SBT_FUNCTION) i_sbtB8_dual_mono, (SBT_FUNCTION) i_sbtB8_dual_left, (SBT_FUNCTION) i_sbtB8_dual_right}}, }; /* Read Only */ static int out_chans[5] = {1, 2, 1, 1, 1}; /*---------------------------------------------------------*/ #ifdef _MSC_VER #pragma warning(disable: 4056) #endif void i_mpeg_init(MPEGI *m) { memset(&m->iup, 0, sizeof(m->iup)); m->iup.nsb_limit = 6; m->iup.nbat[0] = 3; m->iup.nbat[1] = 8; m->iup.nbat[3] = 12; m->iup.nbat[4] = 7; m->iup.nsbt = 36; m->iup.sbt = i_sbt_mono; m->iup.unpack_routine = unpack; m->iup.first_pass = 1; m->iup.first_pass_L1 = 1; m->iup.nbatL1 = 32; m->iup.cs_factorL1 = m->iup.cs_factor[0]; } static void table_init(MPEGI *m) { int i, j; int code; int bits; long tmp, sfmax; /*-- c_values (dequant) --*/ for (i = 1; i < 18; i++) m->iup.look_c_value[i] = (int) (32768.0 * 2.0 / steps[i]); for (i = 1; i < 18; i++) m->iup.look_c_shift[i] = 16 - stepbits[i]; /*-- scale factor table, scale by 32768 for 16 pcm output --*/ bits = min(8 * sizeof(SAMPLEINT), 8 * sizeof(m->iup.sf_table[0])); tmp = 1L << (bits - 2); sfmax = tmp + (tmp - 1); for (i = 0; i < 64; i++) { tmp = (long) (32768.0 * 2.0 * pow(2.0, -i / 3.0)); if (tmp > sfmax) tmp = sfmax; m->iup.sf_table[i] = tmp; } /*-- grouped 3 level lookup table 5 bit token --*/ for (i = 0; i < 32; i++) { code = i; for (j = 0; j < 3; j++) { m->iup.group3_table[i][j] = (char) ((code % 3) - 1); code /= 3; } } /*-- grouped 5 level lookup table 7 bit token --*/ for (i = 0; i < 128; i++) { code = i; for (j = 0; j < 3; j++) { m->iup.group5_table[i][j] = (char) ((code % 5) - 2); code /= 5; } } /*-- grouped 9 level lookup table 10 bit token --*/ for (i = 0; i < 1024; i++) { code = i; for (j = 0; j < 3; j++) { m->iup.group9_table[i][j] = (short) ((code % 9) - 4); code /= 9; } } } #ifdef _MSC_VER #pragma warning(default: 4056) #endif /*---------------------------------------------------------*/ int i_audio_decode_initL1(MPEGI *m, MPEG_HEAD * h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); void i_sbt_init(); /*---------------------------------------------------------*/ /* mpeg_head defined in mhead.h frame bytes is without pad */ int i_audio_decode_init(MPEGI *m, MPEG_HEAD * h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit) { int i, j, k; int abcd_index; long samprate; int limit; int bit_code; if (m->iup.first_pass) { table_init(m); m->iup.first_pass = 0; } /* check if code handles */ if (h->option == 3) /* layer I */ return i_audio_decode_initL1(m, h, framebytes_arg, reduction_code, transform_code, convert_code, freq_limit); if (h->option != 2) return 0; /* layer II only */ m->iup.unpack_routine = unpack; transform_code = transform_code; /* not used, asm compatability */ bit_code = 0; if (convert_code & 8) bit_code = 1; convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ if (reduction_code < 0) reduction_code = 0; if (reduction_code > 2) reduction_code = 2; if (freq_limit < 1000) freq_limit = 1000; m->iup.framebytes = framebytes_arg; /* compute abcd index for bit allo table selection */ if (h->id) /* mpeg 1 */ abcd_index = lookqt[h->mode][h->sr_index][h->br_index]; else abcd_index = 4; /* mpeg 2 */ for (i = 0; i < 4; i++) for (j = 0; j < 16; j++) m->iup.bat[i][j] = look_bat[abcd_index][i][j]; for (i = 0; i < 4; i++) m->iup.nbat[i] = look_nbat[abcd_index][i]; m->iup.max_sb = m->iup.nbat[0] + m->iup.nbat[1] + m->iup.nbat[2] + m->iup.nbat[3]; /*----- compute nsb_limit --------*/ samprate = sr_table[4 * h->id + h->sr_index]; m->iup.nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; /*- caller limit -*/ /*---- limit = 0.94*(32>>reduction_code); ----*/ limit = (32 >> reduction_code); if (limit > 8) limit--; if (m->iup.nsb_limit > limit) m->iup.nsb_limit = limit; if (m->iup.nsb_limit > m->iup.max_sb) m->iup.nsb_limit = m->iup.max_sb; m->iup.outvalues = 1152 >> reduction_code; if (h->mode != 3) { /* adjust for 2 channel modes */ for (i = 0; i < 4; i++) m->iup.nbat[i] *= 2; m->iup.max_sb *= 2; m->iup.nsb_limit *= 2; } /* set sbt function */ m->iup.nsbt = 36; k = 1 + convert_code; if (h->mode == 3) { k = 0; } m->iup.sbt = sbt_table[bit_code][reduction_code][k]; m->iup.outvalues *= out_chans[k]; if (bit_code != 0) m->iup.outbytes = m->iup.outvalues; else m->iup.outbytes = sizeof(short) * m->iup.outvalues; m->iup.decinfo.channels = out_chans[k]; m->iup.decinfo.outvalues = m->iup.outvalues; m->iup.decinfo.samprate = samprate >> reduction_code; if (bit_code != 0) m->iup.decinfo.bits = 8; else m->iup.decinfo.bits = sizeof(short) * 8; m->iup.decinfo.framebytes = m->iup.framebytes; m->iup.decinfo.type = 0; /* clear sample buffer, unused sub bands must be 0 */ for (i = 0; i < 2304; i++) m->iup.sample[i] = 0; /* init sub-band transform */ i_sbt_init(); return 1; } /*---------------------------------------------------------*/ void i_audio_decode_info(MPEGI *m, DEC_INFO * info) { *info = m->iup.decinfo; /* info return, call after init */ } /*---------------------------------------------------------*/ <file_sep>/modules/ogg/Makefile # # oggvorbis module for DreamShell # Copyright (C) 2011-2023 SWAT # http://www.dc-swat.ru # TARGET_NAME = oggvorbis OBJS = module.o DBG_LIBS = -lds LIBS = -loggvorbisplay -logg-local -lvorbis-local EXPORTS_FILE = exports.txt VER_MAJOR = 1 VER_MINOR = 3 VER_MICRO = 0 VER_BUILD = 0 KOS_LIB_PATHS += -L./liboggvorbis/liboggvorbisplay/lib \ -L./liboggvorbis/liboggvorbis/libogg/build \ -L./liboggvorbis/liboggvorbis/libvorbis/build all: rm-elf library install library: cd ./liboggvorbis && make include ../../sdk/Makefile.loadable rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) ln -nsf $(DS_SDK)/lib/$(TARGET_LIB) $(DS_SDK)/lib/libvorbis.a ln -nsf $(DS_SDK)/lib/$(TARGET_LIB) $(DS_SDK)/lib/libvorbisenc.a ln -nsf $(DS_SDK)/lib/$(TARGET_LIB) $(DS_SDK)/lib/libogg.a <file_sep>/applications/gd_ripper/modules/module.c /* DreamShell ##version## module.c - GD Ripper app module Copyright (C)2014 megavolt85 */ #include "ds.h" #include "isofs/isofs.h" DEFAULT_MODULE_EXPORTS(app_gd_ripper); #define SEC_BUF_SIZE 8 static int rip_sec(int tn,int first,int count,int type,char *dst_file, int disc_type); static int gdfiles(char *dst_folder,char *dst_file,char *text); static struct self { App_t *app; GUI_Widget *bad; GUI_Widget *sd_c; GUI_Widget *hdd_c; GUI_Widget *net_c; GUI_Widget *gname; GUI_Widget *pbar; GUI_Widget *track_label; GUI_Widget *read_error; GUI_Widget *num_read; int lastgdtrack; } self; static uint8_t rip_cancel = 0; static void cancel_callback(void) { rip_cancel = 1; } void gd_ripper_toggleSavedevice(GUI_Widget *widget) { GUI_WidgetSetState(self.sd_c, 0); GUI_WidgetSetState(self.hdd_c, 0); GUI_WidgetSetState(self.net_c, 0); GUI_WidgetSetState(widget, 1); } void gd_ripper_Number_read() { char name[4]; if (atoi(GUI_TextEntryGetText(self.num_read)) > 50) { GUI_TextEntrySetText(self.num_read, "50"); } else { snprintf(name, 4, "%d", atoi(GUI_TextEntryGetText(self.num_read))); GUI_TextEntrySetText(self.num_read, name); } } void gd_ripper_Gamename() { int x ; char text[NAME_MAX]; char txt[NAME_MAX]; strcpy(txt,"\0"); snprintf(txt,NAME_MAX,"%s", GUI_TextEntryGetText(self.gname)); if(strlen(txt) == 0) strcpy(txt,"Game"); snprintf(text,NAME_MAX,"%s",txt); for (x=0;text[x] !=0;x++) { if (text[x] == ' ') text[x] = '_' ; } GUI_TextEntrySetText(self.gname, text); //ds_printf("Image name - %s\n",text); } void gd_ripper_Delname(GUI_Widget *widget) { GUI_TextEntrySetText(widget, ""); } void gd_ripper_ipbin_name() { CDROM_TOC toc ; int status = 0, disc_type = 0, cdcr = 0, x = 0; char pbuff[2048] , text[NAME_MAX]; uint32 lba; cdrom_set_sector_size(2048); if((cdcr = cdrom_get_status(&status, &disc_type)) != ERR_OK) { switch (cdcr) { case ERR_NO_DISC : ds_printf("DS_ERROR: Disk not inserted\n"); return; default: ds_printf("DS_ERROR: GD-rom error\n"); return; } } if (disc_type == CD_CDROM_XA) { if(cdrom_read_toc(&toc, 0) != CMD_OK) { ds_printf("DS_ERROR: Toc read error\n"); return; } if(!(lba = cdrom_locate_data_track(&toc))) { ds_printf("DS_ERROR: Error locate data track\n"); return; } if (cdrom_read_sectors(pbuff,lba , 1)) { ds_printf("DS_ERROR: CD read error %d\n",lba); return; } } else if (disc_type == CD_GDROM) { if (cdrom_read_sectors(pbuff,45150 , 1)) { ds_printf("DS_ERROR: GD read error\n"); return; } } else { ds_printf("DS_ERROR: not game disc\n"); return; } ipbin_meta_t *meta = (ipbin_meta_t*) pbuff; char *p; char *o; p = meta->title; o = text; // skip any spaces at the beginning while(*p == ' ' && meta->title + 29 > p) p++; // copy rest to output buffer while(meta->title + 29 > p) { *o = *p; p++; o++; } // make sure output buf is null terminated *o = '\0'; o--; // remove trailing spaces while(*o == ' ' && o > text) { *o='\0'; o--; } if (strlen(text) == 0) { GUI_TextEntrySetText(self.gname, "Game"); } else { for (x=0;text[x] !=0;x++) { if (text[x] == ' ') text[x] = '_' ; } GUI_TextEntrySetText(self.gname, text); } //ds_printf("Image name - %s\n",text); } void gd_ripper_Init(App_t *app, const char* fileName) { if(app != NULL) { memset(&self, 0, sizeof(self)); self.app = app; self.bad = APP_GET_WIDGET("bad_btn"); self.gname = APP_GET_WIDGET("gname-text"); self.pbar = APP_GET_WIDGET("progress_bar"); self.sd_c = APP_GET_WIDGET("sd_c"); self.hdd_c = APP_GET_WIDGET("hdd_c"); self.net_c = APP_GET_WIDGET("net_c"); self.track_label = APP_GET_WIDGET("track-label"); self.read_error = APP_GET_WIDGET("read_error"); self.num_read = APP_GET_WIDGET("num-read"); if(!DirExists("/pc")) GUI_WidgetSetEnabled(self.net_c, 0); else GUI_WidgetSetState(self.net_c, 1); if(!DirExists("/sd")) { GUI_WidgetSetEnabled(self.sd_c, 0); } else { GUI_WidgetSetState(self.net_c, 0); GUI_WidgetSetState(self.sd_c, 1); } if(!DirExists("/ide")) { GUI_WidgetSetEnabled(self.hdd_c, 0); } else { GUI_WidgetSetState(self.sd_c, 0); GUI_WidgetSetState(self.net_c, 0); GUI_WidgetSetState(self.hdd_c, 1); } gd_ripper_ipbin_name(); cont_btn_callback(0, CONT_X, (cont_btn_callback_t)cancel_callback); } else { ds_printf("DS_ERROR: %s: Attempting to call %s is not by the app initiate.\n", lib_get_name(), __func__); } } void gd_ripper_StartRip() { file_t fd; CDROM_TOC toc ; int status, disc_type ,cdcr ,start ,s_end ,nsec ,type ,tn ,session, terr = 0; char dst_folder[NAME_MAX]; char dst_file[NAME_MAX]; char riplabel[64]; char text[NAME_MAX]; uint64 stoptimer, starttimer, riptime; rip_cancel = 0; starttimer = timer_ms_gettime64 (); // timer cdrom_reinit(); snprintf(text ,NAME_MAX,"%s", GUI_TextEntryGetText(self.gname)); if(GUI_WidgetGetState(self.sd_c)) { snprintf(dst_folder, NAME_MAX, "/sd/%s", text); } else if(GUI_WidgetGetState(self.hdd_c)) { snprintf(dst_folder, NAME_MAX, "/ide/%s", text); } else if(GUI_WidgetGetState(self.net_c)) { snprintf(dst_folder, NAME_MAX, "/net/%s", text); } //ds_printf("Dst file1 %s\n" ,dst_folder); getstatus: if((cdcr = cdrom_get_status(&status, &disc_type)) != ERR_OK) { switch (cdcr) { case ERR_NO_DISC : ds_printf("DS_ERROR: Disk not inserted\n"); return; case ERR_DISC_CHG : cdrom_reinit(); goto getstatus; case CD_STATUS_BUSY : thd_sleep(200); goto getstatus; case CD_STATUS_SEEKING : thd_sleep(200); goto getstatus; case CD_STATUS_SCANNING : thd_sleep(200); goto getstatus; default: ds_printf("DS_ERROR: GD-rom error\n"); return; } } if(disc_type == CD_CDROM_XA) { rname: snprintf(dst_file,NAME_MAX, "%s.iso", dst_folder); if ((fd=fs_open(dst_file , O_RDONLY)) != FILEHND_INVALID) { fs_close(fd); strcpy(dst_file,"\0"); strcat(dst_folder , "0"); goto rname ; } else { disc_type = 1; } } else if (disc_type == CD_GDROM) { rname1: if ((fd=fs_open (dst_folder , O_DIR)) != FILEHND_INVALID) { fs_close(fd); strcat(dst_folder , "0"); goto rname1 ; } else { strcpy(dst_file,"\0"); snprintf(dst_file,NAME_MAX,"%s", dst_folder); disc_type = 2; fs_mkdir(dst_file); } while(cdrom_read_toc(&toc, 1) != CMD_OK) { terr++; cdrom_reinit(); if (terr > 100) { ds_printf("DS_ERROR: Toc read error for gdlast\n"); fs_rmdir(dst_folder); return; } } terr=0; self.lastgdtrack = TOC_TRACK(toc.last); } else { ds_printf("DS_ERROR: This is not game disk\nInserted %d disk\n",disc_type); return; } //ds_printf("Dst file %s\n" ,dst_file); for(session = 0; session < disc_type; session++) { cdrom_set_sector_size(2048); while(cdrom_read_toc(&toc, session) != CMD_OK) { terr++; if(terr==5) cdrom_reinit(); thd_sleep(500); if (terr > 10) { ds_printf("DS_ERROR: Toc read error\n"); if (disc_type == 1) { if(fs_unlink(dst_file) != 0) ds_printf("Error delete file: %s\n" ,dst_file); } else { if ((fd=fs_open (dst_folder , O_DIR)) == FILEHND_INVALID) { ds_printf("Error folder '%s' not found\n" ,dst_folder); return; } dirent_t *dir; while ((dir = fs_readdir(fd))) { if (!strcmp(dir->name,".") || !strcmp(dir->name,"..")) continue; strcpy(dst_file,"\0"); snprintf(dst_file, NAME_MAX, "%s/%s", dst_folder, dir->name); fs_unlink(dst_file); } fs_close(fd); fs_rmdir(dst_folder); } return; } } terr = 0; int first = TOC_TRACK(toc.first); int last = TOC_TRACK(toc.last); for (tn = first; tn <= last; tn++ ) { if (disc_type == 1) tn = last; type = TOC_CTRL(toc.entry[tn-1]); if (disc_type == 2) { strcpy(dst_file,"\0"); snprintf(dst_file,NAME_MAX,"%s/track%02d.%s", dst_folder, tn, (type == 4 ? "iso" : "raw")); } start = TOC_LBA(toc.entry[tn-1]); s_end = TOC_LBA((tn == last ? toc.leadout_sector : toc.entry[tn])); nsec = s_end - start; if(disc_type == 1 && type == 4) nsec -= 2 ; else if(session==1 && tn != last && type != TOC_CTRL(toc.entry[tn])) nsec -= 150; else if(session==0 && type == 4) nsec -= 150; if(disc_type == 2 && session == 0) { strcpy(riplabel,"\0"); sprintf(riplabel,"Track %d of %d\n",tn ,self.lastgdtrack ); } else if(disc_type == 2 && session == 1 && tn != self.lastgdtrack) { strcpy(riplabel,"\0"); sprintf(riplabel,"Track %d of %d\n",tn ,self.lastgdtrack ); } else { strcpy(riplabel,"\0"); sprintf(riplabel,"Last track\n"); } GUI_LabelSetText(self.track_label, riplabel); if (rip_sec(tn, start, nsec, type, dst_file, disc_type) != CMD_OK) { GUI_LabelSetText(self.track_label, " "); stoptimer = timer_ms_gettime64 (); // timer GUI_ProgressBarSetPosition(self.pbar, 0.0); cdrom_spin_down(); if (disc_type == 1) { if(fs_unlink(dst_file) != 0) ds_printf("Error delete file: %s\n" ,dst_file); } else { if((fd=fs_open (dst_folder , O_DIR)) == FILEHND_INVALID) { ds_printf("Error folder '%s' not found\n" ,dst_folder); return; } dirent_t *dir; while ((dir = fs_readdir(fd))) { if (!strcmp(dir->name,".") || !strcmp(dir->name,"..")) continue; strcpy(dst_file,"\0"); snprintf(dst_file, NAME_MAX, "%s/%s", dst_folder, dir->name); fs_unlink(dst_file); } fs_close(fd); fs_rmdir(dst_folder); } return ; } GUI_LabelSetText(self.track_label, " "); GUI_ProgressBarSetPosition(self.pbar, 0.0); } } GUI_LabelSetText(self.track_label, " "); GUI_WidgetMarkChanged(self.app->body); if (disc_type == 2) { if (gdfiles(dst_folder, dst_file, text) != CMD_OK) { cdrom_spin_down(); if ((fd=fs_open (dst_folder , O_DIR)) == FILEHND_INVALID) { ds_printf("Error folder '%s' not found\n" ,dst_folder); return; } dirent_t *dir; while ((dir = fs_readdir(fd))) { if(!strcmp(dir->name,".") || !strcmp(dir->name,"..")) continue; strcpy(dst_file,"\0"); snprintf(dst_file, NAME_MAX, "%s/%s", dst_folder, dir->name); fs_unlink(dst_file); } fs_close(fd); fs_rmdir(dst_folder); return; } } GUI_ProgressBarSetPosition(self.pbar, 0.0); cdrom_spin_down(); stoptimer = timer_ms_gettime64 (); // timer riptime = stoptimer - starttimer; int ripmin = riptime / 60000 ; int ripsec = riptime % 60 ; ds_printf("DS_OK: End ripping. Save at %d:%d\n",ripmin,ripsec); } static int rip_sec(int tn,int first,int count,int type,char *dst_file, int disc_type) { double percent,percent_last = 0.0; maple_device_t *cont; cont_state_t *state; file_t hnd; int secbyte = (type == 4 ? 2048 : 2352) , i , count_old=count, bad=0, cdstat, readi; uint8 *buffer = (uint8 *)memalign(32, SEC_BUF_SIZE * secbyte); GUI_WidgetMarkChanged(self.app->body); // ds_printf("Track %d First %d Count %d Type %d\n",tn,first,count,type); /* if (secbyte == 2048) cdrom_set_sector_size (secbyte); else _cdrom_reinit (1); */ cdrom_set_sector_size(secbyte); thd_sleep(200); if ((hnd = fs_open(dst_file,O_WRONLY | O_TRUNC | O_CREAT)) == FILEHND_INVALID) { ds_printf("Error open file %s\n" ,dst_file); cdrom_spin_down(); free(buffer); return CMD_ERROR; } LockVideo(); while(count) { if(rip_cancel == 1) { SDL_WarpMouse(60, 400); return CMD_ERROR; } int nsects = count > SEC_BUF_SIZE ? SEC_BUF_SIZE : count; count -= nsects; while((cdstat=cdrom_read_sectors(buffer, first, nsects)) != ERR_OK ) { if (atoi(GUI_TextEntryGetText(self.num_read)) == 0) break; readi++ ; if (readi > 5) break ; thd_sleep(200); } readi = 0; if (cdstat != ERR_OK) { if (!GUI_WidgetGetState(self.bad)) { UnlockVideo(); GUI_ProgressBarSetPosition(self.read_error, 1.0); for(;;) { cont = maple_enum_type(0, MAPLE_FUNC_CONTROLLER); if(!cont) continue; state = (cont_state_t *)maple_dev_status(cont); if(!state) continue; if(state->buttons & CONT_A) { GUI_ProgressBarSetPosition(self.read_error, 0.0); GUI_WidgetMarkChanged(self.app->body); ds_printf("DS_ERROR: Can't read sector %ld\n", first); free(buffer); fs_close(hnd); return CMD_ERROR; } else if(state->buttons & CONT_B) { GUI_ProgressBarSetPosition(self.read_error, 0.0); GUI_WidgetMarkChanged(self.app->body); break; } else if(state->buttons & CONT_Y) { GUI_ProgressBarSetPosition(self.read_error, 0.0); GUI_WidgetSetState(self.bad, 1); GUI_WidgetMarkChanged(self.app->body); break; } } } // Ошибка, попробуем по одному uint8 *pbuffer = buffer; LockVideo(); for(i = 0; i < nsects; i++) { while((cdstat=cdrom_read_sectors(pbuffer, first, 1)) != ERR_OK ) { readi++ ; if (readi > atoi(GUI_TextEntryGetText(self.num_read))) break ; if (readi == 1 || readi == 6 || readi == 11 || readi == 16 || readi == 21 || readi == 26 || readi == 31 || readi == 36 || readi == 41 || readi == 46) cdrom_reinit(); thd_sleep(200); } readi = 0; if (cdstat != ERR_OK) { // Ошибка, заполним нулями и игнорируем UnlockVideo(); cdrom_reinit(); memset(pbuffer, 0, secbyte); bad++; ds_printf("DS_ERROR: Can't read sector %ld\n", first); LockVideo(); } pbuffer += secbyte; first++; } } else { // Все ок, идем дальше first += nsects; } if(fs_write(hnd, buffer, nsects * secbyte) < 0) { // Ошибка записи, печально, прерываем процесс UnlockVideo(); free(buffer); fs_close(hnd); return CMD_ERROR; } UnlockVideo(); percent = 1-(float)(count) / count_old; if ((percent = ((int)(percent*100 + 0.5))/100.0) > percent_last) { percent_last = percent; GUI_ProgressBarSetPosition(self.pbar, percent); LockVideo(); } } UnlockVideo(); free(buffer); fs_close(hnd); ds_printf("%d Bad sectors on track\n", bad); return CMD_OK; } int gdfiles(char *dst_folder,char *dst_file,char *text) { file_t gdfd; FILE *gdifd; CDROM_TOC gdtoc; CDROM_TOC cdtoc; int track ,lba ,gdtype ,cdtype; uint8 *buff = memalign(32, 32768); cdrom_set_sector_size (2048); if(cdrom_read_toc(&cdtoc, 0) != CMD_OK) { ds_printf("DS_ERROR:CD Toc read error\n"); free(buff); return CMD_ERROR; } if(cdrom_read_toc(&gdtoc, 1) != CMD_OK) { ds_printf("DS_ERROR:GD Toc read error\n"); free(buff); return CMD_ERROR; } if(cdrom_read_sectors(buff,45150,16)) { ds_printf("DS_ERROR: IP.BIN read error\n"); free(buff); return CMD_ERROR; } strcpy(dst_file,"\0"); snprintf(dst_file,NAME_MAX,"%s/IP.BIN",dst_folder); if ((gdfd=fs_open(dst_file,O_WRONLY | O_TRUNC | O_CREAT)) == FILEHND_INVALID) { ds_printf("DS_ERROR: Error open IP.BIN for write\n"); free(buff); return CMD_ERROR; } if (fs_write(gdfd,buff,32768) == -1) { ds_printf("DS_ERROR: Error write IP.BIN\n"); free(buff); fs_close(gdfd); return CMD_ERROR; } fs_close(gdfd); free(buff); ds_printf("IP.BIN succes dumped\n"); fs_chdir(dst_folder); strcpy(dst_file,"\0"); snprintf(dst_file,NAME_MAX,"%s.gdi",text); if ((gdifd=fopen(dst_file,"w")) == NULL) { ds_printf("DS_ERROR: Error open %s.gdi for write\n",text); return CMD_ERROR; } int cdfirst = TOC_TRACK(cdtoc.first); int cdlast = TOC_TRACK(cdtoc.last); int gdfirst = TOC_TRACK(gdtoc.first); int gdlast = TOC_TRACK(gdtoc.last); fprintf(gdifd,"%d\n",gdlast); for (track=cdfirst; track <= cdlast; track++ ) { lba = TOC_LBA(cdtoc.entry[track-1]); lba -= 150; cdtype = TOC_CTRL(cdtoc.entry[track-1]); fprintf(gdifd, "%d %d %d %d track%02d.%s 0\n",track,lba,cdtype,(cdtype == 4 ? 2048 : 2352),track,(cdtype == 4 ? "iso" : "raw")); } for (track=gdfirst; track <= gdlast; track++ ) { lba = TOC_LBA(gdtoc.entry[track-1]); lba -= 150; gdtype = TOC_CTRL(gdtoc.entry[track-1]); fprintf(gdifd, "%d %d %d %d track%02d.%s 0\n",track,lba,gdtype,(gdtype == 4 ? 2048 : 2352),track,(gdtype == 4 ? "iso" : "raw")); } fclose(gdifd); fs_chdir("/"); ds_printf("%s.gdi succes writen\n",text); return CMD_OK; } void gd_ripper_Exit() { cdrom_spin_down(); } <file_sep>/sdk/toolchain/cleanup.sh #!/bin/sh # These version numbers are all that should ever have to be changed. . $PWD/versions.sh while [ "$1" != "" ]; do PARAM=`echo $1 | awk -F= '{print $1}'` case $PARAM in --no-gmp) unset GMP_VER ;; --no-mpfr) unset MPFR_VER ;; --no-mpc) unset MPC_VER ;; --no-deps) unset GMP_VER unset MPFR_VER unset MPC_VER ;; *) echo "ERROR: unknown parameter \"$PARAM\"" exit 1 ;; esac shift done # Clean up downloaded tarballs... echo "Deleting downloaded packages..." rm -f binutils-$BINUTILS_VER.tar.bz2 rm -f gcc-$GCC_VER.tar.gz rm -f newlib-$NEWLIB_VER.tar.gz if [ -n "$GMP_VER" ]; then rm -f gmp-$GMP_VER.tar.bz2 fi if [ -n "$MPFR_VER" ]; then rm -f mpfr-$MPFR_VER.tar.bz2 fi if [ -n "$MPC_VER" ]; then rm -f mpc-$MPC_VER.tar.gz fi echo "Done!" echo "---------------------------------------" # Clean up echo "Deleting unpacked package sources..." rm -rf binutils-$BINUTILS_VER rm -rf gcc-$GCC_VER rm -rf newlib-$NEWLIB_VER if [ -n "$GMP_VER" ]; then rm -rf gmp-$GMP_VER fi if [ -n "$MPFR_VER" ]; then rm -rf mpfr-$MPFR_VER fi if [ -n "$MPC_VER" ]; then rm -rf mpc-$MPC_VER fi echo "Done!" echo "---------------------------------------" # Clean up any stale build directories. echo "Cleaning up build directories..." rm -rf build-* echo "Done!" echo "---------------------------------------" # Clean up the logs. echo "Cleaning up build logs..." rm -f logs/*.log echo "Done!" <file_sep>/firmware/isoldr/loader/maple.c /** * DreamShell ISO Loader * Maple sniffing and VMU emulation * (c)2022-2023 SWAT <http://www.dc-swat.ru> */ #include <main.h> #include <asic.h> #include <exception.h> #include <ubc.h> #include <maple.h> #include <dc/maple.h> #include <dc/controller.h> /** * Turn off maple logging by default * but keep it for sniffer mode. */ #ifdef LOG // # define MAPLE_LOG 1 #endif #if defined(MAPLE_SNIFFER) && defined(LOG) # ifndef MAPLE_LOG # define MAPLE_LOG 1 # endif #endif typedef struct { uint32 function; uint16 size; uint16 partition; uint16 sys_block; uint16 fat_block; uint16 fat_cnt; uint16 file_info_block; uint16 file_info_cnt; uint8 vol_icon; uint8 reserved; uint16 save_block; uint16 save_cnt; uint32 reserved_exec; } maple_memory_t; #ifdef MAPLE_LOG static void maple_dump_frame(const char *direction, uint32 num, maple_frame_t *frame) { LOGF(" %s: %d cmd=%d from=0x%02lx to=0x%02lx len=%d", direction, num, frame->cmd, frame->from, frame->to, frame->datalen); if (frame->datalen) { LOGF(" data="); uint32 *dt = (uint32 *)frame->data; int max_len = frame->datalen > 7 ? 7 : frame->datalen; for(int i = 0; i < max_len; ++i) { LOGF("0x%08lx ", *dt++); } } LOGF("\n"); } static void maple_dump_device_info(maple_devinfo_t *di) { char name[sizeof(di->product_name) + 1]; memcpy(name, di->product_name, sizeof(di->product_name)); name[sizeof(di->product_name)] = '\0'; LOGF(" DEVICE: %s | 0x%08lx | 0x%08lx 0x%08lx 0x%08lx | 0x%02lx | 0x%02lx | %d | %d\n", name, di->func, di->function_data[0], di->function_data[1], di->function_data[2], di->area_code, di->connector_direction, di->standby_power, di->max_power); } static void maple_dump_memory_info(maple_memory_t *mi) { LOGF(" MEMORY: 0x%08lx | %d | %d | %d | %d | %d | %d | %d | %d | %d | %d | %d | 0x%08lx\n", mi->function, mi->size, mi->partition, mi->sys_block, mi->fat_block, mi->fat_cnt, mi->file_info_block, mi->file_info_cnt, mi->vol_icon, mi->reserved, mi->save_block, mi->save_cnt, mi->reserved_exec); } #else # define maple_dump_frame(a, b, c) # define maple_dump_device_info(a) # define maple_dump_memory_info(a) #endif void maple_read_frame(uint32 *buffer, maple_frame_t *frame) { uint32 val = *buffer++; uint8 *b = (uint8 *)&val; frame->cmd = b[0]; frame->to = b[1]; frame->from = b[2]; frame->datalen = b[3]; frame->data = buffer; } #ifndef MAPLE_SNIFFER static int vmu_fd = FILEHND_INVALID; static maple_devinfo_t device_info = { MAPLE_FUNC_MEMCARD | MAPLE_FUNC_LCD | MAPLE_FUNC_CLOCK, { 0x403f7e7e, 0x00100500, 0x00410f00 }, 0xff, 0x00, { 'V','i','s','u','a','l',' ','M','e','m', 'o','r','y',' ',' ',' ',' ',' ',' ',' ', ' ',' ',' ',' ',' ',' ',' ',' ',' ',' ' }, { 'P','r','o','d','u','c','e','d',' ','B','y',' ','o','r',' ', 'U','n','d','e','r',' ','L','i','c','e','n','s','e',' ','F', 'r','o','m',' ','S','E','G','A',' ','E','N','T','E','R','P', 'R','I','S','E','S',',','L','T','D','.',' ',' ',' ',' ',' ' }, 0x007c, 0x0082 }; static maple_memory_t memory_info = { MAPLE_FUNC_MEMCARD, 255, 0, 255, 254, 1, 253, 13, 0, 0, 200, 0, 0x00800000 }; static void maple_vmu_device_info(maple_frame_t *req, maple_frame_t *resp) { maple_devinfo_t *di = (maple_devinfo_t *)&resp->data; resp->cmd = MAPLE_RESPONSE_DEVINFO; resp->datalen = sizeof(maple_devinfo_t) / 4; resp->from = req->to; resp->to = req->from; if (req->cmd == MAPLE_COMMAND_ALLINFO) { resp->cmd = MAPLE_RESPONSE_ALLINFO; resp->datalen += 20; memset(di + sizeof(maple_devinfo_t), 0, 20 * 4); } memcpy(di, &device_info, sizeof(maple_devinfo_t)); maple_dump_device_info(&device_info); } static void maple_vmu_memory_info(maple_frame_t *req, maple_frame_t *resp) { (void)req; maple_memory_t *mi = (maple_memory_t *)&resp->data; resp->cmd = MAPLE_RESPONSE_DATATRF; resp->datalen = sizeof(maple_memory_t) / 4; resp->from = req->to; resp->to = req->from; memcpy(mi, &memory_info, sizeof(maple_memory_t)); maple_dump_memory_info(&memory_info); } static void maple_vmu_block_read(maple_frame_t *req, maple_frame_t *resp) { uint32 *req_params = (uint32 *)req->data; uint32 *resp_params = (uint32 *)&resp->data; resp_params[0] = req_params[0]; resp_params[1] = req_params[1]; resp->from = req->to; resp->to = req->from; if (pre_read_xfer_busy()) { resp->cmd = MAPLE_RESPONSE_AGAIN; resp->datalen = 0; LOGF(" BREAD: device busy\n"); return; } uint16 block = ((req_params[1] >> 24) & 0xff) | ((req_params[1] >> 16) & 0xff) << 8; uint8 *buff = (uint8 *)&resp_params[2]; lseek(vmu_fd, block * 512, SEEK_SET); int res = read(vmu_fd, buff, 512); LOGF(" BREAD: block=%d buff=0x%08lx res=%d\n", block, buff, res); if (res < 0) { resp->datalen = 2; resp->cmd = MAPLE_RESPONSE_FILEERR; return; } resp->cmd = MAPLE_RESPONSE_DATATRF; resp->datalen = 130; if (block == 255) { memcpy((uint8 *)&memory_info.fat_block, &buff[70], 14); } } static void maple_vmu_block_write(maple_frame_t *req, maple_frame_t *resp) { uint32 *req_params = (uint32 *)req->data; resp->cmd = MAPLE_RESPONSE_OK; resp->from = req->to; resp->to = req->from; resp->datalen = 0; // Maybe it's LCD or Buzzer data if (req_params[0] != MAPLE_FUNC_MEMCARD) { return; } if (pre_read_xfer_busy()) { resp->cmd = MAPLE_RESPONSE_AGAIN; LOGF(" BWRITE: device busy\n"); return; } uint8 phase = (req_params[1] >> 8) & 0x0f; uint16 block = ((req_params[1] >> 24) & 0xff) | ((req_params[1] >> 16) & 0xff) << 8; uint8 *buff = (uint8 *)&req_params[2]; #if _FS_READONLY == 0 lseek(vmu_fd, (block * 512) + (128 * phase), SEEK_SET); int res = write(vmu_fd, buff, 128); LOGF(" BWRITE: block=%d phase=%d buff=0x%08lx res=%d\n", block, phase, buff, res); if (res < 0) { uint32 *resp_params = (uint32 *)&resp->data; resp_params[0] = req_params[0]; resp_params[1] = req_params[1]; resp->datalen = 2; resp->cmd = MAPLE_RESPONSE_FILEERR; return; } #else LOGF(" BWRITE: block=%d phase=%d buff=0x%08lx disabled\n", block, phase, buff); #endif if (block == 255 && phase == 0) { memcpy((uint8 *)&memory_info.fat_block, &buff[70], 14); } } static void maple_vmu_block_sync(maple_frame_t *req, maple_frame_t *resp) { resp->cmd = MAPLE_RESPONSE_OK; resp->from = req->to; resp->to = req->from; resp->datalen = 0; if (pre_read_xfer_busy()) { resp->cmd = MAPLE_RESPONSE_AGAIN; LOGF(" BSYNC: device busy\n"); return; } ioctl(vmu_fd, FS_IOCTL_SYNC, NULL); #ifdef LOG uint32 *req_params = (uint32 *)req->data; uint16 block = ((req_params[1] >> 24) & 0xff) | ((req_params[1] >> 16) & 0xff) << 8; uint16 len = ((req_params[1] >> 8) & 0xff) | (req_params[1] & 0xff) << 8; LOGF(" BSYNC: block=%d len=%d\n", block, len); #endif } static void maple_controller(maple_frame_t *req, maple_frame_t *resp) { uint32 *resp_params = (uint32 *)&resp->data; static uint32 prev_buttons = 0; (void)req; if (resp_params[0] != MAPLE_FUNC_CONTROLLER || resp->cmd != MAPLE_RESPONSE_DATATRF) { return; } cont_cond_t *cond = (cont_cond_t *)&resp_params[1]; if (cond->buttons == 0xffff) { prev_buttons = 0; return; } uint32 buttons = (~cond->buttons & 0xffff); // LOGF(" CTRL: but=0x%04lx joyx=%d joyy=%d\n", buttons, cond->joyx, cond->joyy); #ifdef HAVE_SCREENSHOT if (buttons == IsoInfo->scr_hotkey && buttons != prev_buttons) { video_screenshot(); } #endif prev_buttons = buttons; } static void maple_cmd_proc(int8 cmd, maple_frame_t *req, maple_frame_t *resp) { if (vmu_fd > FILEHND_INVALID) { if (resp->from & 0x20) { resp->from |= 0x01; } if (req->to == 0x01) { switch (cmd) { case MAPLE_COMMAND_DEVINFO: case MAPLE_COMMAND_ALLINFO: maple_vmu_device_info(req, resp); break; case MAPLE_COMMAND_GETMINFO: maple_vmu_memory_info(req, resp); break; case MAPLE_COMMAND_BREAD: maple_vmu_block_read(req, resp); break; case MAPLE_COMMAND_BWRITE: maple_vmu_block_write(req, resp); break; case MAPLE_COMMAND_BSYNC: maple_vmu_block_sync(req, resp); break; default: break; } } } if (IsoInfo->scr_hotkey && cmd == MAPLE_COMMAND_GETCOND) { maple_controller(req, resp); } } #else // MAPLE_SNIFFER static void maple_cmd_proc(int8 cmd, maple_frame_t *req, maple_frame_t *resp) { (void)req; switch (cmd) { case MAPLE_COMMAND_DEVINFO: case MAPLE_COMMAND_ALLINFO: maple_dump_device_info((maple_devinfo_t *)NONCACHED_ADDR((uint32)&resp->data)); break; case MAPLE_COMMAND_GETMINFO: maple_dump_memory_info((maple_memory_t *)NONCACHED_ADDR((uint32)&resp->data)); break; default: break; } } #endif // MAPLE_SNIFFER static void maple_dma_proc() { uint32 *data, *recv_data, addr, value; uint32 trans_count; uint8 len, last = 0, port, pattern; maple_frame_t req_frame; maple_frame_t *resp_frame_ptr; addr = MAPLE_REG(MAPLE_DMA_ADDR); data = (uint32 *)NONCACHED_ADDR(addr); for (trans_count = 0; trans_count < 24 && !last; ++trans_count) { /* First word: transfer parameters */ value = *data++; len = value & 0xff; pattern = (value >> 8) & 0xff; port = (value >> 16) & 0x0f; last = (value >> 31) & 0x01; /* Second word: receive buffer physical address */ addr = *data; /* Skip lightgun mode and NOP frame */ if (pattern) { continue; } #ifndef MAPLE_SNIFFER if (port) { data += len + 2; continue; } #endif maple_read_frame(data + 1, &req_frame); data += len + 2; recv_data = (uint32 *)NONCACHED_ADDR(addr); resp_frame_ptr = (maple_frame_t *)recv_data; #ifdef MAPLE_LOG LOGF("MAPLE_XFER: %d value=0x%08lx pattern=0x%02x len=%d port=%d addr=0x%08lx last=%d\n", trans_count, value, pattern, len, port, (pattern ? 0 : addr), last); maple_frame_t resp_frame; maple_read_frame(recv_data, &resp_frame); maple_dump_frame("SEND", trans_count, &req_frame); maple_dump_frame("RECV", trans_count, &resp_frame); maple_cmd_proc(req_frame.cmd, &req_frame, resp_frame_ptr); if (vmu_fd > FILEHND_INVALID && (req_frame.to == 0x01 || resp_frame.from & 0x20)) { maple_read_frame(recv_data, &resp_frame); maple_dump_frame("EMUL", trans_count, &resp_frame); } #else maple_cmd_proc(req_frame.cmd, &req_frame, resp_frame_ptr); #endif } } #ifdef NO_ASIC_LT void *maple_dma_handler(void *passer, register_stack *stack, void *current_vector) { (void)passer; (void)stack; #else static asic_handler_f old_maple_dma_handler = NULL; static void *maple_dma_handler(void *passer, register_stack *stack, void *current_vector) { if (old_maple_dma_handler && passer != current_vector) { current_vector = old_maple_dma_handler(passer, stack, current_vector); } #endif #ifdef HAVE_UBC static uint32 requested = 0; if (passer == current_vector) { // Handle UBC break on Maple register requested = 1; } else if(requested) { maple_dma_proc(); requested = 0; } #else uint32 code = *REG_INTEVT; if (((*ASIC_IRQ11_MASK & ASIC_NRM_AICA_DMA) && code == EXP_CODE_INT11) || ((*ASIC_IRQ9_MASK & ASIC_NRM_AICA_DMA) && code == EXP_CODE_INT9) || ((*ASIC_IRQ13_MASK & ASIC_NRM_AICA_DMA) && code == EXP_CODE_INT13) ) { maple_dma_proc(); } #endif return current_vector; } int maple_init_irq() { #ifdef HAVE_UBC ubc_init(); ubc_configure_channel(UBC_CHANNEL_A, MAPLE_DMA_STATUS, UBC_BBR_OPERAND | UBC_BBR_WRITE); #endif #ifndef NO_ASIC_LT asic_lookup_table_entry a_entry; memset(&a_entry, 0, sizeof(a_entry)); a_entry.irq = EXP_CODE_INT11; a_entry.mask[ASIC_MASK_NRM_INT] = ASIC_NRM_MAPLE_DMA; a_entry.handler = maple_dma_handler; return asic_add_handler(&a_entry, &old_maple_dma_handler, 0); #else return 0; #endif } int maple_init_vmu(int num) { #ifdef MAPLE_SNIFFER (void)num; #else # if _FS_READONLY == 0 int flags = O_RDWR | O_PIO; # else int flags = O_RDONLY | O_PIO; # endif char *filename = relative_filename("vmu001.vmd"); set_file_number(filename, num); if (vmu_fd > FILEHND_INVALID) { close(vmu_fd); } vmu_fd = open(filename, flags); free(filename); if (vmu_fd < 0) { filename = "/DS/vmu/vmu001.vmd"; set_file_number(filename, num); if (vmu_fd < 0) { vmu_fd = open(filename + 3, flags); if (vmu_fd < 0) { LOGFF("can't find VMU dump: %d\n", num); return -1; } } } lseek(vmu_fd, (255 * 512) + 70, SEEK_SET); read(vmu_fd, (uint8 *)&memory_info.fat_block, 14); LOGFF("fat_blk=%d fat_cnt=%d fileinf_blk=%d fileinf_cnt=%d\n", memory_info.fat_block, memory_info.fat_cnt, memory_info.file_info_block, memory_info.file_info_cnt); #endif return 0; } <file_sep>/include/drivers/g1_ide.h /* DreamShell ##version## drivers/g1_ide.h Copyright (C) 2013-2014 SWAT Additional functions for G1-ATA devices */ #ifndef __G1_IDE_H #define __G1_IDE_H #include <sys/cdefs.h> __BEGIN_DECLS #include <dc/g1ata.h> __END_DECLS #endif /* !__G1_IDE_H */ <file_sep>/lib/Makefile # # DreamShell libraries Makefile # Copyright (C) 2008-2022 SWAT # http://www.dc-swat.ru # _SUBDIRS = libcfg/src libparallax SDL_rtf \ lua SDL SDL_gfx SDL_image SDL_ttf _SUBDIRS_CLEAN = $(_SUBDIRS) freetype mxml all: build_freetype build_mxml $(patsubst %, _dir_%, $(_SUBDIRS)) $(patsubst %, _dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _dir_%, %, $@) clean: $(patsubst %, _clean_dir_%, $(_SUBDIRS_CLEAN)) $(patsubst %, _clean_dir_%, $(_SUBDIRS_CLEAN)): $(MAKE) -C $(patsubst _clean_dir_%, %, $@) clean install: $(patsubst %, _install_dir_%, $(_SUBDIRS)) $(patsubst %, _install_dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _install_dir_%, %, $@) install build_freetype: cd freetype/builds/unix && ./conf.sh $(MAKE) -C freetype cp ./freetype/objs/.libs/libfreetype.a libfreetype.a build_mxml: cd ./mxml && ./conf.sh $(MAKE) -C mxml libmxml.a mv mxml/libmxml.a libmxml.a <file_sep>/applications/vmu_manager/Makefile # # Speedtest App for DreamShell # Copyright (C) 2015 megavolt85 # SUBDIRS = modules include ../../sdk/Makefile.cfg APP_NAME = vmu_manager APP_DIR = $(DS_BUILD)/apps/$(APP_NAME) DEPS = modules/app_$(APP_NAME).klf # Uncomment for enable DEBUG #KOS_CFLAGS += -DVMDEBUG all: install $(DEPS): modules/module.c cd modules && make clean: cd modules && make clean && cd ../ install: app.xml $(DEPS) -mkdir -p $(APP_DIR) -mkdir -p $(APP_DIR)/modules cp modules/app_$(APP_NAME).klf $(APP_DIR)/modules/app_$(APP_NAME).klf cp app.xml $(APP_DIR)/app.xml cp -R images $(APP_DIR) <file_sep>/modules/vkb/vkb.c /** * \file vkb.c * \brief DreamShell virtual keyboard * \date 2007-2014 * \author SWAT www.dc-swat.ru */ #include "ds.h" #include "SDL/SDL_rotozoom.h" #define VIRT_KB_SURFACE_COUNT 3 #define VIRT_KB_SURFACE_KEYS 0 #define VIRT_KB_SURFACE_KEYS_CAPS 1 #define VIRT_KB_SURFACE_NUMS 2 typedef struct virt_kb_section { int keys[4]; } virt_kb_section_t; typedef struct virt_kb_syms { virt_kb_section_t sections[9]; } virt_kb_syms_t; typedef struct virt_kb_surface { SDL_Surface *s; float zoom; } virt_kb_surface_t; typedef struct virt_kb { int cur_surf; int visible; int redraw; int row; int col; SDL_Event event; uint32 clr; virt_kb_surface_t surface[VIRT_KB_SURFACE_COUNT]; Event_t *input; Event_t *video; } virt_kb_t; static virt_kb_t vkb; static void VirtKeyboardEvent(void *da_event, void *param, int action); static void VirtKeyboardDraw(void *da_event, void *param, int action); static void VirtKeyboardUpdateWorkPlace(); #define VKB_DRAW_PADDING 10 static virt_kb_syms_t VirtKeyboardKeySyms[VIRT_KB_SURFACE_COUNT] = { // Syms {{ {{ 'e', 'f', 'g', 'h' }}, // TopLeft {{ 'i', 'j', 'k', 'l' }}, // Top {{ 'm', 'n', 'o', 'p' }}, // TopRight {{ 'a', 'b', 'c', 'd' }}, // Left {{ SDLK_BACKSPACE, ' ', SDLK_RETURN, SDLK_ESCAPE }}, // Center {{ 'q', 'r', 's', 't' }}, // Right {{ '<', '[', '>', ']' }}, // BottomLeft {{ 'y', '.', 'z', ',' }}, // Bottom {{ 'u', 'v', 'w', 'x' }} // BottomRight }}, // Cap syms {{ {{ 'E', 'F', 'G', 'H' }}, // TopLeft {{ 'I', 'J', 'K', 'L' }}, // Top {{ 'M', 'N', 'O', 'P' }}, // TopRight {{ 'A', 'B', 'C', 'D' }}, // Left {{ SDLK_DELETE, SDLK_TAB, SDLK_RETURN, SDLK_LCTRL }}, // Center {{ 'Q', 'R', 'S', 'T' }}, // Right {{ '(', '{', ')', '}' }}, // BottomLeft {{ 'Y', '.', 'Z', ',' }}, // Bottom {{ 'U', 'V', 'W', 'X' }} // BottomRight }}, // Nums {{ {{ '1', '2', '3', '4' }}, // TopLeft {{ '5', '6', '7', '8' }}, // Top {{ '9', '\"', '0', '\'' }}, // TopRight {{ '+', '-', '*', '\\' }}, // Left {{ SDLK_DELETE, SDLK_TAB, SDLK_RETURN, '_' }}, // Center {{ '@', '|', '?', '/' }}, // Right {{ '#', '~', '!', '`' }}, // BottomLeft {{ ';', '.', ':', '$' }}, // Bottom {{ '&', '^', '%', '=' }} // BottomRight }} }; static int VirtKeyboardLoading(int reset) { char fn[NAME_MAX]; int i = 0; if(reset) { for(i = 0; i < VIRT_KB_SURFACE_COUNT; i++) { if(vkb.surface[i].s != NULL) { SDL_FreeSurface(vkb.surface[i].s); } } } sprintf(fn, "%s/gui/keyboard/syms.bmp", getenv("PATH")); vkb.surface[VIRT_KB_SURFACE_KEYS].s = IMG_Load(fn); if(vkb.surface[VIRT_KB_SURFACE_KEYS].s == NULL) { ds_printf("DS_ERROR: Can't load %s\n", fn); goto error; } vkb.surface[VIRT_KB_SURFACE_KEYS].zoom = 1.0f; sprintf(fn, "%s/gui/keyboard/cap_syms.bmp", getenv("PATH")); vkb.surface[VIRT_KB_SURFACE_KEYS_CAPS].s = IMG_Load(fn); if(vkb.surface[VIRT_KB_SURFACE_KEYS_CAPS].s == NULL) { ds_printf("DS_ERROR: Can't load %s\n", fn); goto error; } vkb.surface[VIRT_KB_SURFACE_KEYS_CAPS].zoom = 1.0f; sprintf(fn, "%s/gui/keyboard/nums.bmp", getenv("PATH")); vkb.surface[VIRT_KB_SURFACE_NUMS].s = IMG_Load(fn); if(vkb.surface[VIRT_KB_SURFACE_NUMS].s == NULL) { ds_printf("DS_ERROR: Can't load %s\n", fn); goto error; } vkb.surface[VIRT_KB_SURFACE_NUMS].zoom = 1.0f; return 0; error: for(i = 0; i < VIRT_KB_SURFACE_COUNT; i++) { if(vkb.surface[i].s != NULL) { SDL_FreeSurface(vkb.surface[i].s); } } return -1; } int VirtKeyboardInit() { memset(&vkb, 0, sizeof(vkb)); // if(VirtKeyboardLoading(0) < 0) { // return -1; // } vkb.col = 1; vkb.row = 1; vkb.cur_surf = VIRT_KB_SURFACE_KEYS; vkb.visible = 0; vkb.redraw = 0; vkb.clr = 0x0000007F; vkb.input = AddEvent("VirtKeyboardInput", EVENT_TYPE_INPUT, VirtKeyboardEvent, NULL); if(!vkb.input) { VirtKeyboardShutdown(); return -1; } vkb.video = AddEvent("VirtKeyboardVideo", EVENT_TYPE_VIDEO, VirtKeyboardDraw, NULL); if(!vkb.video) { VirtKeyboardShutdown(); return -1; } vkb.event.type = SDL_KEYDOWN; vkb.event.key.type = SDL_KEYDOWN; return 0; } void VirtKeyboardShutdown() { int i; if(VirtKeyboardIsVisible()) { VirtKeyboardHide(); } if(vkb.input) RemoveEvent(vkb.input); if(vkb.video) RemoveEvent(vkb.video); for(i = 0; i < VIRT_KB_SURFACE_COUNT; i++) { if(vkb.surface[i].s != NULL) { SDL_FreeSurface(vkb.surface[i].s); } } } void VirtKeyboardShow() { if(vkb.surface[0].s == NULL) { LockVideo(); if(VirtKeyboardLoading(0) < 0) { UnlockVideo(); return; } UnlockVideo(); } vkb.visible = 1; vkb.redraw = 1; SDL_DC_EmulateMouse(SDL_FALSE); SetEventState(vkb.video, EVENT_STATE_ACTIVE); } void VirtKeyboardHide() { vkb.visible = 0; vkb.redraw = 0; SetEventState(vkb.video, EVENT_STATE_SLEEP); VirtKeyboardUpdateWorkPlace(); if(!ConsoleIsVisible()) { SDL_DC_EmulateMouse(SDL_TRUE); } } int VirtKeyboardIsVisible() { return vkb.visible; } void VirtKeyboardToggle() { if(!vkb.visible) VirtKeyboardShow(); else VirtKeyboardHide(); } static virt_kb_surface_t *VirtKeyboardGetSurface() { return &vkb.surface[vkb.cur_surf]; } static void VirtKeyboardUpdateWorkPlace() { VideoEventUpdate_t area; virt_kb_surface_t *surf = VirtKeyboardGetSurface(); SDL_Surface *DScreen = GetScreen(); area.x = DScreen->w - surf->s->w - VKB_DRAW_PADDING; area.y = VKB_DRAW_PADDING; area.w = surf->s->w; area.h = surf->s->h; ProcessVideoEventsUpdate(&area); } static void VirtKeyboardResize() { int i; LockVideo(); for(i = 0; i < VIRT_KB_SURFACE_COUNT; i++) { if(vkb.surface[i].s != NULL) { if(vkb.surface[i].zoom < 2.0f) { vkb.surface[i].zoom += 0.2f; } else { VirtKeyboardLoading(1); VirtKeyboardUpdateWorkPlace(); VirtKeyboardReDraw(); UnlockVideo(); return; } SDL_Surface *s = zoomSurface(vkb.surface[i].s, 1.2f, 1.2f, 1); if(s == NULL) { ds_printf("DS_ERROR: Virtual keyboard zoom error\n"); } else { SDL_FreeSurface(vkb.surface[i].s); vkb.surface[i].s = s; } } } vkb.redraw = 1; UnlockVideo(); } static void VirtKeyboardSetSurface(int index) { vkb.cur_surf = index; } void VirtKeyboardReDraw() { vkb.redraw = 1; } static void VirtKeyboardDraw(void *ds_event, void *param, int action) { if(action == EVENT_ACTION_RENDER && vkb.redraw) { ConsoleInformation *DSConsole = GetConsole(); SDL_Surface *DScreen = GetScreen(); SDL_Surface *dst = DSConsole->Visible != CON_CLOSED ? DSConsole->ConsoleSurface : DScreen; virt_kb_surface_t *surf = VirtKeyboardGetSurface(); SDL_Rect dest; dest.x = dst->w - surf->s->w - VKB_DRAW_PADDING; dest.y = VKB_DRAW_PADDING; int box_w = (surf->s->h / 3) - 1; int box_h = (surf->s->w / 3) - 1; if(surf->zoom > 1.0f) { box_w += surf->zoom; box_h += surf->zoom; } //SDL_FillRect(scr, 0, SDL_MapRGBA(scr->format, 250, 250, 250, 0)); SDL_BlitSurface(surf->s, NULL, dst, &dest); boxRGBA(dst, dest.x + (box_w * vkb.col) + vkb.col, dest.y + (box_h * vkb.row) + vkb.row, dest.x + (box_w * vkb.col) + box_w, dest.y + (box_h * vkb.row) + box_h, (vkb.clr >> 24) & 0xff, (vkb.clr >> 16) & 0xff, (vkb.clr >> 8) & 0xff, (vkb.clr >> 0) & 0xff); vkb.redraw = 0; if(DSConsole->Visible != CON_CLOSED) // WasUnicode used now as async update DSConsole->WasUnicode = 1; //CON_UpdateConsole(DSConsole); else ScreenChanged(); } else if(action == EVENT_ACTION_UPDATE) { //if(param == NULL) { VirtKeyboardReDraw(); SDL_DC_EmulateMouse(SDL_FALSE); // Console can switch on this feature. //} else { /* VideoEventUpdate_t *area = (VideoEventUpdate_t *)param; virt_kb_surface_t *surf = VirtKeyboardGetSurface(); x = DScreen->w - surf->s->w - VKB_DRAW_PADDING; y = VKB_DRAW_PADDING; */ //} } } static int ButtonToKey(int but) { int key = 0; switch(but) { case 1: key = 2; break; case 2: key = 3; break; case 5: key = 1; break; case 6: key = 0; break; default: break; } return VirtKeyboardKeySyms[vkb.cur_surf].sections[(vkb.row*3) + vkb.col].keys[key]; } static void VirtKeyboardEvent(void *ds_event, void *param, int action) { SDL_Event *event = (SDL_Event *) param; if(VirtKeyboardIsVisible()) { switch(event->type) { case SDL_KEYDOWN: switch(event->key.keysym.sym) { case SDLK_F1: case SDLK_ESCAPE: VirtKeyboardReDraw(); default: break; } break; case SDL_JOYBUTTONDOWN: switch(event->jbutton.button) { case 1: case 2: case 5: case 6: vkb.event.key.keysym.sym = ButtonToKey(event->jbutton.button); switch(vkb.event.key.keysym.sym) { case SDLK_LCTRL: vkb.event.key.keysym.mod |= KMOD_CTRL; vkb.event.key.keysym.sym = SDLK_c; break; case SDLK_BACKSPACE: case SDLK_RETURN: case SDLK_ESCAPE: case SDLK_DELETE: vkb.event.key.keysym.mod = 0; break; case SDLK_TAB: vkb.event.key.keysym.mod = 0; vkb.event.key.keysym.unicode = '_'; vkb.event.key.keysym.sym = SDLK_UNDERSCORE; break; default: vkb.event.key.keysym.unicode = vkb.event.key.keysym.sym; vkb.event.key.keysym.sym = 0; vkb.event.key.keysym.mod = 0; break; } SDL_PushEvent(&vkb.event); vkb.clr = 0xFD241F7F; VirtKeyboardReDraw(); break; case 3: VirtKeyboardHide(); break; } /* * 1 - B * 6 - X * 5 - Y * 2 - A * 3 - START */ break; case SDL_JOYBUTTONUP: vkb.clr = 0x0000007F; VirtKeyboardReDraw(); break; case SDL_JOYHATMOTION: switch(event->jhat.value) { case 0x0E: vkb.event.key.keysym.sym = SDLK_UP; break; case 0x0B: vkb.event.key.keysym.sym = SDLK_DOWN; break; case 0x07: vkb.event.key.keysym.sym = SDLK_LEFT; break; case 0x0D: vkb.event.key.keysym.sym = SDLK_RIGHT; break; } vkb.event.key.keysym.unicode = 0; vkb.event.key.keysym.mod = 0; //vkb.event->motion.x = 0; //vkb.event->motion.y = 0; SDL_PushEvent(&vkb.event); break; case SDL_MOUSEMOTION: event->type = 0; break; case SDL_JOYAXISMOTION: switch(event->jaxis.axis) { case 0: if(event->jaxis.value < -64) { vkb.col = 0; } else if(event->jaxis.value > 64) { vkb.col = 2; } else { vkb.col = 1; } break; case 1: if(event->jaxis.value < -64) { vkb.row = 0; } else if(event->jaxis.value > 64) { vkb.row = 2; } else { vkb.row = 1; } break; case 2: // rtrig if(event->jaxis.value) { VirtKeyboardSetSurface(VIRT_KB_SURFACE_KEYS_CAPS); } else { VirtKeyboardSetSurface(VIRT_KB_SURFACE_KEYS); } break; case 3: //ltrig if(event->jaxis.value) { if(vkb.cur_surf == VIRT_KB_SURFACE_KEYS_CAPS) { VirtKeyboardResize(); break; } VirtKeyboardSetSurface(VIRT_KB_SURFACE_NUMS); } else { VirtKeyboardSetSurface(VIRT_KB_SURFACE_KEYS); } break; } VirtKeyboardReDraw(); break; default: break; } } else { if(event->type == SDL_JOYBUTTONDOWN && event->jbutton.button == 3) { VirtKeyboardToggle(); } } } <file_sep>/modules/luaTask/src/queue.c /* ** $Id: queue.c 10 2007-09-15 19:37:27Z danielq $ ** Queue Management: Implementation ** SoongSoft, Argentina ** http://www.soongsoft.com mailto:<EMAIL> ** Copyright (C) 2003-2006 <NAME>. All rights reserved. */ #ifdef _WIN32 # include <windows.h> #ifndef NATV_WIN32 #include <pthread.h> #endif #else # include <unistd.h> # include <strings.h> # include <pthread.h> #endif #include <stdlib.h> #include "syncos.h" #include "queue.h" #if !defined(_WIN32) && !defined(_arch_dreamcast) # define QUEUE_PIPE_IN 0 # define QUEUE_PIPE_OUT 1 #endif static int InsertMsgAtQueueTail( QUEUE *pQueue, void *pMsg) { QMSG *pQMsg; pQMsg = ( QMSG *) calloc( 1, sizeof( QMSG)); pQMsg->pMsg = pMsg; if( pQueue->qMsgHead == NULL) { pQueue->qMsgHead = pQMsg; pQueue->qMsgTail = pQMsg; } else { pQueue->qMsgTail->next = pQMsg; pQueue->qMsgTail = pQMsg; } pQueue->msgcount++; return( 0); } static QMSG * RemoveMsgFromQueueHead( QUEUE *pQueue) { QMSG *pQMsg; pQMsg = pQueue->qMsgHead; if( pQueue->qMsgHead == pQueue->qMsgTail) { pQueue->qMsgTail = NULL; } pQueue->qMsgHead = pQueue->qMsgHead->next; pQueue->msgcount--; return( pQMsg); } int QueDestroy( QUEUE *pQueue) { while( pQueue->qMsgHead != NULL) { QMSG *pQMsg; pQMsg = RemoveMsgFromQueueHead( pQueue); free( pQMsg->pMsg); free( pQMsg); } #ifdef _WIN32 CloseHandle( pQueue->qNotEmpty); if( pQueue->qNotFull != NULL) CloseHandle( pQueue->qNotFull); CloseHandle( pQueue->qMutex); #elif defined(_arch_dreamcast) sem_destroy( pQueue->qNotEmpty); if( pQueue->qNotFull != NULL) sem_destroy( pQueue->qNotFull); #else close( pQueue->qNotEmpty[QUEUE_PIPE_IN]); close( pQueue->qNotEmpty[QUEUE_PIPE_OUT]); #endif return( 0); } int _QueGet( QUEUE *pQueue, void **ppMsg) { QMSG *pQMsg; OsLockMutex( ( void *) pQueue->qMutex, INFINITE); pQMsg = RemoveMsgFromQueueHead( pQueue); OsUnlockMutex( ( void *) pQueue->qMutex); if( pQueue->qMax != QUE_NO_LIMIT) { #ifdef _WIN32 ReleaseSemaphore( pQueue->qNotFull, 1, NULL); #elif defined(_arch_dreamcast) sem_signal(pQueue->qNotFull); #endif } #if !defined(_WIN32) && !defined(_arch_dreamcast) { char b; read( pQueue->qNotEmpty[QUEUE_PIPE_IN], &b, 1); } #endif *ppMsg = pQMsg->pMsg; free( pQMsg); return( 0); } int QueGet( QUEUE *pQueue, void **ppMsg) { #ifdef _WIN32 WaitForSingleObject( pQueue->qNotEmpty, INFINITE); #elif defined(_arch_dreamcast) sem_wait(pQueue->qNotEmpty); #endif return( _QueGet( pQueue, ppMsg)); } int QuePut( QUEUE *pQueue, void *pMsg) { if( pQueue->qMax != QUE_NO_LIMIT) { /* bounded queue */ #ifdef _WIN32 WaitForSingleObject( pQueue->qNotFull, INFINITE); #elif defined(_arch_dreamcast) sem_wait(pQueue->qNotFull); #endif } OsLockMutex( ( void *) pQueue->qMutex, INFINITE); InsertMsgAtQueueTail( pQueue, pMsg); OsUnlockMutex( ( void *) pQueue->qMutex); #ifdef _WIN32 ReleaseSemaphore( pQueue->qNotEmpty, 1, NULL); #elif defined(_arch_dreamcast) sem_signal(pQueue->qNotEmpty); #else { char b; write( pQueue->qNotEmpty[QUEUE_PIPE_OUT], &b, 1); } #endif return( 0); } int QueCreate( QUEUE *pQueue, int qLimit ) { pQueue->qMutex = OsCreateMutex( NULL); #ifdef _WIN32 pQueue->qNotEmpty = CreateSemaphore( NULL, 0, 0x7fffffff, NULL); #elif defined(_arch_dreamcast) pQueue->qNotEmpty = sem_create(0); #else if( pipe(pQueue->qNotEmpty)) { return( -1); } #endif if( qLimit != QUE_NO_LIMIT) { #ifdef _WIN32 pQueue->qNotFull = CreateSemaphore( NULL, qLimit, 0x7fffffff, NULL); } else pQueue->qNotFull = NULL; #elif defined(_arch_dreamcast) pQueue->qNotFull = sem_create(qLimit); } else pQueue->qNotFull = NULL; #else } else pQueue->qNotFull = 0; #endif pQueue->qMax = qLimit; pQueue->qMsgHead = NULL; pQueue->qMsgTail = NULL; pQueue->msgcount = 0; return( 0); } long GetQueNotEmptyHandle( QUEUE *pQueue) { #if defined(_WIN32) || defined(_arch_dreamcast) return( ( long) ( pQueue->qNotEmpty)); #else return( ( long) ( pQueue->qNotEmpty[QUEUE_PIPE_IN])); #endif } <file_sep>/firmware/aica/codec/fileinfo.c /* Copyright (C) 2006 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <stdio.h> #include <string.h> #include <assert.h> #ifdef ARM #include "ff.h" #include "profile.h" #include "heapsort.h" #else #include "fatfs/integer.h" #define FIL FILE #define iprintf printf #endif #include "fileinfo.h" #define MIN(x,y) ( ((x) < (y)) ? (x) : (y) ) char *memstr(char *haystack, char *needle, int size) { char *p; char needlesize = strlen(needle); for (p = haystack; p <= (haystack-needlesize+size); p++) { if (memcmp(p, needle, needlesize) == 0) return p; /* found */ } return NULL; } #ifdef ARM void songlist_build(SONGLIST *songlist) { DIR dir; FILINFO fileinfo; SONGINFO songinfo; // build song list unsigned int song_index = 0; memset(songlist, 0, sizeof(SONGLIST)); memset(&dir, 0, sizeof(DIR)); assert(f_opendir(&dir, "/") == FR_OK); while ( f_readdir( &dir, &fileinfo ) == FR_OK && fileinfo.fname[0] ) { iprintf( "%s ( %li bytes )\n" , fileinfo.fname, fileinfo.fsize ) ; if (get_filetype(fileinfo.fname) == MP3 || get_filetype(fileinfo.fname) == MP4 || get_filetype(fileinfo.fname) == MP2) { // save filename in list strncpy(songlist->list[song_index].filename, fileinfo.fname, sizeof(songlist->list[song_index].filename)); // try to read song info or don't save this entry if (read_song_info_for_song(&(songlist->list[song_index]), &songinfo) == 0) { song_index++; } } songlist->size = song_index; } } void songlist_sort(SONGLIST *songlist) { PROFILE_START("sorting song list"); heapsort(songlist->list, songlist->size, sizeof(songlist->list[0]), (void *)compar_song); PROFILE_END(); } #endif char* skip_artist_prefix(char* s) { if(strstr(s, "The ") || strstr(s, "Die ")) { return s + 4; } else { return s; } } #ifdef ARM // compare two songs to determine the sorting order int compar_song(SONGFILE *a, SONGFILE *b) { SONGINFO songinfo; char str_a[30], str_b[30]; memset(str_a, 0, sizeof(str_a)); memset(str_b, 0, sizeof(str_b)); memset(&songinfo, 0, sizeof(SONGINFO)); assert(read_song_info_for_song(a, &songinfo) == 0); strncpy(str_a, skip_artist_prefix(songinfo.artist), sizeof(str_a)-1); memset(&songinfo, 0, sizeof(SONGINFO)); assert(read_song_info_for_song(b, &songinfo) == 0); strncpy(str_b, skip_artist_prefix(songinfo.artist), sizeof(str_b)-1); //iprintf("comparing %s <-> %s: %d\n", str_a, str_b, strncasecmp(str_a, str_b, MIN(sizeof(str_a), sizeof(str_b)))); return strncasecmp(str_a, str_b, MIN(sizeof(str_a), sizeof(str_b))); } enum filetypes get_filetype(char * filename) { char *extension; extension = strrchr(filename, '.') + 1; if(strncasecmp(extension, "MP2", 3) == 0) { return MP2; } else if (strncasecmp(extension, "MP3", 3) == 0) { return MP3; } else if (strncasecmp(extension, "MP4", 3) == 0 || strncasecmp(extension, "M4A", 3) == 0) { return MP4; } else if (strncasecmp(extension, "AAC", 3) == 0) { return AAC; } else if (strncasecmp(extension, "WAV", 3) == 0 || strncasecmp(extension, "RAW", 3) == 0) { return WAV; } else { return UNKNOWN; } } int read_song_info_for_song(SONGFILE *song, SONGINFO *songinfo) { FIL _file; enum filetypes type = UNKNOWN; int result = -1; memset(&_file, 0, sizeof(FIL)); assert(f_open(&_file, get_full_filename(song->filename), FA_OPEN_EXISTING|FA_READ) == FR_OK); type = get_filetype(get_full_filename(song->filename)); songinfo->type = type; if (type == MP4) { result = read_song_info_mp4(&_file, songinfo); } else if (type == MP3) { result = read_song_info_mp3(&_file, songinfo); } else { result = -1; } assert(songinfo->type != 0); assert(f_close(&_file) == FR_OK); return result; } #endif /*int read_song_info(FIL *file, SONGINFO *songinfo) { }*/ int read_song_info_mp4(FIL *file, SONGINFO *songinfo) { char buffer[3000]; char *p; long data_offset = 0; WORD bytes_read; memset(songinfo, 0, sizeof(SONGINFO)); songinfo->type = MP4; for(int n=0; n<100; n++) { assert(f_read(file, buffer, sizeof(buffer), &bytes_read) == FR_OK); p = memstr(buffer, "mdat", sizeof(buffer)); if(p != NULL) { data_offset = (p - buffer) + file->fptr - bytes_read + 4; iprintf("found mdat atom data at 0x%lx\n", data_offset); break; } else { // seek backwards //assert(f_lseek(file, file->fptr - 4) == FR_OK); } } if(data_offset == 0) { puts("couldn't find mdat atom"); return -1; } assert(f_lseek(file, data_offset) == FR_OK); songinfo->data_start = data_offset; return 0; } int read_song_info_mp3(FIL *file, SONGINFO *songinfo) { BYTE id3buffer[3000]; WORD bytes_read; memset(songinfo, 0, sizeof(SONGINFO)); songinfo->type = MP3; // try ID3v2 #ifdef ARM assert(f_read(file, id3buffer, sizeof(id3buffer), &bytes_read) == FR_OK); #else fread(id3buffer, 1, sizeof(id3buffer), file); #endif if (strncmp("ID3", id3buffer, 3) == 0) { DWORD tag_size, frame_size; BYTE version_major, version_release, extended_header; int frame_header_size; DWORD i; tag_size = ((DWORD)id3buffer[6] << 21)|((DWORD)id3buffer[7] << 14)|((WORD)id3buffer[8] << 7)|id3buffer[9]; songinfo->data_start = tag_size; version_major = id3buffer[3]; version_release = id3buffer[4]; extended_header = id3buffer[5] & (1<<6); //iprintf("found ID3 version 2.%x.%x, length %lu, extended header: %i\n", version_major, version_release, tag_size, extended_header); if (version_major >= 3) { frame_header_size = 10; } else { frame_header_size = 6; } i = 10; // iterate through frames while (i < MIN(tag_size, sizeof(id3buffer))) { //puts(id3buffer + i); if (version_major >= 3) { frame_size = ((DWORD)id3buffer[i + 4] << 24)|((DWORD)id3buffer[i + 5] << 16)|((WORD)id3buffer[i + 6] << 8)|id3buffer[i + 7]; } else { frame_size = ((DWORD)id3buffer[i + 3] << 14)|((WORD)id3buffer[i + 4] << 7)|id3buffer[i + 5]; } //iprintf("frame size: %lu\n", frame_size); if (strncmp("TT2", id3buffer + i, 3) == 0 || strncmp("TIT2", id3buffer + i, 4) == 0) { strncpy(songinfo->title, id3buffer + i + frame_header_size + 1, MIN(frame_size - 1, sizeof(songinfo->title) - 1)); } else if (strncmp("TP1", id3buffer + i, 3) == 0 || strncmp("TPE1", id3buffer + i, 4) == 0) { strncpy(songinfo->artist, id3buffer + i + frame_header_size + 1, MIN(frame_size - 1, sizeof(songinfo->artist) - 1)); } else if (strncmp("TAL", id3buffer + i, 3) == 0) { strncpy(songinfo->album, id3buffer + i + frame_header_size + 1, MIN(frame_size - 1, sizeof(songinfo->album) - 1)); } i += frame_size + frame_header_size; /* doesn't work when frame is too large if (sizeof(id3buffer) - i < 500) { puts("refilling buffer"); memmove(id3buffer, id3buffer + i, sizeof(id3buffer) - i); #ifdef ARM assert(f_read(file, id3buffer + i, sizeof(id3buffer) - i, &bytes_read) == FR_OK); #else fread(id3buffer + i, 1, sizeof(id3buffer) - i, file); #endif i = 0; } */ } } else { // try ID3v1 #ifdef ARM assert(f_lseek(file, file->fsize - 128) == FR_OK); assert(f_read(file, id3buffer, 128, &bytes_read) == FR_OK); #endif if (strncmp("TAG", id3buffer, 3) == 0) { strncpy(songinfo->title, id3buffer + 3, MIN(30, sizeof(songinfo->title) - 1)); strncpy(songinfo->artist, id3buffer + 3 + 30, MIN(30, sizeof(songinfo->artist) - 1)); strncpy(songinfo->album, id3buffer + 3 + 60, MIN(30, sizeof(songinfo->album) - 1)); //iprintf("found ID3 version 1\n"); } songinfo->data_start = 0; } return 0; } char * get_full_filename(char * filename) { static char full_filename[14]; full_filename[0] = '/'; strncpy(full_filename + 1, filename, 12); full_filename[13] = '\0'; return full_filename; } #ifndef ARM int main(int argc, char *argv[]) { FILE *fp; SONGINFO songinfo; if (argc != 2) { puts("usage: program filename"); return 1; } memset(&songinfo, 0, sizeof(SONGINFO)); fp = fopen(argv[1], "r"); read_song_info(fp, &songinfo); puts(songinfo.title); puts(songinfo.artist); puts(songinfo.album); return 0; } #endif <file_sep>/applications/gdplay/modules/module.c /* DreamShell ##version## module.c - GDPlay app module Copyright (C)2014 megavolt85 */ #include "ds.h" #include <dc/sound/sound.h> DEFAULT_MODULE_EXPORTS(app_gdplay); typedef struct ip_meta { char hardware_ID[16]; char maker_ID[16]; char ks[5]; char disk_type[6]; char disk_num[5]; char country_codes[8]; char ctrl[4]; char dev[1]; char VGA[1]; char WinCE[1]; char unk[1]; char product_ID[10]; char product_version[6]; char release_date[8]; char unk2[8]; char boot_file[16]; char software_maker_info[16]; char title[128]; } ip_meta_t; enum { SURF_GDROM = 0, SURF_MILCD = 1, SURF_AUDIOCD = 2, SURF_CDROM = 3, SURF_NODISC = 4, SURF_ONCD = 5, }; enum { TXT_REGION = 0, TXT_VGA = 1, TXT_DATE = 2, TXT_DISCNUM = 3, TXT_VERSION = 4, TXT_TITLE1 = 5, TXT_TITLE2 = 6, TXT_TITLE3 = 7, TXT_TITLE4 = 8, TXT_TITLE5 = 9, TXT_END = 10, }; #define COLUMN_LEN 26 static struct self { App_t *app; ip_meta_t *info; GUI_Widget *play_btn; GUI_Widget *text[10]; GUI_Surface *gdtex[6]; GUI_Surface *play; void *bios_patch; } self; kthread_t *check_gdrom_thd; int kill_gdrom_thd = 0; void gdplay_run_game(void *param); static void clear_text(void) { int i; for(i=0; i<TXT_END; i++) GUI_LabelSetText(self.text[i], " "); self.info = NULL; } static char *trim_spaces(char *txt, int len) { int32_t i; while(txt[0] == ' ') { txt++; } if(!len) len = strlen(txt); for(i=len; i ; i--) { if(txt[i] > ' ') break; txt[i] = '\0'; } return txt; } static void set_img(GUI_Surface *surface, int enable) { GUI_ButtonSetNormalImage(self.play_btn, surface); GUI_ButtonSetHighlightImage(self.play_btn, self.play); GUI_ButtonSetPressedImage(self.play_btn, surface); GUI_ButtonSetDisabledImage(self.play_btn, surface); GUI_WidgetSetEnabled(self.play_btn, enable); // self.rotate = surface; } static void set_info(int disc_type) { int lba = 45150; char pbuff[2048]; if(FileExists("/cd/0gdtex.pvr")) { self.gdtex[SURF_ONCD] = GUI_SurfaceLoad("/cd/0gdtex.pvr"); set_img(self.gdtex[SURF_ONCD], 1); } else { set_img(self.gdtex[(disc_type == CD_CDROM_XA)], 1); } if(disc_type == CD_CDROM_XA) { CDROM_TOC toc; if(cdrom_read_toc(&toc, 0) != CMD_OK) { set_img(self.gdtex[SURF_CDROM], 0); ds_printf("DS_ERROR: Toc read error\n"); return; } if(!(lba = cdrom_locate_data_track(&toc))) { set_img(self.gdtex[SURF_CDROM], 0); ds_printf("DS_ERROR: Error locate data track\n"); return; } } if (cdrom_read_sectors(pbuff,lba , 1)) { ds_printf("DS_ERROR: CD read error %d\n",lba); set_img(self.gdtex[SURF_CDROM], 0); return; } self.info = (ip_meta_t *) pbuff; if(strncmp(self.info->hardware_ID, "SEGA", 4)) { set_img(self.gdtex[SURF_CDROM], 0); return; } char tmp[NAME_MAX]; if(strlen(trim_spaces(self.info->country_codes, sizeof(self.info->country_codes))) > 1) { strcpy(tmp, "FREE"); } else { switch(self.info->country_codes[0]) { case 'J': strcpy(tmp, "JAPAN"); break; case 'U': strcpy(tmp, "USA"); break; case 'E': strcpy(tmp, "EUROPE"); break; } } GUI_LabelSetText(self.text[TXT_REGION], tmp); GUI_LabelSetText(self.text[TXT_VGA], self.info->VGA[0] == '1'? "YES":"NO"); memset(tmp, 0, NAME_MAX); snprintf(tmp, COLUMN_LEN, "%c%c%c%c-%c%c-%c%c", self.info->release_date[0], self.info->release_date[1], self.info->release_date[2], self.info->release_date[3], self.info->release_date[4], self.info->release_date[5], self.info->release_date[6], self.info->release_date[7]); GUI_LabelSetText(self.text[TXT_DATE], trim_spaces(tmp, 8)); snprintf(tmp, COLUMN_LEN, "%c OF %c", self.info->disk_num[0], self.info->disk_num[2]); GUI_LabelSetText(self.text[TXT_DISCNUM], tmp); memset(tmp, 0, NAME_MAX); memcpy(tmp, self.info->product_version, 6); GUI_LabelSetText(self.text[TXT_VERSION], tmp); memset(tmp, 0, NAME_MAX); strncpy(tmp, trim_spaces(self.info->title, 128), 128); int num_column = strlen(tmp) / COLUMN_LEN; if((strlen(tmp) % COLUMN_LEN)) num_column++; char column_txt[COLUMN_LEN+1]; for(int i=0; i<num_column; i++) { strncpy(column_txt, &tmp[i*COLUMN_LEN], COLUMN_LEN); GUI_LabelSetText(self.text[TXT_TITLE1 + i], column_txt); } } static void check_cd(void) { int status, disc_type, cd_status; clear_text(); getstatus: if((cd_status = cdrom_get_status(&status, &disc_type)) != ERR_OK) { switch(cd_status) { case ERR_DISC_CHG: cdrom_reinit(); goto getstatus; break; default: set_img(self.gdtex[SURF_NODISC], 0); return; } } switch(status) { case CD_STATUS_OPEN: case CD_STATUS_NO_DISC: set_img(self.gdtex[SURF_NODISC], 0); return; } switch(disc_type) { case CD_CDDA: set_img(self.gdtex[SURF_AUDIOCD], 0); break; case CD_GDROM: case CD_CDROM_XA: set_info(disc_type); break; case CD_CDROM: case CD_CDI: default: set_img(self.gdtex[SURF_CDROM], 0); break; } cdrom_spin_down(); } static void *check_gdrom() { int status, disc_type, cd_status; while(!kill_gdrom_thd) { cd_status = cdrom_get_status(&status, &disc_type); switch(cd_status) { case ERR_DISC_CHG: check_cd(); break; default: switch(status) { case CD_STATUS_OPEN: case CD_STATUS_NO_DISC: if(self.info) clear_text(); set_img(self.gdtex[SURF_NODISC], 0); break; default: if(!self.info) check_cd(); break; } } thd_pass(); } return NULL; } /* int rotate_en = 0; kthread_t *rotate_thd; static void *rotate_gdtex() { SDL_Surface *surf; rotate_en = 1; while(rotate_en) { surf = GUI_SurfaceGet(self.rotate); GUI_Surface *s = GUI_SurfaceFrom("rotated-surface", rotozoomSurface(surf, 1.0, 1.0, 1)); GUI_ButtonSetHighlightImage(self.play_btn, s); self.rotate = s; GUI_WidgetMarkChanged(self.app->body); } return NULL; } void gdplay_rotate_on(GUI_Widget *widget) { (void) widget; ds_printf("gdplay_rotate_on\n"); if(!rotate_en) rotate_thd = thd_create(1, rotate_gdtex, NULL); } void gdplay_rotate_off(GUI_Widget *widget) { (void) widget; ds_printf("gdplay_rotate_off\n"); rotate_en = 0; thd_join(rotate_thd, NULL); } */ void gdplay_play(GUI_Widget *widget) { (void) widget; kill_gdrom_thd = 1; thd_join(check_gdrom_thd, NULL); ShutdownDS(); arch_shutdown(); gdplay_run_game(self.bios_patch); } void gdplay_Init(App_t *app) { if(app != NULL) { memset(&self, 0, sizeof(self)); self.app = app; self.play_btn = APP_GET_WIDGET("play-btn"); self.text[TXT_REGION] = APP_GET_WIDGET("region-txt"); self.text[TXT_VGA] = APP_GET_WIDGET("vga-txt"); self.text[TXT_DATE] = APP_GET_WIDGET("date-txt"); self.text[TXT_DISCNUM] = APP_GET_WIDGET("disk-num-txt"); self.text[TXT_VERSION] = APP_GET_WIDGET("version-txt"); self.text[TXT_TITLE1] = APP_GET_WIDGET("title1-txt"); self.text[TXT_TITLE2] = APP_GET_WIDGET("title2-txt"); self.text[TXT_TITLE3] = APP_GET_WIDGET("title3-txt"); self.text[TXT_TITLE4] = APP_GET_WIDGET("title4-txt"); self.text[TXT_TITLE5] = APP_GET_WIDGET("title5-txt"); self.gdtex[SURF_GDROM] = APP_GET_SURFACE("gdrom"); self.gdtex[SURF_MILCD] = APP_GET_SURFACE("milcd"); self.gdtex[SURF_AUDIOCD]= APP_GET_SURFACE("cdaudio"); self.gdtex[SURF_CDROM] = APP_GET_SURFACE("cdrom"); self.gdtex[SURF_NODISC] = APP_GET_SURFACE("nodisc"); self.play = APP_GET_SURFACE("play"); char path[NAME_MAX]; snprintf(path, NAME_MAX, "%s/firmware/rungd.bin", getenv("PATH")); FILE *f = fopen(path, "rb"); if(!f) { ds_printf("DS_ERROR: Can't open %s\n", path); ShowConsole(); return; } self.bios_patch = memalign(32, 65280); fread(self.bios_patch, 65280, 1, f); fclose(f); check_cd(); check_gdrom_thd = thd_create(1, check_gdrom, NULL); } else { ds_printf("DS_ERROR: %s: Attempting to call %s is not by the app initiate.\n", lib_get_name(), __func__); } } void gdplay_Exit() { /* rotate_en = 0; thd_join(rotate_thd, NULL); */ kill_gdrom_thd = 1; thd_join(check_gdrom_thd, NULL); if(self.bios_patch) free(self.bios_patch); } <file_sep>/modules/ogg/liboggvorbis/liboggvorbis/Makefile # KallistiOS Ogg/Vorbis Decoder Library # # Library Makefile # (c)2001 <NAME> # Based on KOS Makefiles by <NAME> OBJS = SUBDIRS = libogg libvorbis all: subdirs liboggvorbis.a # Target: liboggvorbis.a -> base library for OggVobis Files liboggvorbis.a: -rm -f ./build/*.o -cp ./libvorbis/build/*.o ./build/ -cp ./libogg/build/*.o ./build/ # $(KOS_AR) rcs ./lib/liboggvorbis.a ./build/*.o # Target: liboggvorbisplay.a -> KOS sndstream decoder library liboggvorbisplay.a: -rm -f ./build/*.o -cp ./libvorbis/build/*.o build/ -cp ./libogg/build/*.o build/ -cp ../libsndoggvorbis/build/*.o build/ $(KOS_AR) rcs ./lib/liboggvorbisplay.a build/*.o include ../../../../sdk/Makefile.library clean: clean_subdirs -rm -f build/*.o lib/*.a run: <file_sep>/lib/libparallax/include/dr.h /* Parallax for KallistiOS ##version## dr.h (c)2002 <NAME> */ #ifndef __PARALLAX_DR #define __PARALLAX_DR #include <sys/cdefs.h> __BEGIN_DECLS /** \file Direct render stuff. This, like matrix.h, is just here to try to keep client code as platform independent as possible for porting. This will pretty much all get optimized out by the compiler. */ #include <dc/pvr.h> typedef pvr_dr_state_t plx_dr_state_t; typedef pvr_vertex_t plx_vertex_t; #define PLX_VERT PVR_CMD_VERTEX #define PLX_VERT_EOS PVR_CMD_VERTEX_EOL #define plx_dr_init(a) pvr_dr_init(*a) #define plx_dr_target(a) pvr_dr_target(*a) #define plx_dr_commit(a) pvr_dr_commit(a) #define plx_prim pvr_prim static inline void plx_scene_begin() { pvr_wait_ready(); pvr_scene_begin(); } static inline void plx_list_begin(int type) { pvr_list_begin(type); } static inline void plx_scene_end() { pvr_scene_finish(); } __END_DECLS #endif /* __PARALLAX_DR */ <file_sep>/lib/libparallax/src/context.c /* Parallax for KallistiOS ##version## context.c (c)2002 <NAME> */ #include <assert.h> #include <stdio.h> #include <string.h> #include <plx/context.h> /* See the header file for all comments and documentation */ /* Our working context and header */ static pvr_poly_cxt_t cxt_working; static pvr_poly_hdr_t hdr_working_op, hdr_working_tr, hdr_working_pt; static void compile_cxts() { cxt_working.list_type = PVR_LIST_OP_POLY; cxt_working.gen.alpha = PVR_ALPHA_DISABLE; cxt_working.txr.env = PVR_TXRENV_MODULATE; pvr_poly_compile(&hdr_working_op, &cxt_working); cxt_working.list_type = PVR_LIST_TR_POLY; cxt_working.gen.alpha = PVR_ALPHA_ENABLE; cxt_working.txr.env = PVR_TXRENV_MODULATEALPHA; pvr_poly_compile(&hdr_working_tr, &cxt_working); cxt_working.list_type = PVR_LIST_PT_POLY; cxt_working.gen.alpha = PVR_ALPHA_ENABLE; cxt_working.txr.env = PVR_TXRENV_MODULATEALPHA; pvr_poly_compile(&hdr_working_pt, &cxt_working); } void plx_cxt_init() { pvr_poly_cxt_col(&cxt_working, PVR_LIST_TR_POLY); cxt_working.gen.culling = PVR_CULLING_NONE; } void plx_cxt_texture(plx_texture_t * txr) { if (txr) { memcpy_sh4(&cxt_working.txr, &txr->cxt_opaque.txr, sizeof(cxt_working.txr)); cxt_working.txr.enable = PVR_TEXTURE_ENABLE; } else { cxt_working.txr.enable = PVR_TEXTURE_DISABLE; } compile_cxts(); } void plx_cxt_blending(int src, int dst) { cxt_working.blend.src = src; cxt_working.blend.dst = dst; compile_cxts(); } void plx_cxt_culling(int type) { cxt_working.gen.culling = type; compile_cxts(); } void plx_cxt_fog(int type) { cxt_working.gen.fog_type = type; compile_cxts(); } void plx_cxt_send(int type) { switch (type) { case PVR_LIST_OP_POLY: pvr_prim(&hdr_working_op, sizeof(pvr_poly_hdr_t)); break; case PVR_LIST_TR_POLY: pvr_prim(&hdr_working_tr, sizeof(pvr_poly_hdr_t)); break; case PVR_LIST_PT_POLY: pvr_prim(&hdr_working_pt, sizeof(pvr_poly_hdr_t)); break; default: assert_msg( 0, "List type not handled by plx_cxt_send" ); } } <file_sep>/lib/SDL_gui/Layout.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_Layout::GUI_Layout(const char *aname) : GUI_Object(aname) { } GUI_Layout::~GUI_Layout() { } void GUI_Layout::Layout(GUI_Container *container) { } <file_sep>/modules/luaGUI/Makefile # # luaGUI module for DreamShell # Copyright (C) 2007-2016 SWAT # http://www.dc-swat.ru # TARGET_NAME = luaGUI LUA_MODULE_NAME = GUI LUA_MODULE_OBJS = tolua_clean_$(LUA_MODULE_NAME).o OBJS = module.o DBG_LIBS = -lds -ltolua EXPORTS_FILE = exports.txt VER_MAJOR = 1 VER_MINOR = 0 VER_MICRO = 3 OLD_FUNC = tolua_function(tolua_S,"GUI_ NEW_FUNC = tolua_function(tolua_S," all: rm-elf include ../../sdk/Makefile.loadable tolua_clean_$(LUA_MODULE_NAME).c: tolua_$(LUA_MODULE_NAME).c sed 's/$(OLD_FUNC)/$(NEW_FUNC)/g' tolua_$(LUA_MODULE_NAME).c > tolua_clean_$(LUA_MODULE_NAME).c KOS_CFLAGS += -I$(DS_SDK)/include/lua rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/sdk/toolchain/ubuntu_build.sh #!/bin/bash # exports export SH_PREFIX=/opt/toolchains/dc/sh-elf export ARM_PREFIX=/opt/toolchains/dc/arm-eabi export KOS_ROOT=/usr/local/dc/kos export KOS_BASE=$KOS_ROOT/kos export KOS_PORTS=$KOS_ROOT/kos-ports # install deps and setup directories sudo apt-get update sudo apt-get install -y subversion build-essential gcc-4.7 make \ autoconf bison flex libelf-dev texinfo latex2html \ git wget sed lyx libjpeg62-dev libpng-dev sudo mkdir -p $KOS_ROOT sudo mkdir -p $SH_PREFIX/sh-elf/include sudo mkdir -p $ARM_PREFIX/share sudo chown -R $USER:$USER $ARM_PREFIX sudo chown -R $USER:$USER $SH_PREFIX sudo chown -R $USER:$USER $KOS_ROOT # clone kos git clone git://git.code.sf.net/p/cadcdev/kallistios kos git clone --recursive git://git.code.sf.net/p/cadcdev/kos-ports kos-ports cp -r kos $KOS_ROOT rm -rf kos cp -r kos-ports $KOS_ROOT rm -rf kos-ports # prepare ./download.sh ./unpack.sh cd gcc-9.3.0 ./contrib/download_prerequisites cd .. && make patch # build make -j9 build-sh4-binutils make -j9 build-sh4-gcc-pass1 make -j9 build-sh4-newlib-only make -j9 fixup-sh4-newlib make -j9 build-sh4-gcc-pass2 make -j9 build-arm-binutils make -j9 build-arm-gcc # env script cp $KOS_BASE/doc/environ.sh.sample $KOS_BASE/environ.sh sed -i 's/\/opt\/toolchains\/dc\/kos/\/usr\/local\/dc\/kos\/kos/g' $KOS_BASE/environ.sh source $KOS_BASE/environ.sh # build kos and kos-ports pushd `pwd` cd $KOS_BASE make -j9 cd $KOS_PORTS ./utils/build-all.sh popd <file_sep>/modules/mp3/libmp3/xingmp3/uph.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** uph.c *************************************************** Layer 3 audio huffman decode ******************************************************************/ #include <float.h> #include <math.h> #include "L3.h" #include "mhead.h" #ifdef _MSC_VER #pragma warning(disable: 4505) #endif /*===============================================================*/ /* max bits required for any lookup - change if htable changes */ /* quad required 10 bit w/signs must have (MAXBITS+2) >= 10 */ #define MAXBITS 9 static HUFF_ELEMENT huff_table_0[4] = {{0}, {0}, {0}, {64}}; /* dummy must not use */ #include "htable.h" /*-- 6 bit lookup (purgebits, value) --*/ static unsigned char quad_table_a[][2] = { {6, 11}, {6, 15}, {6, 13}, {6, 14}, {6, 7}, {6, 5}, {5, 9}, {5, 9}, {5, 6}, {5, 6}, {5, 3}, {5, 3}, {5, 10}, {5, 10}, {5, 12}, {5, 12}, {4, 2}, {4, 2}, {4, 2}, {4, 2}, {4, 1}, {4, 1}, {4, 1}, {4, 1}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 8}, {4, 8}, {4, 8}, {4, 8}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, }; typedef struct { HUFF_ELEMENT *table; int linbits; int ncase; } HUFF_SETUP; #define no_bits 0 #define one_shot 1 #define no_linbits 2 #define have_linbits 3 #define quad_a 4 #define quad_b 5 static HUFF_SETUP table_look[] = { {huff_table_0, 0, no_bits}, {huff_table_1, 0, one_shot}, {huff_table_2, 0, one_shot}, {huff_table_3, 0, one_shot}, {huff_table_0, 0, no_bits}, {huff_table_5, 0, one_shot}, {huff_table_6, 0, one_shot}, {huff_table_7, 0, no_linbits}, {huff_table_8, 0, no_linbits}, {huff_table_9, 0, no_linbits}, {huff_table_10, 0, no_linbits}, {huff_table_11, 0, no_linbits}, {huff_table_12, 0, no_linbits}, {huff_table_13, 0, no_linbits}, {huff_table_0, 0, no_bits}, {huff_table_15, 0, no_linbits}, {huff_table_16, 1, have_linbits}, {huff_table_16, 2, have_linbits}, {huff_table_16, 3, have_linbits}, {huff_table_16, 4, have_linbits}, {huff_table_16, 6, have_linbits}, {huff_table_16, 8, have_linbits}, {huff_table_16, 10, have_linbits}, {huff_table_16, 13, have_linbits}, {huff_table_24, 4, have_linbits}, {huff_table_24, 5, have_linbits}, {huff_table_24, 6, have_linbits}, {huff_table_24, 7, have_linbits}, {huff_table_24, 8, have_linbits}, {huff_table_24, 9, have_linbits}, {huff_table_24, 11, have_linbits}, {huff_table_24, 13, have_linbits}, {huff_table_0, 0, quad_a}, {huff_table_0, 0, quad_b}, }; /*========================================================*/ /*------------- get n bits from bitstream -------------*/ /* unused static unsigned int bitget(int n) { unsigned int x; if (bitdat.bits < n) { */ /* refill bit buf if necessary */ /* while (bitdat.bits <= 24) { bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; bitdat.bits += 8; } } bitdat.bits -= n; x = bitdat.bitbuf >> bitdat.bits; bitdat.bitbuf -= x << bitdat.bits; return x; } */ /*----- get n bits - checks for n+2 avail bits (linbits+sign) -----*/ static unsigned int bitget_lb(MPEG *m, int n) { unsigned int x; if (m->cupl.bitdat.bits < (n + 2)) { /* refill bit buf if necessary */ while (m->cupl.bitdat.bits <= 24) { m->cupl.bitdat.bitbuf = (m->cupl.bitdat.bitbuf << 8) | *m->cupl.bitdat.bs_ptr++; m->cupl.bitdat.bits += 8; } } m->cupl.bitdat.bits -= n; x = m->cupl.bitdat.bitbuf >> m->cupl.bitdat.bits; m->cupl.bitdat.bitbuf -= x << m->cupl.bitdat.bits; return x; } /*------------- get n bits but DO NOT remove from bitstream --*/ static unsigned int bitget2(MPEG *m, int n) { unsigned int x; if (m->cupl.bitdat.bits < (MAXBITS + 2)) { /* refill bit buf if necessary */ while (m->cupl.bitdat.bits <= 24) { m->cupl.bitdat.bitbuf = (m->cupl.bitdat.bitbuf << 8) | *m->cupl.bitdat.bs_ptr++; m->cupl.bitdat.bits += 8; } } x = m->cupl.bitdat.bitbuf >> (m->cupl.bitdat.bits - n); return x; } /*========================================================*/ /*========================================================*/ #define mac_bitget_check(n) if( m->cupl.bitdat.bits < (n) ) { \ while( m->cupl.bitdat.bits <= 24 ) { \ m->cupl.bitdat.bitbuf = (m->cupl.bitdat.bitbuf << 8) | \ *m->cupl.bitdat.bs_ptr++; \ m->cupl.bitdat.bits += 8; \ } \ } /*---------------------------------------------------------*/ #define mac_bitget2(n) (m->cupl.bitdat.bitbuf >> (m->cupl.bitdat.bits-n)); /*---------------------------------------------------------*/ #define mac_bitget(n) ( m->cupl.bitdat.bits -= n, \ code = m->cupl.bitdat.bitbuf >> m->cupl.bitdat.bits, \ m->cupl.bitdat.bitbuf -= code << m->cupl.bitdat.bits, \ code ) /*---------------------------------------------------------*/ #define mac_bitget_purge(n) m->cupl.bitdat.bits -= n, \ m->cupl.bitdat.bitbuf -= (m->cupl.bitdat.bitbuf >> m->cupl.bitdat.bits) \ << m->cupl.bitdat.bits; /*---------------------------------------------------------*/ #define mac_bitget_1bit() ( m->cupl.bitdat.bits--, \ code = m->cupl.bitdat.bitbuf >> m->cupl.bitdat.bits, \ m->cupl.bitdat.bitbuf -= code << m->cupl.bitdat.bits, \ code ) /*========================================================*/ /*========================================================*/ void unpack_huff(MPEG *m, int xy[][2], int n, int ntable) { int i; HUFF_ELEMENT *t; HUFF_ELEMENT *t0; int linbits; int bits; int code; int x, y; if (n <= 0) return; n = n >> 1; /* huff in pairs */ /*-------------*/ t0 = table_look[ntable].table; linbits = table_look[ntable].linbits; switch (table_look[ntable].ncase) { default: /*------------------------------------------*/ case no_bits: /*- table 0, no data, x=y=0--*/ for (i = 0; i < n; i++) { xy[i][0] = 0; xy[i][1] = 0; } return; /*------------------------------------------*/ case one_shot: /*- single lookup, no escapes -*/ for (i = 0; i < n; i++) { mac_bitget_check((MAXBITS + 2)); bits = t0[0].b.signbits; code = mac_bitget2(bits); mac_bitget_purge(t0[1 + code].b.purgebits); x = t0[1 + code].b.x; y = t0[1 + code].b.y; if (x) if (mac_bitget_1bit()) x = -x; if (y) if (mac_bitget_1bit()) y = -y; xy[i][0] = x; xy[i][1] = y; if (m->cupl.bitdat.bs_ptr > m->cupl.bitdat.bs_ptr_end) break; // bad data protect } return; /*------------------------------------------*/ case no_linbits: for (i = 0; i < n; i++) { t = t0; for (;;) { mac_bitget_check((MAXBITS + 2)); bits = t[0].b.signbits; code = mac_bitget2(bits); if (t[1 + code].b.purgebits) break; t += t[1 + code].ptr; /* ptr include 1+code */ mac_bitget_purge(bits); } mac_bitget_purge(t[1 + code].b.purgebits); x = t[1 + code].b.x; y = t[1 + code].b.y; if (x) if (mac_bitget_1bit()) x = -x; if (y) if (mac_bitget_1bit()) y = -y; xy[i][0] = x; xy[i][1] = y; if (m->cupl.bitdat.bs_ptr > m->cupl.bitdat.bs_ptr_end) break; // bad data protect } return; /*------------------------------------------*/ case have_linbits: for (i = 0; i < n; i++) { t = t0; for (;;) { bits = t[0].b.signbits; code = bitget2(m, bits); if (t[1 + code].b.purgebits) break; t += t[1 + code].ptr; /* ptr includes 1+code */ mac_bitget_purge(bits); } mac_bitget_purge(t[1 + code].b.purgebits); x = t[1 + code].b.x; y = t[1 + code].b.y; if (x == 15) x += bitget_lb(m, linbits); if (x) if (mac_bitget_1bit()) x = -x; if (y == 15) y += bitget_lb(m, linbits); if (y) if (mac_bitget_1bit()) y = -y; xy[i][0] = x; xy[i][1] = y; if (m->cupl.bitdat.bs_ptr > m->cupl.bitdat.bs_ptr_end) break; // bad data protect } return; } /*--- end switch ---*/ } /*==========================================================*/ int unpack_huff_quad(MPEG *m, int vwxy[][4], int n, int nbits, int ntable) { int i; int code; int x, y, v, w; int tmp; int i_non_zero, tmp_nz; tmp_nz = 15; i_non_zero = -1; n = n >> 2; /* huff in quads */ if (ntable) goto case_quad_b; /* case_quad_a: */ for (i = 0; i < n; i++) { if (nbits <= 0) break; mac_bitget_check(10); code = mac_bitget2(6); nbits -= quad_table_a[code][0]; mac_bitget_purge(quad_table_a[code][0]); tmp = quad_table_a[code][1]; if (tmp) { i_non_zero = i; tmp_nz = tmp; } v = (tmp >> 3) & 1; w = (tmp >> 2) & 1; x = (tmp >> 1) & 1; y = tmp & 1; if (v) { if (mac_bitget_1bit()) v = -v; nbits--; } if (w) { if (mac_bitget_1bit()) w = -w; nbits--; } if (x) { if (mac_bitget_1bit()) x = -x; nbits--; } if (y) { if (mac_bitget_1bit()) y = -y; nbits--; } vwxy[i][0] = v; vwxy[i][1] = w; vwxy[i][2] = x; vwxy[i][3] = y; if (m->cupl.bitdat.bs_ptr > m->cupl.bitdat.bs_ptr_end) break; // bad data protect } if (nbits < 0) { i--; vwxy[i][0] = 0; vwxy[i][1] = 0; vwxy[i][2] = 0; vwxy[i][3] = 0; } i_non_zero = (i_non_zero + 1) << 2; if ((tmp_nz & 3) == 0) i_non_zero -= 2; return i_non_zero; /*--------------------*/ case_quad_b: for (i = 0; i < n; i++) { if (nbits < 4) break; nbits -= 4; mac_bitget_check(8); tmp = mac_bitget(4) ^ 15; /* one's complement of bitstream */ if (tmp) { i_non_zero = i; tmp_nz = tmp; } v = (tmp >> 3) & 1; w = (tmp >> 2) & 1; x = (tmp >> 1) & 1; y = tmp & 1; if (v) { if (mac_bitget_1bit()) v = -v; nbits--; } if (w) { if (mac_bitget_1bit()) w = -w; nbits--; } if (x) { if (mac_bitget_1bit()) x = -x; nbits--; } if (y) { if (mac_bitget_1bit()) y = -y; nbits--; } vwxy[i][0] = v; vwxy[i][1] = w; vwxy[i][2] = x; vwxy[i][3] = y; if (m->cupl.bitdat.bs_ptr > m->cupl.bitdat.bs_ptr_end) break; // bad data protect } if (nbits < 0) { i--; vwxy[i][0] = 0; vwxy[i][1] = 0; vwxy[i][2] = 0; vwxy[i][3] = 0; } i_non_zero = (i_non_zero + 1) << 2; if ((tmp_nz & 3) == 0) i_non_zero -= 2; return i_non_zero; /* return non-zero sample (to nearest pair) */ } /*-----------------------------------------------------*/ <file_sep>/lib/SDL_gui/Panel.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_Panel::GUI_Panel(const char *aname, int x, int y, int w, int h) : GUI_Container(aname, x, y, w, h) { layout = 0; } GUI_Panel::~GUI_Panel() { if (layout) layout->DecRef(); } void GUI_Panel::Update(int force) { int i; if (flags & WIDGET_CHANGED) { force = 1; flags &= ~WIDGET_CHANGED; } if (force) { SDL_Rect r = area; r.x = x_offset; r.y = y_offset; Erase(&r); } for (i=0; i<n_widgets; i++) widgets[i]->DoUpdate(force); } int GUI_Panel::Event(const SDL_Event *event, int xoffset, int yoffset) { int i; xoffset += area.x - x_offset; yoffset += area.y - y_offset; for (i = 0; i < n_widgets; i++) { if(IsVisibleWidget(widgets[i])) { if (widgets[i]->Event(event, xoffset, yoffset)) return 1; } } return GUI_Drawable::Event(event, xoffset, yoffset); } void GUI_Panel::UpdateLayout(void) { if (layout != NULL) layout->Layout(this); } void GUI_Panel::SetLayout(GUI_Layout *a_layout) { if (GUI_ObjectKeep((GUI_Object **) &layout, a_layout)) { UpdateLayout(); MarkChanged(); } } extern "C" { GUI_Widget *GUI_PanelCreate(const char *name, int x, int y, int w, int h) { return new GUI_Panel(name, x, y, w, h); } int GUI_PanelCheck(GUI_Widget *widget) { // FIXME not implemented return 0; } void GUI_PanelSetBackground(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_Panel *) widget)->SetBackground(surface); } void GUI_PanelSetBackgroundCenter(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_Panel *) widget)->SetBackgroundCenter(surface); } void GUI_PanelSetBackgroundColor(GUI_Widget *widget, SDL_Color c) { ((GUI_Panel *) widget)->SetBackgroundColor(c); } void GUI_PanelSetXOffset(GUI_Widget *widget, int value) { ((GUI_Panel *) widget)->SetXOffset(value); } void GUI_PanelSetYOffset(GUI_Widget *widget, int value) { ((GUI_Panel *) widget)->SetYOffset(value); } void GUI_PanelSetLayout(GUI_Widget *widget, GUI_Layout *layout) { ((GUI_Panel *) widget)->SetLayout(layout); } int GUI_PanelGetXOffset(GUI_Widget *widget) { return ((GUI_Panel *) widget)->GetXOffset(); } int GUI_PanelGetYOffset(GUI_Widget *widget) { return ((GUI_Panel *) widget)->GetYOffset(); } } <file_sep>/modules/ftpd/lftpd/lftpd_string.c #include <string.h> #include <ctype.h> #include "private/lftpd_string.h" char* lftpd_string_trim(char* s) { char* p = s; for (int i = 0, len = strlen(s); i < len && isspace((int) s[i]); i++) { p++; } for (int i = strlen(p); i >= 0 && isspace((int) p[i]); i--) { p[i] = '\0'; } return p; } <file_sep>/modules/luaTask/src/queue.h /* ** $Id: queue.h 10 2007-09-15 19:37:27Z danielq $ ** Queue Management: Declarations ** SoongSoft, Argentina ** http://www.soongsoft.com mailto:<EMAIL> ** Copyright (C) 2003-2006 <NAME>. All rights reserved. */ #ifndef QUE_H_INCLUDED #define QUE_H_INCLUDED #define QUE_NO_LIMIT -1 typedef struct _qmsg QMSG; struct _qmsg { void *pMsg; QMSG *next; }; typedef struct _queue { int qMax; void * qMutex; #ifdef _WIN32 void * qNotEmpty; void * qNotFull; #elif defined(_arch_dreamcast) semaphore_t * qNotEmpty; semaphore_t * qNotFull; #else int qNotEmpty[2]; int qNotFull; #endif QMSG *qMsgHead; QMSG *qMsgTail; long msgcount; } QUEUE; int _QueGet(QUEUE *pQueue, void **ppMsg); int QueGet(QUEUE *pQueue, void **ppMsg); int QuePut(QUEUE *pQueue, void *pMsg); int QueCreate(QUEUE *pQueue, int maxMsgs); int QueDestroy(QUEUE *pQueue); long GetQueNotEmptyHandle( QUEUE *pQueue); #endif <file_sep>/modules/mp3/libmp3/xingmp3/hwin.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** hwin.c *************************************************** Layer III hybrid window/filter ******************************************************************/ #include <float.h> #include <math.h> #include "L3.h" #include "mhead.h" #ifdef ASM_X86 extern int hybrid_asm(float xin[], float xprev[], float y[18][32], int btype, int nlong, int ntot, int nprev, float *win, int band_limit_nsb); extern void FreqInvert_asm(float y[18][32], int n); #endif /* ASM_X86 */ typedef float ARRAY36[36]; /*====================================================================*/ void imdct18(float f[]); /* 18 point */ void imdct6_3(float f[]); /* 6 point */ /*====================================================================*/ ARRAY36 *hwin_init_addr(MPEG *m) { return m->cupl.win; } #ifdef ASM_X86 #ifdef _MSC_VER #pragma warning(disable: 4035) #endif /* _MSC_VER */ #endif /* ASM_X86 */ /*====================================================================*/ int hybrid(MPEG *m, float xin[], float xprev[], float y[18][32], int btype, int nlong, int ntot, int nprev) { #ifdef ASM_X86 return hybrid_asm(xin, xprev, y, btype, nlong, ntot, nprev, (float *)m->cupl.win, m->cupl.band_limit_nsb); #else int i, j; float *x, *x0; float xa, xb; int n; int nout; if (btype == 2) btype = 0; x = xin; x0 = xprev; /*-- do long blocks (if any) --*/ n = (nlong + 17) / 18; /* number of dct's to do */ for (i = 0; i < n; i++) { imdct18(x); for (j = 0; j < 9; j++) { y[j][i] = x0[j] + m->cupl.win[btype][j] * x[9 + j]; y[9 + j][i] = x0[9 + j] + m->cupl.win[btype][9 + j] * x[17 - j]; } /* window x for next time x0 */ for (j = 0; j < 4; j++) { xa = x[j]; xb = x[8 - j]; x[j] = m->cupl.win[btype][18 + j] * xb; x[8 - j] = m->cupl.win[btype][(18 + 8) - j] * xa; x[9 + j] = m->cupl.win[btype][(18 + 9) + j] * xa; x[17 - j] = m->cupl.win[btype][(18 + 17) - j] * xb; } xa = x[j]; x[j] = m->cupl.win[btype][18 + j] * xa; x[9 + j] = m->cupl.win[btype][(18 + 9) + j] * xa; x += 18; x0 += 18; } /*-- do short blocks (if any) --*/ n = (ntot + 17) / 18; /* number of 6 pt dct's triples to do */ for (; i < n; i++) { imdct6_3(x); for (j = 0; j < 3; j++) { y[j][i] = x0[j]; y[3 + j][i] = x0[3 + j]; y[6 + j][i] = x0[6 + j] + m->cupl.win[2][j] * x[3 + j]; y[9 + j][i] = x0[9 + j] + m->cupl.win[2][3 + j] * x[5 - j]; y[12 + j][i] = x0[12 + j] + m->cupl.win[2][6 + j] * x[2 - j] + m->cupl.win[2][j] * x[(6 + 3) + j]; y[15 + j][i] = x0[15 + j] + m->cupl.win[2][9 + j] * x[j] + m->cupl.win[2][3 + j] * x[(6 + 5) - j]; } /* window x for next time x0 */ for (j = 0; j < 3; j++) { x[j] = m->cupl.win[2][6 + j] * x[(6 + 2) - j] + m->cupl.win[2][j] * x[(12 + 3) + j]; x[3 + j] = m->cupl.win[2][9 + j] * x[6 + j] + m->cupl.win[2][3 + j] * x[(12 + 5) - j]; } for (j = 0; j < 3; j++) { x[6 + j] = m->cupl.win[2][6 + j] * x[(12 + 2) - j]; x[9 + j] = m->cupl.win[2][9 + j] * x[12 + j]; } for (j = 0; j < 3; j++) { x[12 + j] = 0.0f; x[15 + j] = 0.0f; } x += 18; x0 += 18; } /*--- overlap prev if prev longer that current --*/ n = (nprev + 17) / 18; for (; i < n; i++) { for (j = 0; j < 18; j++) y[j][i] = x0[j]; x0 += 18; } nout = 18 * i; /*--- clear remaining only to band limit --*/ for (; i < m->cupl.band_limit_nsb; i++) { for (j = 0; j < 18; j++) y[j][i] = 0.0f; } return nout; #endif } #ifdef ASM_X86 #ifdef _MSC_VER #pragma warning(default: 4035) #endif /* _MSC_VER */ #endif /* ASM_X86 */ /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ /*-- convert to mono, add curr result to y, window and add next time to current left */ int hybrid_sum(MPEG *m, float xin[], float xin_left[], float y[18][32], int btype, int nlong, int ntot) { int i, j; float *x, *x0; float xa, xb; int n; int nout; if (btype == 2) btype = 0; x = xin; x0 = xin_left; /*-- do long blocks (if any) --*/ n = (nlong + 17) / 18; /* number of dct's to do */ for (i = 0; i < n; i++) { imdct18(x); for (j = 0; j < 9; j++) { y[j][i] += m->cupl.win[btype][j] * x[9 + j]; y[9 + j][i] += m->cupl.win[btype][9 + j] * x[17 - j]; } /* window x for next time x0 */ for (j = 0; j < 4; j++) { xa = x[j]; xb = x[8 - j]; x0[j] += m->cupl.win[btype][18 + j] * xb; x0[8 - j] += m->cupl.win[btype][(18 + 8) - j] * xa; x0[9 + j] += m->cupl.win[btype][(18 + 9) + j] * xa; x0[17 - j] += m->cupl.win[btype][(18 + 17) - j] * xb; } xa = x[j]; x0[j] += m->cupl.win[btype][18 + j] * xa; x0[9 + j] += m->cupl.win[btype][(18 + 9) + j] * xa; x += 18; x0 += 18; } /*-- do short blocks (if any) --*/ n = (ntot + 17) / 18; /* number of 6 pt dct's triples to do */ for (; i < n; i++) { imdct6_3(x); for (j = 0; j < 3; j++) { y[6 + j][i] += m->cupl.win[2][j] * x[3 + j]; y[9 + j][i] += m->cupl.win[2][3 + j] * x[5 - j]; y[12 + j][i] += m->cupl.win[2][6 + j] * x[2 - j] + m->cupl.win[2][j] * x[(6 + 3) + j]; y[15 + j][i] += m->cupl.win[2][9 + j] * x[j] + m->cupl.win[2][3 + j] * x[(6 + 5) - j]; } /* window x for next time */ for (j = 0; j < 3; j++) { x0[j] += m->cupl.win[2][6 + j] * x[(6 + 2) - j] + m->cupl.win[2][j] * x[(12 + 3) + j]; x0[3 + j] += m->cupl.win[2][9 + j] * x[6 + j] + m->cupl.win[2][3 + j] * x[(12 + 5) - j]; } for (j = 0; j < 3; j++) { x0[6 + j] += m->cupl.win[2][6 + j] * x[(12 + 2) - j]; x0[9 + j] += m->cupl.win[2][9 + j] * x[12 + j]; } x += 18; x0 += 18; } nout = 18 * i; return nout; } /*--------------------------------------------------------------------*/ void sum_f_bands(float a[], float b[], int n) { int i; for (i = 0; i < n; i++) a[i] += b[i]; } /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ void FreqInvert(float y[18][32], int n) { #ifdef ASM_X86 FreqInvert_asm(y, n); #else int i, j; n = (n + 17) / 18; for (j = 0; j < 18; j += 2) { for (i = 0; i < n; i += 2) { y[1 + j][1 + i] = -y[1 + j][1 + i]; } } #endif } /*--------------------------------------------------------------------*/ <file_sep>/sdk/bin/jslua.lua #! /usr/local/bin/lua-5.1 -- -- * jslua - transform javascript like syntax into lua -- * -- * @author : <NAME> (ziggy at zlash.com) -- * -- * if arg [ 0 ] then standalone = 1 end format = string . format function enter_namespace(name ) local parent = getfenv ( 2 ) local namespace = { parent_globals = parent } local i , v for i , v in pairs ( parent ) do if i ~= "parent_globals" then namespace [ i ]= v end end parent [ name ]= namespace namespace [ name ]= namespace setfenv ( 2 , namespace ) end function exit_namespace() local parent = getfenv ( 2 ) setfenv ( 2 , parent . parent_globals ) end enter_namespace ( "jslua" ) local symbols = "~!#%%%^&*()%-%+=|/%.,<>:;\"'%[%]{}%?" local symbolset = "[" .. symbols .. "]" local msymbols = "<>!%&%*%-%+%=%|%/%%%^%." local msymbolset = "[" .. msymbols .. "]" local nospace = { [ "~" ] = 1 , [ "#" ] = 1 , } local paths = { "" , } function add_path(path ) table . insert ( paths , path ) end local loadfile_orig = loadfile function loadfile(name ) local module , error for _ , path in pairs ( paths ) do module , error = loadfile_orig ( path .. name ) if module then setfenv ( module , getfenv ( 2 ) ) break end end return module , error end function _message(msg ) io . stderr : write ( msg .. "\n" ) end function message(msg ) if verbose then _message ( msg ) end end function dbgmessage(msg ) if dbgmode then _message ( msg ) end end function emiterror(msg , source ) local p = "" source = source or cursource if source then p = format ( "%s (%d) at token '%s' : " , source . filename , source . nline or - 1 , source . token or "<null>" ) end _message ( p .. msg ) has_error = 1 num_error = ( num_error or 0 )+ 1 end function colapse(t ) local i , n while t [ 2 ] do n = #t local t2 = { } for i = 1 , n , 2 do table . insert ( t2 , t [ i ] .. ( t [ i + 1 ] or "" ) ) end t = t2 end return t [ 1 ]or "" end function opensource(realfn , filename ) local source = { } source . filename = filename if standalone then if realfn then source . handle = io . open ( filename , "r" ) else source . handle = io . stdin end if not source . handle then emiterror ( format ( "Can't open source '%s'" , filename ) ) return nil end else source . buffer = gBuffer source . bufpos = 1 end source . nline = 0 source . ntoken = 0 source . tokens = { } source . tokentypes = { } source . tokenlines = { } source . tokencomments = { } local token = basegettoken ( source ) while token do table . insert ( source . tokens , token ) table . insert ( source . tokentypes , source . tokentype ) table . insert ( source . tokenlines , source . nline ) source . ntoken = source . ntoken + 1 token = basegettoken ( source ) end source . tokenpos = 1 return source end function closesource(source ) if standalone then source . handle : close ( ) source . handle = nil end cursource = nil end function getline(source ) if standalone then source . linebuffer = source . handle : read ( "*l" ) else if not source . bufpos then return end local i = string . find ( source . buffer , "\n" , source . bufpos ) source . linebuffer = string . sub ( source . buffer , source . bufpos , ( i or 0 ) - 1 ) source . bufpos = i and ( i + 1 ) end source . nline = source . nline + 1 source . newline = 1 end function savepos(source ) return source . tokenpos end function gotopos(source , pos ) source . tokenpos = pos - 1 return gettoken ( source ) end function gettoken(source ) cursource = source local pos = source . tokenpos local token = source . tokens [ pos ] source . token = token source . tokentype = source . tokentypes [ pos ] source . nline = source . tokenlines [ pos ] if not token then return end source . tokenpos = pos + 1 dbgmessage ( token ) if source . tokentype == "comment" then if not source . tokencomments [ source . tokenpos - 1 ] then out ( string . gsub ( "-- " .. token , "\n" , outcurindent .. "\n--" ) .. "\n" ) source . tokencomments [ source . tokenpos - 1 ]= 1 end return gettoken ( source ) end return token end function basegettoken(source ) local newline local tokens if not source . linebuffer then newline = 1 getline ( source ) if not source . linebuffer then return nil end else source . newline = nil end local i , j local s = source . linebuffer i = string . find ( s , "%S" ) if not i then source . linebuffer = nil return basegettoken ( source ) end j = string . find ( s , "[%s" .. symbols .. "]" , i ) if not j then j = string . len ( s )+ 1 else j = j - 1 end source . stick = ( i == 1 ) source . tokentype = "word" if i ~= j then local c = string . sub ( s , i , i ) if string . find ( c , symbolset ) then j = i while string . find ( string . sub ( s , j + 1 , j + 1 ) , msymbolset ) and string . find ( c , msymbolset ) do j = j + 1 end source . tokentype = string . sub ( s , i , j ) else if string . find ( string . sub ( s , j - 1 , j ) , symbolset ) then j = j - 1 end end end token = string . sub ( s , i , j ) source . token = token source . linebuffer = string . sub ( s , j + 1 ) if token == "\"" or token == "'" then local t = token s = source . linebuffer local ok while not ok do local _ , k _ , k = string . find ( s , t ) while k and k > 1 do local l = k - 1 local n = 0 while l > 0 and string . sub ( s , l , l ) == "\\" do l = l - 1 n = n + 0.5 end if n > 0 then dbgmessage ( format ( "N = %g (%g) '%s'" , n , math . floor ( n ) , source . linebuffer ) ) end if math . floor ( n ) == n then break end _ , k = string . find ( s , t , k + 1 ) end if k then token = token .. string . sub ( s , 1 , k ) source . linebuffer = string . sub ( s , k + 1 ) dbgmessage ( format ( "TOKEN(%s) REST(%s), k(%d)" , token , source . linebuffer , k + 1 ) ) ok = 1 else token = token .. string . sub ( s , 1 , - 2 ) getline ( source ) if not source . linebuffer then return nil end s = source . linebuffer end end source . tokentype = t end if token == "//" or ( source . newline and token == "#" ) then getline ( source ) return basegettoken ( source ) end if token == "/*" then local _ , k _ , k = string . find ( s , "*/" , j + 2 ) token = "" while not k do token = token .. string . sub ( s , j + 2 ).. "\n" getline ( source ) s = source . linebuffer if not s then return nil end _ , k = string . find ( s , "*/" ) j = - 1 end source . linebuffer = string . sub ( s , k + 1 ) source . tokentype = "comment" token = token .. string . sub ( s , j + 2 , k - 1 ) end if source . tokentype == "word" and not string . find ( token , "[^0123456789%.]" ) then source . tokentype = "number" local s = source . linebuffer if string . sub ( s , 1 , 1 ) == "." then local i = string . find ( s , "%D" , 2 ) if i then source . linebuffer = string . sub ( s , i ) i = i - 1 else source . linebuffer = nil end token = token .. string . sub ( s , 1 , i ) end end return token end local exprstack = { } function processaccum(source , token , what ) out ( "= " ) for i = exprstack [ #exprstack ] - 1 , source . tokenpos - 3 , 1 do out ( source . tokens [ i ] .. " " ) end out ( string . sub ( what , 1 , 1 ) .. " " ) return token end function processincr(source , token , what ) processaccum ( source , token , what ) out ( "1 " ) return token end local exprkeywords = { [ "function" ] = function (source , token , what ) out ( "function " ) if token ~= "(" then out ( token ) token = gettoken ( source ) end if token ~= "(" then emiterror ( "'(' expected" , source ) return token end out ( "(" ) token = processblock ( source , "(" , ")" , 1 ) out ( ")" ) outnl ( ) outindent ( 1 ) token = processstatement ( source , gettoken ( source ) , 1 ) outindent ( - 1 ) outi ( ) out ( "end" ) outnl ( ) gotopos ( source , source . tokenpos - 1 ) return ";" end , [ "var" ] = "local" , [ "||" ] = "or" , [ "&&" ] = "and" , [ "!=" ] = "~=" , [ "!" ] = "not" , [ "+=" ] = processaccum , [ "-=" ] = processaccum , [ "*=" ] = processaccum , [ "/=" ] = processaccum , [ "++" ] = processincr , [ "--" ] = processincr , } function eatexpr(source , token ) while token and exprkeywords [ token ] do local expr = exprkeywords [ token ] if type ( expr ) == "string" then out ( expr .. " " ) token = gettoken ( source ) else token = exprkeywords [ token ]( source , gettoken ( source ) , token ) end end return token end function processblock(source , open , close , n ) if n < 1 then if gettoken ( source ) ~= open then emiterror ( format ( "expected '%s' but got '%s'" , open , source . token ) , source ) return nil end n = 1 end local token = gettoken ( source ) table . insert ( exprstack , savepos ( source ) ) while n >= 1 do token = eatexpr ( source , token ) if not token then return nil end if token == open then n = n + 1 else if token == close then n = n - 1 end end if n >= 1 then if token ~= ";" then if nospace [ token ] then out ( token ) else out ( token .. " " ) end end token = gettoken ( source ) end end table . remove ( exprstack ) return token end local expression_terminators = { [ ";" ] = 1 , -- [")"] = 1, -- [","] = 1, -- ["]"] = 1, -- ["}"] = 1 * } local openclose = { [ "(" ] = ")" , [ "[" ] = "]" , [ "{" ] = "}" , } function processexpression(source , token ) table . insert ( exprstack , savepos ( source ) ) while token do token = eatexpr ( source , token ) if not token or expression_terminators [ token ] then break end if nospace [ token ] then out ( token ) else out ( token .. " " ) end local close = openclose [ token ] if close then processblock ( source , token , close , 1 ) out ( close ) end token = gettoken ( source ) end table . remove ( exprstack ) return token end function process_if(source , token , what ) if token ~= "(" then emiterror ( "'(' expected" , source ) return token end outi ( ) out ( what .. " " ) token = processblock ( source , "(" , ")" , 1 ) if what == "if" then out ( "then" ) else out ( "do" ) end outnl ( ) outindent ( 1 ) token = processstatement ( source , gettoken ( source ) , 1 ) outindent ( - 1 ) while what == "if" and token == "elseif" do token = gettoken ( source ) if token ~= "(" then emiterror ( "'(' expected" , source ) return token end outi ( ) out ( "elseif " ) token = processblock ( source , "(" , ")" , 1 ) out ( "then" ) outnl ( ) outindent ( 1 ) token = processstatement ( source , gettoken ( source ) , 1 ) outindent ( - 1 ) end if what == "if" and token == "else" then outi ( ) out ( token ) outnl ( ) outindent ( 1 ) token = processstatement ( source , gettoken ( source ) , 1 ) outindent ( - 1 ) end outi ( ) out ( "end" ) outnl ( ) return token end keywords = { [ "if" ] = process_if , [ "while" ] = process_if , [ "for" ] = process_if , } function processstatement(source , token , delimited ) if keywords [ token ] then return keywords [ token ]( source , gettoken ( source ) , token ) else if token == "{" then if not delimited then outi ( ) out ( "do" ) outnl ( ) outindent ( 1 ) end token = gettoken ( source ) while token and token ~= "}" do token = processstatement ( source , token ) end if not delimited then outindent ( - 1 ) outi ( ) out ( "end" ) outnl ( ) end token = gettoken ( source ) else outi ( ) token = processexpression ( source , token ) outnl ( ) if token and token ~= ";" and token ~= "}" then emiterror ( "warning ';' or '}' expected" , source ) token = gettoken ( source ) end if token == ";" then token = gettoken ( source ) end end end return token end function processsource(source ) local token = gettoken ( source ) while token do token = processstatement ( source , token ) end end function loadmodule(name , ns ) local mname = "mod_" .. name local ons = getfenv ( ) if ns then setfenv ( 1 , ns ) end enter_namespace ( mname ) local table = getfenv ( ) local module , error = loadfile ( name .. ".lua" ) if module then message ( format ( "Module '%s' loaded" , name ) ) setfenv ( module , table ) module ( ) add_options ( table . options ) else emiterror ( format ( "Could not load module '%s'" , name ) ) message ( error ) table = nil end exit_namespace ( ) setfenv ( 1 , ons ) return table end function jslua(f ) has_error = nil num_error = 0 resultString = { } local filename = f or "stdin" message ( "Reading from " .. filename ) local source = opensource ( f , filename ) if not source then return "" end message ( format ( "%d lines, %d tokens" , source . nline , source . ntoken ) ) message ( "Processing " .. filename ) processsource ( source ) closesource ( source ) if has_error then message ( format ( "%d error(s) while compiling" , num_error ) ) return "" else message ( format ( "no error while compiling" ) ) end return colapse ( resultString ) end function dofile(file ) local source = jslua ( file ) local module , error = loadstring ( source ) source = nil if module then module ( ) else emiterror ( format ( "Could not load string" ) ) message ( error ) end end postprocess = { } function do_postprocess() for _ , v in pairs ( postprocess ) do v ( ) end end function add_postprocess(f ) table . insert ( postprocess , f ) end outcurindent = "" outindentstring = " " outindentlevel = 0 function out(s ) table . insert ( resultString , s ) end function outf(... ) local s = format ( ... ) out ( s ) end function get_outcurindent() return outcurindent end function outi() out ( outcurindent ) end local line = 1 function outnl() line = line + 1 out ( "\n" ) end function outindent(l ) outindentlevel = outindentlevel + l outcurindent = string . rep ( outindentstring , outindentlevel ) end function option_list(opt ) for i , v in pairs ( opt ) do emiterror ( i .. " " .. v . help ) end end function option_help() print ( "usage : jslua [options] [filenames]" ) option_list ( options ) os . exit ( ) end function option_module() local name = option_getarg ( ) loadmodule ( name ) end local outhandle = io . stdout local compileonly function option_output() compileonly = 1 local fn = option_getarg ( ) outhandle = io . open ( fn , "w" ) if not outhandle then emiterror ( "Failed to open '" .. fn .. "' for writing." ) else message ( "Opened '" .. fn .. "' for writing ..." ) end end options = { [ "-o" ] = { call = option_output , help = "compile only, and output lua source code to specified file" } , [ "-c" ] = { call = function () compileonly = 1 end , help = "compile only, and output lua source code on stdout" } , [ "-v" ] = { call = function () verbose = 1 end , help = "turn verbose mode on" } , [ "-d" ] = { call = function () dbgmode = 1 end , help = "turn debug mode on" } , [ "--module" ] = { call = option_module , help = "<modulename> load a module" } , [ "--help" ] = { call = option_help , help = "display this help message" } } function add_options(table ) for i , v in pairs ( table ) do if options [ i ] then emiterror ( format ( "Option '%s' overriden" , i ) ) end options [ i ]= v end end function option_getarg() local arg = option_args [ option_argind ] option_argind = option_argind + 1 return arg end exit_namespace ( ) if standalone then local name = arg [ 0 ] if name then local i = 0 local j while i ~= nil do j = i i = string . find ( name , "[/\\]" , i + 1 ) end if j then name = string . sub ( name , 0 , j ) jslua . message ( format ( "Adding path '%s'" , name ) ) jslua . add_path ( name ) end end jslua . option_args = arg jslua . option_argind = 1 local filename = { } while jslua . option_argind <= #jslua . option_args do local arg = jslua . option_getarg ( ) if string . sub ( arg , 1 , 1 ) == "-" then local opt = jslua . options [ arg ] if opt then if opt . call then opt . call ( ) end if opt . postcall then jslua . add_postprocess ( opt . postcall ) end else jslua . emiterror ( format ( "Unknown option '%s'\n" , arg ) ) jslua . option_help ( ) end else table . insert ( filename , arg ) end end local function doit(filename ) if compileonly then outhandle : write ( jslua . jslua ( filename ) ) else jslua . dofile ( filename ) end end if not next ( filename ) then doit ( ) else for _ , v in pairs ( filename ) do doit ( v ) end end jslua . do_postprocess ( ) if jslua . has_error then os . exit ( - 1 ) end end <file_sep>/firmware/isoldr/loader/dev/sd/spi.h /* DreamShell ##version## sd/spi.h Copyright (C) 2011-2016 SWAT */ #ifndef _SPI_H #define _SPI_H #include <arch/types.h> #include <arch/timer.h> /** * \file * SPI interface for Sega Dreamcast SCIF * * \author SWAT */ /** * \brief Initializes the SPI interface */ int spi_init(); /** * \brief Shutdown the SPI interface */ int spi_shutdown(); /** * \brief Switch on CS pin and lock SPI bus * * \param[in] the CS pin */ void spi_cs_on(); /** * \brief Switch off CS pin and unlock SPI bus * * \param[in] the CS pin */ void spi_cs_off(); /** * \brief Sends a byte over the SPI bus. * * \param[in] b The byte to send. */ void spi_send_byte(register uint8 b); /** * \brief Receives a byte from the SPI bus. * * \returns The received byte. */ uint8 spi_rec_byte(); /** * \brief Send and receive a byte to/from the SPI bus. * * \param[in] b The byte to send. * \returns The received byte. */ uint8 spi_sr_byte(register uint8 b); /** * \brief Slow send and receive a byte to/from the SPI bus. * Used for SDC/MMC commands. * * \param[in] b The byte to send. * \returns The received byte. */ uint8 spi_slow_sr_byte(register uint8 b); /** * \brief Sends data contained in a buffer over the SPI bus. * * \param[in] data A pointer to the buffer which contains the data to send. * \param[in] len The number of bytes to send. */ void spi_send_data(const uint8* data, uint16 data_len); void spi_send_data_fast(const uint8* data, uint16 data_len); /** * \brief Receives multiple bytes from the SPI bus and writes them to a buffer. * * \param[out] buffer A pointer to the buffer into which the data gets written. * \param[in] len The number of bytes to read. */ void spi_rec_data(uint8* buffer, uint16 buffer_len); void spi_rec_data_fast(uint8* buffer, uint16 buffer_len); #endif /* _SPI_H */ <file_sep>/firmware/isoldr/loader/include/fs.h /** * DreamShell ISO Loader * File system * (c)2011-2022 SWAT <http://www.dc-swat.ru> */ #ifndef __FS_H__ #define __FS_H__ #if defined(DEV_TYPE_NET) #include "commands.h" #elif defined(DEV_TYPE_SD) || defined(DEV_TYPE_IDE) #include "ff.h" #include "diskio.h" #if defined(DEV_TYPE_SD) #include "spi.h" #elif defined(DEV_TYPE_IDE) #include <ide/ide.h> #endif #elif defined(DEV_TYPE_GD) #include <ide/ide.h> #endif /* DEV_TYPE_NET */ #ifndef MAX_OPEN_FILES # define MAX_OPEN_FILES 3 #endif #define FS_ERR_SYSERR -1 /* Generic error from device */ #define FS_ERR_DIRERR -2 /* Root directory not found */ #define FS_ERR_NOFILE -3 /* File not found */ #define FS_ERR_PARAM -4 /* Invalid parameters passed to function */ #define FS_ERR_NUMFILES -5 /* Max number of open files exceeded */ #define FS_ERR_NODISK -6 /* No disc/card present */ #define FS_ERR_DISKCHG -7 /* Disc has been replaced with a new one */ #define FS_ERR_EXISTS -8 /* File already exists */ #define FS_ERR_NO_PATH -9 /* No path */ /** \brief File descriptor type */ typedef int file_t; /** \brief Invalid file handle constant (for open failure, etc) */ #define FILEHND_INVALID ((file_t)-1) /** \brief Callback function type */ typedef void fs_callback_f(size_t); /** \defgroup seek_modes Seek modes These are the values you can pass for the whence parameter to fs_seek(). @{ */ #define SEEK_SET 0 /**< \brief Set position to offset. */ #define SEEK_CUR 1 /**< \brief Seek from current position. */ #define SEEK_END 2 /**< \brief Seek from end of file. */ /** @} */ #define O_MODE_MASK 0x0f #define O_RDONLY 0 #define O_DIR 1 #define O_WRONLY 2 #define O_RDWR 3 #define O_APPEND 0x0008 /* append (writes guaranteed at the end) */ #define O_CREAT 0x0200 /* open with file create */ #define O_TRUNC 0x0400 /* open with truncation */ #define O_PIO 0x1000 /* do not use DMA */ enum FS_DMA_STATE { FS_DMA_DISABLED = 0, FS_DMA_SHARED = 1, FS_DMA_HIDDEN = 2, FS_DMA_NO_IRQ = 3 }; enum FS_IOCTL_CMD { FS_IOCTL_GET_LBA = 0, FS_IOCTL_SYNC = 1 }; int fs_init(); void fs_shutdown(); void fs_enable_dma(int state); int fs_dma_enabled(); int open(const char *path, int mode); int close(int fd); int pread(int fd, void *buf, unsigned int nbyte, unsigned int offset); int read(int fd, void *buf, unsigned int nbyte); int write(int fd, void *buf, unsigned int nbyte); long int lseek(int fd, long int offset, int whence); long int tell(int fd); unsigned long total(int fd); int ioctl(int fd, int cmd, void *data); /** * Async read feature */ int read_async(int fd, void *buf, unsigned int nbyte, fs_callback_f *cb); int abort_async(int fd); int poll(int fd); void poll_all(int err); /** * Async stream read feature */ int pre_read(int fd, unsigned int size); #if defined(DEV_TYPE_GD) || defined(DEV_TYPE_IDE) # define pre_read_xfer_start g1_ata_xfer # define pre_read_xfer_busy g1_ata_in_progress # define pre_read_xfer_size g1_ata_transfered # define pre_read_xfer_done g1_ata_has_irq # define pre_read_xfer_end g1_ata_ack_irq # define pre_read_xfer_abort g1_ata_abort #else # define pre_read_xfer_start(addr, bytes) do { } while(0) # define pre_read_xfer_busy() 0 # define pre_read_xfer_size() 1 # define pre_read_xfer_done() 1 # define pre_read_xfer_end() do { } while(0) # define pre_read_xfer_abort() do { } while(0) #endif #endif /* __FS_H__ */ <file_sep>/modules/aicaos/aica_syscalls.h #ifndef AICA_SYSCALLS_H #define AICA_SYSCALLS_H #include "aica_common.h" void aica_init_syscalls(void); struct open_param { const char *name; const int namelen; int flags; int mode; }; struct fstat_param { int file; struct stat *st; }; struct stat_param { const char *name; const int namelen; struct stat *st; }; struct link_param { const char *old; const int namelen_old; const char *new; const int namelen_new; }; struct lseek_param { int file; int ptr; int dir; }; struct read_param { int file; void *ptr; size_t len; }; struct write_param { int file; const void *ptr; size_t len; }; #endif <file_sep>/firmware/isoldr/loader/dev/ide/ide.c /** * Copyright (c) 2014-2023 SWAT <http://www.dc-swat.ru> * Copyright (c) 2017 Megavolt85 * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <main.h> #include <exception.h> #include <asic.h> #include <mmu.h> #include <arch/cache.h> #include <arch/timer.h> #define ATA_SR_BSY 0x80 #define ATA_SR_DRDY 0x40 #define ATA_SR_DF 0x20 #define ATA_SR_DSC 0x10 #define ATA_SR_DRQ 0x08 #define ATA_SR_CORR 0x04 #define ATA_SR_IDX 0x02 #define ATA_SR_ERR 0x01 #define ATA_ER_BBK 0x80 #define ATA_ER_UNC 0x40 #define ATA_ER_MC 0x20 #define ATA_ER_IDNF 0x10 #define ATA_ER_MCR 0x08 #define ATA_ER_ABRT 0x04 #define ATA_ER_TK0NF 0x02 #define ATA_ER_AMNF 0x01 // ATA-Commands: #define ATA_CMD_READ_PIO 0x20 #define ATA_CMD_READ_PIO_EXT 0x24 #define ATA_CMD_READ_DMA 0xC8 #define ATA_CMD_READ_DMA_EXT 0x25 #define ATA_CMD_WRITE_PIO 0x30 #define ATA_CMD_WRITE_PIO_EXT 0x34 #define ATA_CMD_WRITE_DMA 0xCA #define ATA_CMD_WRITE_DMA_EXT 0x35 #define ATA_CMD_CACHE_FLUSH 0xE7 #define ATA_CMD_CACHE_FLUSH_EXT 0xEA #define ATA_CMD_IDENTIFY 0xEC #define ATA_CMD_SET_FEATURES 0xEF // ATAPI-Commands: #define ATAPI_CMD_PACKET 0xA0 #define ATAPI_CMD_IDENTIFY 0xA1 #define ATAPI_CMD_RESET 0x08 #define ATAPI_CMD_READ 0xA8 #define ATAPI_CMD_EJECT 0x1B #define ATAPI_CMD_READ_TOC 0x43 #define ATAPI_CMD_MODE_SENSE 0x5A #define ATAPI_CMD_READ_CD 0xBE // SPI-Commands: #define SPI_CMD_EJECT 0x16 #define SPI_CMD_READ_TOC 0x14 #define SPI_CMD_REQ_STAT 0x10 #define SPI_CMD_READ_CD 0x30 #define SPI_CMD_SEEK 0x21 #define SPI_CMD_REQ_MODE 0x11 #define ATA_MASTER 0x00 #define ATA_SLAVE 0x01 #define IDE_ATA 0x00 #define IDE_ATAPI 0x01 #define IDE_SPI 0x02 #define G1_ATA_CTRL 0xA05F7018 #define G1_ATA_BASE 0xA05F7080 /* ATA-related registers. Some of these serve very different purposes when read than they do when written (hence why some addresses are duplicated). */ #define G1_ATA_ALTSTATUS 0xA05F7018 /* Read */ #define G1_ATA_CTL 0xA05F7018 /* Write */ #define G1_ATA_DATA 0xA05F7080 /* Read/Write */ #define G1_ATA_ERROR 0xA05F7084 /* Read */ #define G1_ATA_FEATURES 0xA05F7084 /* Write */ #define G1_ATA_IRQ_REASON 0xA05F7088 /* Read */ #define G1_ATA_SECTOR_COUNT 0xA05F7088 /* Write */ #define G1_ATA_LBA_LOW 0xA05F708C /* Read/Write */ #define G1_ATA_LBA_MID 0xA05F7090 /* Read/Write */ #define G1_ATA_LBA_HIGH 0xA05F7094 /* Read/Write */ #define G1_ATA_DEVICE_SELECT 0xA05F7098 /* Read/Write */ #define G1_ATA_STATUS_REG 0xA05F709C /* Read */ #define G1_ATA_COMMAND_REG 0xA05F709C /* Write */ /* DMA-related registers. */ #define G1_ATA_DMA_RACCESS_WAIT 0xA05F74A0 /* Write-only */ #define G1_ATA_DMA_WACCESS_WAIT 0xA05F74A4 /* Write-only */ #define G1_ATA_DMA_ADDRESS 0xA05F7404 /* Read/Write */ #define G1_ATA_DMA_LENGTH 0xA05F7408 /* Read/Write */ #define G1_ATA_DMA_DIRECTION 0xA05F740C /* Read/Write */ #define G1_ATA_DMA_ENABLE 0xA05F7414 /* Read/Write */ #define G1_ATA_DMA_STATUS 0xA05F7418 /* Read/Write */ #define G1_ATA_DMA_STARD 0xA05F74F4 /* Read-only */ #define G1_ATA_DMA_LEND 0xA05F74F8 /* Read-only */ #define G1_ATA_DMA_PRO 0xA05F74B8 /* Write-only */ #define G1_ATA_DMA_PRO_SYSMEM 0x8843407F /* PIO-related registers. */ #define G1_ATA_PIO_RACCESS_WAIT 0xA05F7490 /* Write-only */ #define G1_ATA_PIO_WACCESS_WAIT 0xA05F7494 /* Write-only */ #define G1_ATA_PIO_IORDY_CTRL 0xA05F74B4 /* Write-only */ /* Subcommands we might care about for the SET FEATURES command. */ #define ATA_FEATURE_TRANSFER_MODE 0x03 /* Transfer mode values. */ #define ATA_TRANSFER_PIO_DEFAULT 0x00 #define ATA_TRANSFER_PIO_NOIORDY 0x01 #define ATA_TRANSFER_PIO_FLOW(x) 0x08 | ((x) & 0x07) #define ATA_TRANSFER_WDMA(x) 0x20 | ((x) & 0x07) #define ATA_TRANSFER_UDMA(x) 0x40 | ((x) & 0x07) /* Access timing data. */ #define G1_ACCESS_WDMA_MODE2 0x00001001 #define G1_ACCESS_PIO_DEFAULT 0x00000222 /* DMA Settings. */ #define G1_DMA_TO_DEVICE 0 #define G1_DMA_TO_MEMORY 1 /* Macros to access the ATA registers */ #define OUT32(addr, data) *((volatile u32 *)addr) = data #define OUT16(addr, data) *((volatile u16 *)addr) = data #define OUT8(addr, data) *((volatile u8 *)addr) = data #define IN32(addr) *((volatile u32 *)addr) #define IN16(addr) *((volatile u16 *)addr) #define IN8(addr) *((volatile u8 *)addr) typedef struct ide_req { void *buff; u64 lba; u32 count; u32 bytes; u8 cmd; u8 async; struct ide_device *dev; } ide_req_t; #ifdef DEV_TYPE_EMU # define MAX_DEVICE_COUNT 1 #else # define MAX_DEVICE_COUNT 2 #endif static struct ide_device ide_devices[MAX_DEVICE_COUNT]; static u32 device_count = 0; #ifndef DEV_TYPE_IDE static u32 g1_dma_part_avail = 0; #endif static u32 g1_dma_irq_visible = 1; static u32 g1_dma_irq_code_game = 0; static u32 g1_pio_total = 0; static u32 g1_pio_avail = 0; static u32 g1_pio_trans = 0; #ifdef HAVE_EXPT static u32 g1_dma_irq_code_internal = 0; #endif #define g1_ata_wait_status(n) \ do {} while((IN8(G1_ATA_ALTSTATUS) & (n))) #define g1_ata_wait_nbsy() g1_ata_wait_status(ATA_SR_BSY) #define g1_ata_wait_bsydrq() g1_ata_wait_status(ATA_SR_DRQ | ATA_SR_BSY) #define g1_ata_wait_drdy() \ do {} while(!(IN8(G1_ATA_ALTSTATUS) & ATA_SR_DRDY)) #define g1_ata_wait_dma() \ do {} while(IN32(G1_ATA_DMA_STATUS)) u8 swap8(u8 n) { return ((n >> 4) | (n << 4)); } u16 swap16(u16 n) { return ((n >> 8) | (n << 8)); } /* Is a G1 DMA in progress? */ u32 g1_dma_in_progress(void) { return IN32(G1_ATA_DMA_STATUS); } u32 g1_dma_transfered(void) { return IN32(G1_ATA_DMA_LEND); } static void delay_1ms() { timer_spin_sleep_bios(1); } #ifdef HAVE_EXPT void *g1_dma_handler(void *passer, register_stack *stack, void *current_vector) { const uint32 code = *REG_INTEVT; const uint32 status = ASIC_IRQ_STATUS[ASIC_MASK_NRM_INT]; const uint32 statusExt = ASIC_IRQ_STATUS[ASIC_MASK_EXT_INT]; const uint32 statusErr = ASIC_IRQ_STATUS[ASIC_MASK_ERR_INT]; const uint32 errFlags = (ASIC_ERR_G1DMA_ILLEGAL | ASIC_ERR_G1DMA_OVERRUN | ASIC_ERR_G1DMA_ROM_FLASH); (void)passer; (void)stack; (void)code; DBGF("G1_IRQ: %03lx %08lx %08lx %08lx\n", code, status, statusExt, statusErr); if (g1_dma_irq_visible) { return current_vector; } if (statusExt & ASIC_EXT_GD_CMD) { DBGF("G1_ATA_IRQ: %03lx %08lx\n", code, statusExt); g1_ata_ack_irq(); ASIC_IRQ_STATUS[ASIC_MASK_NRM_INT] = ASIC_NRM_EXTERNAL; } if (status & ASIC_NRM_GD_DMA) { ASIC_IRQ_STATUS[ASIC_MASK_NRM_INT] = ASIC_NRM_GD_DMA; } if ((statusErr & errFlags)) { LOGFF("G1_ERROR_IRQ: %03lx %08lx\n", code, statusErr); ASIC_IRQ_STATUS[ASIC_MASK_ERR_INT] = errFlags; ASIC_IRQ_STATUS[ASIC_MASK_NRM_INT] = ASIC_NRM_ERROR; poll_all(-1); return current_vector; } if (status & ASIC_NRM_GD_DMA) { /* Ack DMA IRQ. */ ASIC_IRQ_STATUS[ASIC_MASK_NRM_INT] = ASIC_NRM_GD_DMA; /* Processing filesystem */ poll_all(0); uint32 st = status & ~ASIC_NRM_GD_DMA; if (g1_dma_irq_code_internal == EXP_CODE_INT9) { st = ((*ASIC_IRQ9_MASK) & st); } else if(g1_dma_irq_code_internal == EXP_CODE_INT11) { st = ((*ASIC_IRQ11_MASK) & st); } if (st == 0) { return my_exception_finish; } } return current_vector; } s32 g1_dma_init_irq() { g1_dma_irq_code_game = 0; g1_dma_irq_code_internal = 0; g1_dma_irq_visible = 1; #ifdef NO_ASIC_LT return 0; #else asic_lookup_table_entry a_entry; a_entry.irq = EXP_CODE_ALL; a_entry.clear_irq = 0; a_entry.mask[ASIC_MASK_NRM_INT] = ASIC_NRM_GD_DMA; a_entry.mask[ASIC_MASK_EXT_INT] = ASIC_EXT_GD_CMD; a_entry.mask[ASIC_MASK_ERR_INT] = (ASIC_ERR_G1DMA_ILLEGAL | ASIC_ERR_G1DMA_OVERRUN | ASIC_ERR_G1DMA_ROM_FLASH); a_entry.handler = g1_dma_handler; return asic_add_handler(&a_entry, NULL, 0); #endif } #endif void g1_dma_abort(void) { OUT8(G1_ATA_DMA_ENABLE, 0); if (g1_dma_in_progress()) { g1_ata_wait_dma(); } } void g1_dma_start(u32 addr, size_t bytes) { /* Set the DMA parameters up. */ OUT32(G1_ATA_DMA_PRO, G1_ATA_DMA_PRO_SYSMEM); OUT32(G1_ATA_DMA_ADDRESS, (addr & 0x0FFFFFFF)); OUT32(G1_ATA_DMA_LENGTH, bytes); OUT8(G1_ATA_DMA_DIRECTION, G1_DMA_TO_MEMORY); /* Enable G1 DMA. */ OUT8(G1_ATA_DMA_ENABLE, 1); /* Start the DMA transfer. */ OUT8(G1_ATA_DMA_STATUS, 1); } void g1_dma_irq_hide(s32 all) { g1_dma_irq_visible = 0; g1_dma_irq_code_game = g1_dma_has_irq_mask(); OUT8(G1_ATA_CTL, 2); #ifdef HAVE_EXPT if (!all && exception_inited()) { if (g1_dma_irq_code_game == EXP_CODE_INT9) { *ASIC_IRQ11_MASK |= ASIC_NRM_GD_DMA; g1_dma_irq_code_internal = EXP_CODE_INT11; } else { *ASIC_IRQ9_MASK |= ASIC_NRM_GD_DMA; g1_dma_irq_code_internal = EXP_CODE_INT9; } } else { g1_dma_irq_code_internal = 0; } #else (void)all; #endif } void g1_dma_irq_restore(void) { #ifdef HAVE_EXPT if (g1_dma_irq_code_internal == EXP_CODE_INT9) { *ASIC_IRQ9_MASK &= ~ASIC_NRM_GD_DMA; } else if(g1_dma_irq_code_internal == EXP_CODE_INT11) { *ASIC_IRQ11_MASK &= ~ASIC_NRM_GD_DMA; } // g1_dma_irq_code_internal = 0; #endif if(g1_dma_irq_code_game == EXP_CODE_INT9) { *ASIC_IRQ9_MASK |= ASIC_NRM_GD_DMA; } else if(g1_dma_irq_code_game == EXP_CODE_INT11) { *ASIC_IRQ11_MASK |= ASIC_NRM_GD_DMA; } else if(g1_dma_irq_code_game == EXP_CODE_INT13) { *ASIC_IRQ13_MASK |= ASIC_NRM_GD_DMA; } // g1_dma_irq_code_game = 0; g1_dma_irq_visible = 1; OUT8(G1_ATA_CTL, 0); } void g1_dma_set_irq_mask(s32 last_transfer) { s32 dma_mode = fs_dma_enabled(); if (dma_mode == FS_DMA_DISABLED) { if (!g1_dma_irq_visible) { g1_dma_irq_restore(); } } else if (dma_mode == FS_DMA_HIDDEN) { /* Hide all internal DMA transfers (CDDA, etc...) */ if (g1_dma_irq_visible) { g1_dma_irq_hide(0); } } else if (dma_mode == FS_DMA_SHARED) { if (last_transfer && !g1_dma_irq_visible) { g1_dma_irq_restore(); } else if (!last_transfer && g1_dma_irq_visible) { g1_dma_irq_hide(0); } else if(!g1_dma_irq_code_game) { g1_dma_irq_code_game = g1_dma_has_irq_mask(); } } #ifdef DEBUG LOGFF("%03lx %03lx %03lx (mode=%d last=%d game=%03lx int=%03lx)\n", (*ASIC_IRQ9_MASK & ASIC_NRM_GD_DMA) ? EXP_CODE_INT9 : 0, (*ASIC_IRQ11_MASK & ASIC_NRM_GD_DMA) ? EXP_CODE_INT11 : 0, (*ASIC_IRQ13_MASK & ASIC_NRM_GD_DMA) ? EXP_CODE_INT13 : 0, dma_mode, last_transfer, g1_dma_irq_code_game, # ifdef HAVE_EXPT g1_dma_irq_code_internal # else 0 # endif ); #endif } u32 g1_dma_has_irq_mask() { if (*ASIC_IRQ9_MASK & ASIC_NRM_GD_DMA) return EXP_CODE_INT9; if (*ASIC_IRQ11_MASK & ASIC_NRM_GD_DMA) return EXP_CODE_INT11; if (*ASIC_IRQ13_MASK & ASIC_NRM_GD_DMA) return EXP_CODE_INT13; return 0; } /* This one is an inline function since it needs to return something... */ static inline s32 g1_ata_wait_drq(void) { u8 val = IN8(G1_ATA_ALTSTATUS); while(!(val & ATA_SR_DRQ) && !(val & (ATA_SR_ERR | ATA_SR_DF))) { val = IN8(G1_ATA_ALTSTATUS); } return (val & (ATA_SR_ERR | ATA_SR_DF)) ? -1 : 0; } #if !defined(HAVE_LIMIT) || defined(DEV_TYPE_GD) static s32 g1_ata_set_transfer_mode(u8 mode) { u8 status; /* Fill in the registers as is required. */ OUT8(G1_ATA_FEATURES, ATA_FEATURE_TRANSFER_MODE); OUT8(G1_ATA_SECTOR_COUNT, mode); OUT8(G1_ATA_LBA_LOW, 0); OUT8(G1_ATA_LBA_MID, 0); OUT8(G1_ATA_LBA_HIGH,0); /* Send the SET FEATURES command. */ OUT8(G1_ATA_COMMAND_REG, ATA_CMD_SET_FEATURES); delay_1ms(); /* Wait for command completion. */ g1_ata_wait_nbsy(); /* See if the command completed. */ status = IN8(G1_ATA_STATUS_REG); if((status & ATA_SR_ERR) || (status & ATA_SR_DF)) { LOGFF("Error setting transfer mode %02x\n", mode); return -1; } return 0; } #endif #if defined(LOG) && !defined(DEV_TYPE_EMU) static const s8 *dev_bus_name[] = {"MASTER", "SLAVE"}; static const s8 *dev_proto_name[] = {"ATAPI", "SPI"}; #endif static s32 g1_dev_scan(void) { #ifdef DEV_TYPE_EMU memset(&ide_devices[0], 0, sizeof(ide_devices)); ide_devices[0].wdma_modes = 0x0407; ide_devices[0].cd_info.sec_type = 0x10; ide_devices[0].reserved = 1; ide_devices[0].type = IDE_SPI; ide_devices[0].drive = 0; g1_ata_set_transfer_mode(ATA_TRANSFER_PIO_DEFAULT); g1_ata_set_transfer_mode(ATA_TRANSFER_WDMA(2)); OUT32(G1_ATA_DMA_RACCESS_WAIT, G1_ACCESS_WDMA_MODE2); OUT32(G1_ATA_DMA_WACCESS_WAIT, G1_ACCESS_WDMA_MODE2); OUT32(G1_ATA_DMA_PRO, G1_ATA_DMA_PRO_SYSMEM); return 1; #else s32 i; u8 j, st, err, type; int d = 0; u16 *data; #if defined(DEV_TYPE_IDE) // Do not init twice. if(device_count) { return device_count; } #endif memset(&ide_devices[0], 0, sizeof(ide_devices)); data = (u16 *) malloc(512); if (!data) { LOGFF("Memory failed"); return 0; } memset(data, 0, 512); for (j = 0; j < MAX_DEVICE_COUNT; j++) { err = 0; type = IDE_ATA; ide_devices[j].reserved = 0; // Assuming that no drive here. #if defined(DEV_TYPE_IDE) // FIXME: Skip master drive, so do not spin GD-ROM // Must add new driver to DS core before. if (j == 0) continue; #endif OUT8(G1_ATA_DEVICE_SELECT, (0xA0 | (j << 4))); delay_1ms(); OUT8(G1_ATA_SECTOR_COUNT, 0); OUT8(G1_ATA_LBA_LOW, 0); OUT8(G1_ATA_LBA_MID, 0); OUT8(G1_ATA_LBA_HIGH, 0); OUT8(G1_ATA_COMMAND_REG, ATA_CMD_IDENTIFY); delay_1ms(); st = IN8(G1_ATA_STATUS_REG); if(!(st & (ATA_SR_DRDY | ATA_SR_DSC)) && !(st & ATA_SR_ERR)) { LOGFF("%s device not found\n", dev_bus_name[j]); continue; } while (d++ < 10000) { if (st & ATA_SR_ERR) { err = 1; break; } else if (!(st & ATA_SR_BSY) && (st & ATA_SR_DRQ)) { break; // Everything is right. } st = IN8(G1_ATA_STATUS_REG); } if (err) { OUT8(G1_ATA_COMMAND_REG, ATAPI_CMD_RESET); g1_ata_wait_nbsy(); u8 cl = IN8(G1_ATA_LBA_MID); u8 ch = IN8(G1_ATA_LBA_HIGH); if ((cl == 0x14 && ch == 0xEB) || (cl == 0x69 && ch == 0x96)) { type = IDE_ATAPI; } else continue; // Unknown Type (And always not be a device). OUT8(G1_ATA_COMMAND_REG, ATAPI_CMD_IDENTIFY); g1_ata_wait_drq(); } for(i = 0; i < 256; i++) data[i] = IN16(G1_ATA_DATA); #if defined(DEV_TYPE_GD) if (!memcmp(&data[40], &data[136], 192)) { type = IDE_SPI; ide_devices[j].wdma_modes = 0x0407; ide_devices[j].cd_info.sec_type = 0x10; ide_devices[j].lba48 = 1; g1_ata_set_transfer_mode(ATA_TRANSFER_PIO_DEFAULT); g1_ata_set_transfer_mode(ATA_TRANSFER_WDMA(2)); OUT32(G1_ATA_DMA_RACCESS_WAIT, G1_ACCESS_WDMA_MODE2); OUT32(G1_ATA_DMA_WACCESS_WAIT, G1_ACCESS_WDMA_MODE2); OUT32(G1_ATA_DMA_PRO, G1_ATA_DMA_PRO_SYSMEM); } else #endif { #if defined(DEV_TYPE_IDE) if (type == IDE_ATA) { ide_devices[j].command_sets = (u32)(data[82]) | ((u32)(data[83]) << 16); ide_devices[j].capabilities = (u32)(data[49]) | ((u32)(data[50]) << 16); ide_devices[j].wdma_modes = data[63]; #ifdef LOG if (!(ide_devices[j].capabilities & (1 << 9))) { LOGF("CHS don't supported\n"); // continue; } #endif if(!(ide_devices[j].command_sets & (1 << 26))) { ide_devices[j].max_lba = (u64)(data[60]) | ((u64)(data[61]) << 16); ide_devices[j].lba48 = 0; } else { ide_devices[j].max_lba = (u64)(data[100]) | ((u64)(data[101]) << 16) | ((u64)(data[102]) << 32) | ((u64)(data[103]) << 48); ide_devices[j].lba48 = 1; } #ifndef HAVE_LIMIT g1_ata_set_transfer_mode(ATA_TRANSFER_PIO_DEFAULT); /* Do we support Multiword DMA mode 2? If so, enable it. Otherwise, we won't even bother doing DMA at all. */ if(ide_devices[j].wdma_modes & 0x0004 && !g1_ata_set_transfer_mode(ATA_TRANSFER_WDMA(2))) { OUT32(G1_ATA_DMA_RACCESS_WAIT, G1_ACCESS_WDMA_MODE2); OUT32(G1_ATA_DMA_WACCESS_WAIT, G1_ACCESS_WDMA_MODE2); OUT32(G1_ATA_DMA_PRO, G1_ATA_DMA_PRO_SYSMEM); } else { ide_devices[j].wdma_modes = 0; } #endif } #elif defined(DEV_TYPE_GD) if (type == IDE_ATAPI) { ide_devices[j].cd_info.sec_type = 0x10; ide_devices[j].lba48 = 1; } #endif } ide_devices[j].reserved = 1; ide_devices[j].type = type; ide_devices[j].drive = j; device_count++; } #ifdef LOG for (i = 0; i < 2; i++) { if (ide_devices[i].reserved == 1) { if (ide_devices[i].type == IDE_ATA) { LOGF("%s %s ATA drive %ld Kb\n", dev_bus_name[i], ide_devices[i].lba48 ? "LBA48":"LBA28", (u32)(ide_devices[i].max_lba >> 1)); } else { LOGF("%s %s drive\n", dev_bus_name[i], dev_proto_name[ide_devices[i].type-1]); } } else { LOGF("%s device not found\n", dev_bus_name[i]); } } #endif free(data); return device_count; #endif /* DEV_TYPE_EMU */ } #ifdef DEV_TYPE_IDE static s32 g1_ata_access(struct ide_req *req) { struct ide_device *dev = req->dev; u8 *buff = req->buff; u32 count = req->count; u32 len; u64 lba = req->lba; u8 lba_io[6]; u8 head; u16 cmd; const u32 sector_size = 512; if ((req->cmd & 2)) { if ((u32)buff & 0x1f) { LOGFF("Unaligned output address: 0x%08lx (32 byte)\n", (u32)buff); return -1; } cmd = (req->cmd & 1) ? ATA_CMD_WRITE_DMA : ATA_CMD_READ_DMA; } else { if ((u32)buff & 0x01) { LOGFF("Unaligned output address: 0x%08lx (2 byte)\n", (u32)buff); return -1; } cmd = (req->cmd & 1) ? ATA_CMD_WRITE_PIO : ATA_CMD_READ_PIO; } #ifdef LOG if (IN8(G1_ATA_ALTSTATUS) & ATA_SR_DRQ) { LOGF("G1_ATA_STATUS=0x%lx\n", IN8(G1_ATA_ALTSTATUS)); } #endif g1_ata_wait_bsydrq(); while(count) { // (I) Select one from LBA28, LBA48; if (dev->lba48) // Sure Drive should support LBA in this case, or you are { // giving a wrong LBA. // LBA48: lba_io[0] = (lba & 0x000000FF) >> 0; lba_io[1] = (lba & 0x0000FF00) >> 8; lba_io[2] = (lba & 0x00FF0000) >> 16; lba_io[3] = (lba & 0xFF000000) >> 24; lba_io[4] = 0; // LBA28 is integer, so 32-bits are enough to access 2TB. lba_io[5] = 0; // LBA28 is integer, so 32-bits are enough to access 2TB. head = 0; // Lower 4-bits of HDDEVSEL are not used here. } else { // LBA28: lba_io[0] = (lba & 0x00000FF) >> 0; lba_io[1] = (lba & 0x000FF00) >> 8; lba_io[2] = (lba & 0x0FF0000) >> 16; lba_io[3] = 0; // These Registers are not used here. lba_io[4] = 0; // These Registers are not used here. lba_io[5] = 0; // These Registers are not used here. head = (lba & 0xF000000) >> 24; } OUT8(G1_ATA_DEVICE_SELECT, (0xE0 | (dev->drive << 4) | head)); if (dev->lba48) { len = (count > 65536) ? 65536 : count; count -= len; if ((req->cmd & 2)) cmd = (req->cmd & 1) ? ATA_CMD_WRITE_DMA_EXT : ATA_CMD_READ_DMA_EXT; else cmd = (req->cmd & 1) ? ATA_CMD_WRITE_PIO_EXT : ATA_CMD_READ_PIO_EXT; OUT8(G1_ATA_SECTOR_COUNT, (u8)(len >> 8)); OUT8(G1_ATA_LBA_LOW, lba_io[3]); OUT8(G1_ATA_LBA_MID, lba_io[4]); OUT8(G1_ATA_LBA_HIGH, lba_io[5]); } else { len = (count > 256) ? 256 : count; count -= len; } OUT8(G1_ATA_SECTOR_COUNT, (u8)(len & 0xff)); OUT8(G1_ATA_LBA_LOW, lba_io[0]); OUT8(G1_ATA_LBA_MID, lba_io[1]); OUT8(G1_ATA_LBA_HIGH, lba_io[2]); if ((req->cmd & 2)) { g1_dma_abort(); if (req->cmd == G1_READ_DMA) { /* Invalidate the dcache over the range of the data. */ if((u32)buff & 0xF0000000) { dcache_inval_range((u32) buff, req->bytes ? req->bytes : (len * sector_size)); } } #if _FS_READONLY == 0 else { /* Flush the dcache over the range of the data. */ dcache_flush_range((u32) buff, len * sector_size); } #endif /* Set the DMA parameters up. */ OUT32(G1_ATA_DMA_PRO, G1_ATA_DMA_PRO_SYSMEM); OUT32(G1_ATA_DMA_ADDRESS, ((u32) buff & 0x0FFFFFFF)); OUT32(G1_ATA_DMA_LENGTH, req->bytes ? req->bytes : (len * sector_size)); OUT8(G1_ATA_DMA_DIRECTION, (req->cmd == G1_READ_DMA)); /* Enable G1 DMA. */ OUT8(G1_ATA_DMA_ENABLE, 1); } g1_ata_wait_nbsy(); g1_ata_wait_drdy(); OUT8(G1_ATA_COMMAND_REG, cmd); if (req->cmd == G1_READ_PIO) { OUT8(G1_ATA_CTL, 2); g1_pio_reset(len * sector_size); // g1_pio_xfer((u32)buff, len * sector_size); g1_pio_trans = 1; for (u32 i = 0; i < len; ++i){ if (g1_ata_wait_drq()) { LOGFF("Error, status=%02x\n", IN8(G1_ATA_ALTSTATUS)); break; } for (u32 w = 0; w < (sector_size >> 1); ++w) { u16 word = IN16(G1_ATA_DATA); buff[0] = word; buff[1] = word >> 8; buff += 2; } } g1_ata_ack_irq(); g1_ata_wait_bsydrq(); g1_pio_reset(0); OUT8(G1_ATA_CTL, 0); } #if _FS_READONLY == 0 else if (req->cmd == G1_WRITE_PIO) { OUT8(G1_ATA_CTL, 2); for (u32 i = 0; i < len; i++) { // dcache_pref_range((u32)buff, sector_size); g1_ata_wait_nbsy(); for (u32 j = 0; j < sector_size >> 1; ++j) { OUT16(G1_ATA_DATA, (u16)(buff[0] | buff[1] << 8)); buff += 2; } // dcache_purge_range(((u32)buff) - sector_size, sector_size); } OUT8(G1_ATA_COMMAND_REG, dev->lba48 ? ATA_CMD_CACHE_FLUSH_EXT : ATA_CMD_CACHE_FLUSH); g1_ata_wait_bsydrq(); g1_ata_ack_irq(); OUT8(G1_ATA_CTL, 0); } #endif else { /* Start the DMA transfer. */ OUT8(G1_ATA_DMA_STATUS, 1); if (req->async) { return 0; } buff += len; g1_ata_wait_dma(); OUT8(G1_ATA_DMA_ENABLE, 0); if (g1_ata_ack_irq() < 0) { return -1; } g1_ata_wait_bsydrq(); } } return 0; } #if defined(LOG) && defined(DEBUG) static const s8 *dev_fs_name[] = { "FAT16", "FAT16B", "FAT32", "FAT32X", "EXT2"}; void g1_get_partition(void) { s32 i, j; u8 buff[0x200]; struct ide_req req; req.buff = (void *) buff; req.cmd = G1_READ_PIO; req.count = 1; req.lba = 0; //Опрашиваем все ATA устройства и получаем от каждого таблицу разделов: for(i = 0; i < MAX_DEVICE_COUNT; i++) { if(!ide_devices[i].reserved || ide_devices[i].type != IDE_ATA) continue; req.dev = &ide_devices[i]; if(g1_ata_access(&req)) continue; /* Make sure the ATA disk uses MBR partitions. TODO: Support GPT partitioning at some point. */ if(((u16 *)buff)[0xFF] != 0xAA55) { LOGFF("ATA device doesn't appear to have a MBR %04X\n", ((u16 *)buff)[0xFF]); continue; } memcpy(ide_devices[i].pt, (struct pt_struct *)(&buff[0x1BE]), 0x40); for (j = 0; j < 4; j++) { if (!ide_devices[i].pt[j].sect_total) continue; u8 type = 0; switch (ide_devices[i].pt[j].type_part) { case 0x00: type = 0; break; case 0x04: type = 1; break; case 0x06: type = 2; break; case 0x0B: type = 3; break; case 0x0C: type = 4; break; case 0x83: type = 5; break; case 0x07: type = 6; break; case 0x05: case 0x0F: case 0xCF: type = 7; break; default: type = 8; break; } if (!type) { LOGF("%s device don't have partitions\n", dev_bus_name[ide_devices[i].drive]); break; } else if (type < 6) { LOGF("%s device part%d %s - %ld Kb\n", dev_bus_name[ide_devices[i].drive], j, dev_fs_name[type - 1], ide_devices[i].pt[j].sect_total >> 1); } else if (type < 8) { LOGF("%s device part%d EXTENDED partition don't supported\n", dev_bus_name[ide_devices[i].drive], j); } else { LOGF("%s device part%d partition type 0x%02X don't supported\n", dev_bus_name[ide_devices[i].drive], j, ide_devices[i].pt[j].type_part); } ide_devices[i].pt_num++; } } return; } #endif s32 g1_ata_read_blocks(u64 block, size_t count, u8 *buf, u8 wait_dma) { const u8 drive = 1; // TODO struct ide_req req; req.buff = buf; req.count = count; req.bytes = 0; req.dev = &ide_devices[drive & 1]; req.cmd = fs_dma_enabled() ? G1_READ_DMA : G1_READ_PIO; req.lba = block; req.async = (wait_dma || req.cmd == G1_READ_PIO) ? 0 : 1; // g1_dma_part_avail = 0; DBGF("G1_ATA_READ: %ld %d 0x%08lx %s[%d] %s\n", (uint32)block, count, (uint32)buf, req.cmd == G1_READ_DMA ? "DMA" : "PIO", fs_dma_enabled(), req.async ? "ASYNC" : "BLOCKED"); return g1_ata_access(&req); } #if _FS_READONLY == 0 s32 g1_ata_write_blocks(u64 block, size_t count, const u8 *buf, u8 wait_dma) { const u8 drive = 1; // TODO struct ide_req req; req.buff = (u8 *)buf; req.count = count; req.bytes = 0; req.dev = &ide_devices[drive & 1]; req.cmd = fs_dma_enabled() ? G1_WRITE_DMA : G1_WRITE_PIO; req.lba = block; req.async = (wait_dma || req.cmd == G1_WRITE_PIO) ? 0 : 1; DBGF("G1_ATA_WRITE: %ld %d 0x%08lx %s[%d] %s\n", (uint32)block, count, (uint32)buf, req.cmd == G1_WRITE_DMA ? "DMA" : "PIO", fs_dma_enabled(), req.async ? "ASYNC" : "BLOCKED"); return g1_ata_access(&req); } #endif #if 0 s32 g1_ata_read_lba_dma_part(u64 sector, size_t bytes, u8 *buf) { LOGF("G1_ATA_PART: b=%d a=%d", bytes, g1_dma_part_avail); if (g1_dma_part_avail > 0) { LOGF(" continue\n"); g1_dma_part_avail -= bytes; g1_dma_start((u32)buf, bytes); return 0; } if (bytes > 512) { g1_dma_part_avail = 512 - (bytes % 512); } else { g1_dma_part_avail = 512 - bytes; } const u8 drive = 1; // TODO struct ide_req req; req.buff = buf; req.count = (bytes / 512) + 1; req.bytes = bytes; req.dev = &ide_devices[drive & 1]; req.cmd = G1_READ_DMA; req.lba = sector; req.async = 1; LOGF(" read c=%d a=%d\n", req.count, g1_dma_part_avail); return g1_ata_access(&req); } #endif s32 g1_ata_pre_read_lba(u64 sector, size_t count) { const u8 drive = 1; // TODO struct ide_device *dev = &ide_devices[drive & 1]; u8 lba_io[6]; DBGF("G1_ATA_PRE_READ: s=%ld c=%ld\n", (uint32)sector, count); if (fs_dma_enabled()) { g1_dma_abort(); } // LBA48 only lba_io[0] = (sector & 0x000000FF) >> 0; lba_io[1] = (sector & 0x0000FF00) >> 8; lba_io[2] = (sector & 0x00FF0000) >> 16; lba_io[3] = (sector & 0xFF000000) >> 24; lba_io[4] = 0; lba_io[5] = 0; #ifdef LOG if (IN8(G1_ATA_ALTSTATUS) & ATA_SR_DRQ) { LOGF("G1_ATA_STATUS=0x%lx\n", IN8(G1_ATA_ALTSTATUS)); } #endif g1_ata_wait_bsydrq(); OUT8(G1_ATA_DEVICE_SELECT, (0xE0 | (dev->drive << 4))); OUT8(G1_ATA_SECTOR_COUNT, (u8)(count >> 8)); OUT8(G1_ATA_LBA_LOW, lba_io[3]); OUT8(G1_ATA_LBA_MID, lba_io[4]); OUT8(G1_ATA_LBA_HIGH, lba_io[5]); OUT8(G1_ATA_SECTOR_COUNT, (u8)(count & 0xff)); OUT8(G1_ATA_LBA_LOW, lba_io[0]); OUT8(G1_ATA_LBA_MID, lba_io[1]); OUT8(G1_ATA_LBA_HIGH, lba_io[2]); g1_ata_wait_bsydrq(); if (fs_dma_enabled()) { // g1_dma_part_avail = 0; OUT8(G1_ATA_COMMAND_REG, ATA_CMD_READ_DMA_EXT); } else { OUT8(G1_ATA_COMMAND_REG, ATA_CMD_READ_PIO_EXT); g1_pio_reset(count * 512); } return 0; } void g1_ata_raise_interrupt(u64 sector) { const size_t count = 1; const u8 drive = 1; // TODO struct ide_device *dev = &ide_devices[drive & 1]; u8 lba_io[6]; u8 status = 0; LOGF("G1_ATA_IRQ_RAISE: %ld 0x%lx\n", sector, IN8(G1_ATA_ALTSTATUS)); // LBA48 only lba_io[0] = (sector & 0x000000FF) >> 0; lba_io[1] = (sector & 0x0000FF00) >> 8; lba_io[2] = (sector & 0x00FF0000) >> 16; lba_io[3] = (sector & 0xFF000000) >> 24; lba_io[4] = 0; lba_io[5] = 0; g1_ata_wait_bsydrq(); OUT8(G1_ATA_DEVICE_SELECT, (0xE0 | (dev->drive << 4))); OUT8(G1_ATA_SECTOR_COUNT, (u8)(count >> 8)); OUT8(G1_ATA_LBA_LOW, lba_io[3]); OUT8(G1_ATA_LBA_MID, lba_io[4]); OUT8(G1_ATA_LBA_HIGH, lba_io[5]); OUT8(G1_ATA_SECTOR_COUNT, (u8)(count & 0xff)); OUT8(G1_ATA_LBA_LOW, lba_io[0]); OUT8(G1_ATA_LBA_MID, lba_io[1]); OUT8(G1_ATA_LBA_HIGH, lba_io[2]); g1_ata_wait_bsydrq(); OUT8(G1_ATA_COMMAND_REG, ATA_CMD_READ_PIO_EXT); // OUT8(G1_ATA_CTL, 2); do { status = IN8(G1_ATA_ALTSTATUS); } while(!(status & ATA_SR_DRQ)); // g1_ata_ack_irq(); // OUT8(G1_ATA_CTL, 0); for (u32 w = 0; w < 256; ++w) { u16 d = IN16(G1_ATA_DATA); d++; // Prevent gcc optimization on register reading. } } s32 g1_ata_poll(void) { int rv = 0; if(!exception_inside_int() && g1_dma_in_progress()) { rv = g1_dma_transfered(); return rv > 0 ? rv : 1; } if (g1_dma_irq_visible == 0) { rv = g1_ata_ack_irq(); } // if(!g1_dma_part_avail) { OUT8(G1_ATA_DMA_ENABLE, 0); // } return rv; } #if _USE_MKFS && !_FS_READONLY u64 g1_ata_max_lba(void) { const u8 drive = 1; // TODO return ide_devices[drive & 1].max_lba; } #endif s32 g1_ata_flush(void) { // TODO return 0; } #endif /* DEV_TYPE_IDE */ /** * GD ATAPI PIO IRQ: First one for packed command and then two for every sector ready/end (2048 bytes). * IDE ATA PIO IRQ: Two for every sector ready/end (512 bytes). * * Need to keep one extra interrupt to simulate packet command * and filter other extra interrupts due to sector size difference. */ void g1_pio_reset(size_t total_bytes) { g1_pio_total = total_bytes; g1_pio_avail = g1_pio_total; g1_pio_trans = 0; } void g1_pio_xfer(u32 addr, size_t bytes) { u16 *buff = (u16 *)addr; u32 words_count = bytes >> 1; const u32 ide_sec_size = 512; const u32 gd_sec_size = 2048; g1_pio_trans = 1; for(u32 w = 0; w < words_count; ++w) { u32 transfered = g1_pio_total - g1_pio_avail; u32 gd_sec_remain = (transfered % gd_sec_size); if (gd_sec_remain == 0 || gd_sec_remain == ide_sec_size || transfered == gd_sec_size >> 1) { OUT8(G1_ATA_CTL, 0); } else if (gd_sec_remain == (gd_sec_size - ide_sec_size) && transfered != ide_sec_size) { OUT8(G1_ATA_CTL, 2); } if ((transfered % ide_sec_size) == 0) { if (g1_ata_wait_drq()) { LOGFF("Error, status=%02x\n", IN8(G1_ATA_ALTSTATUS)); break; } } buff[w] = IN16(G1_ATA_DATA); g1_pio_avail -= 2; if (g1_pio_avail == 0) { break; } } g1_pio_trans = 0; if (g1_pio_avail == 0) { OUT8(G1_ATA_CTL, 0); } } void g1_pio_abort(void) { g1_pio_reset(0); } u32 g1_pio_in_progress(void) { return g1_pio_trans; } u32 g1_pio_transfered(void) { return g1_pio_total - g1_pio_avail; } void g1_ata_xfer(u32 addr, size_t bytes) { if (fs_dma_enabled()) { g1_dma_start(addr, bytes); } else { g1_pio_xfer(addr, bytes); } } u32 g1_ata_in_progress(void) { if (fs_dma_enabled()) { return g1_dma_in_progress(); } else { return g1_pio_in_progress(); } } u32 g1_ata_transfered(void) { if (fs_dma_enabled()) { return g1_dma_transfered(); } else { return g1_pio_transfered(); } } void g1_ata_abort(void) { if (fs_dma_enabled()) { g1_dma_abort(); } else { g1_pio_abort(); } OUT8(G1_ATA_DEVICE_SELECT, 0x10); OUT8(G1_ATA_FEATURES, 0); g1_ata_wait_nbsy(); OUT8(G1_ATA_COMMAND_REG, 0); g1_ata_wait_bsydrq(); } s32 g1_ata_ack_irq(void) { /* Ack device IRQ. */ u8 st = IN8(G1_ATA_STATUS_REG); DBGF("G1_ATA_ACK_IRQ: %02lx\n", st); if(st & ATA_SR_ERR || st & ATA_SR_DF) { LOGFF("ERR=%d DRQ=%d DSC=%d DF=%d DRDY=%d BSY=%d\n", (st & ATA_SR_ERR ? 1 : 0), (st & ATA_SR_DRQ ? 1 : 0), (st & ATA_SR_DSC ? 1 : 0), (st & ATA_SR_DF ? 1 : 0), (st & ATA_SR_DRDY ? 1 : 0), (st & ATA_SR_BSY ? 1 : 0)); return -1; } return 0; } s32 g1_ata_has_irq() { return (ASIC_IRQ_STATUS[ASIC_MASK_EXT_INT] & ASIC_EXT_GD_CMD); } s32 g1_bus_init(void) { s32 count = g1_dev_scan(); if (!count) { return -1; } #if defined(DEV_TYPE_IDE) && defined(DEBUG) g1_get_partition(); #endif return 0; } #ifdef DEV_TYPE_GD static s32 ide_polling(u8 advanced_check) { u8 i; // (I) Delay 400 nanosecond for BSY to be set: // ------------------------------------------------- for(i = 0; i < 4; i++) IN8(G1_ATA_ALTSTATUS); // Reading the Alternate Status port wastes 100ns; loop four times. // (II) Wait for BSY to be cleared: // ------------------------------------------------- g1_ata_wait_nbsy(); if (advanced_check) { u8 state = IN8(G1_ATA_STATUS_REG); // Read Status Register. // (III) Check For Errors: // ------------------------------------------------- if (state & ATA_SR_ERR) return -2; // Error. // (IV) Check If Device fault: // ------------------------------------------------- if (state & ATA_SR_DF) return -1; // Device Fault. // (V) Check DRQ: // ------------------------------------------------- // BSY = 0; DF = 0; ERR = 0 so we should check for DRQ now. if ((state & ATA_SR_DRQ) == 0) return -3; // DRQ should be set } return 0; // No Error. } static void send_packet_command(u8 *cmd_buff, u8 drive) { s32 i; /* В соответствии с алгоритмом ждем нулевого значения битов BSY и DRQ */ g1_ata_wait_bsydrq(); /* Выбираем устройство и в его регистр команд записываем код пакетной команды */ OUT8(G1_ATA_DEVICE_SELECT, 0xA0 | (drive << 4)); OUT8(G1_ATA_COMMAND_REG, ATAPI_CMD_PACKET); /* Ждём сброса бита BSY и установки DRQ */ if (ide_polling(1)) return; /* Записываем в регистр данных переданный 12-байтный командный пакет */ for(i = 0; i < 6; i++) OUT16(G1_ATA_DATA, ((u16 *)cmd_buff)[i]); /* Ждём сброса бита BSY и установки DRDY */ g1_ata_wait_nbsy(); g1_ata_wait_drdy(); } static s32 send_packet_data_command(u16 data_len, u8 *cmd_buff, u8 drive, u8 dma) { s32 i, err; /* Ожидаем сброса битов BSY и DRQ */ g1_ata_wait_bsydrq(); /* Выбираем устройство */ OUT8(G1_ATA_DEVICE_SELECT, 0xA0 | (drive << 4)); /* В младший байт счетчика байтов (CL) заносим размер запрашиваемых данных */ OUT8(G1_ATA_LBA_MID, (data_len & 0xff)); OUT8(G1_ATA_LBA_HIGH, (data_len >> 8)); OUT8(G1_ATA_FEATURES, dma); /* В регистр команд записываем код пакетной команды */ OUT8(G1_ATA_COMMAND_REG, ATAPI_CMD_PACKET); /* Ждём установки бита DRQ */ if ((err = ide_polling(1))) return err; /* В регистр данных записываем 12-байтный командный пакет */ for(i = 0; i < 6; i++) OUT16(G1_ATA_DATA, ((u16 *)cmd_buff)[i]); /* Ждём завершения команды - установленного бита DRQ. Если произошла ошибка - фиксируем этот факт */ err = ide_polling(1); return err; } static void wait_while_ready(struct ide_device *dev) { u8 cmd_buff[12]; if (!dev->reserved || dev->type == IDE_ATA) return; memset((void *)cmd_buff, 0, 12); send_packet_command(cmd_buff, dev->drive); } void close_cdrom(u8 drive) { u8 cmd_buff[12]; struct ide_device *dev = &ide_devices[drive & 1]; if (!dev->reserved || dev->type != IDE_ATAPI) return; memset((void *)cmd_buff, 0, 12); cmd_buff[0] = ATAPI_CMD_EJECT; // код команды START/STOP UNIT cmd_buff[4] = 0x3; // LoEj = 1, Start = 1 send_packet_command(cmd_buff, dev->drive); } void open_cdrom(u8 drive) { u8 cmd_buff[12]; struct ide_device *dev = &ide_devices[drive & 1]; if (!dev->reserved || dev->type == IDE_ATA) return; memset((void *)cmd_buff, 0, 12); if (dev->type == IDE_ATAPI) { cmd_buff[0] = ATAPI_CMD_EJECT; cmd_buff[4] = 0x2; // LoEj = 1, Start = 0 } else cmd_buff[0] = SPI_CMD_EJECT; send_packet_command(cmd_buff, dev->drive); } static cd_sense_t *request_sense(u8 drive) { s32 i = 0; u8 cmd_buff[12]; u8 type = (ide_devices[drive].type == IDE_ATAPI) ? 0 : 4; u8 sense_buff[14-type]; static cd_sense_t sense; #define SK (sense_buff[2] & 0x0F) #define ASC sense_buff[12-type] #define ASCQ sense_buff[13-type] memset((void *)cmd_buff, 0, 12); memset((void *)sense_buff, 0, 14 - type); /* Формируем пакетную команду REQUEST SENSE. Из блока sense data считываем первые 14 байт - * этого нам хватит, чтобы определить причину ошибки */ cmd_buff[0] = 0x3 + (type << 2); cmd_buff[4] = 14-type; /* Посылаем устройству команду и считываем sense data */ if(send_packet_data_command(14-type, cmd_buff, drive, 0) < 0) { LOGF("Error request sense\n"); sense.sk = 0XFF; return &sense; } for(i = 0; i < ((14-type) >> 1); i++) ((u16 *)sense_buff)[i] = IN16(G1_ATA_DATA); if (ide_polling(1)) { return NULL; } if (SK) { LOGF("SK/ASC/ASCQ: 0x%X/0x%X/0x%X\n", SK, ASC, ASCQ); sense.sk = SK; sense.asc = ASC; sense.ascq = ASCQ; return &sense; } return NULL; } static s32 read_toc(u8 drive) { struct ide_device *dev = &ide_devices[drive & 1]; if (!dev->reserved || (dev->type != IDE_ATAPI && dev->type != IDE_SPI)) return -1; s32 i, j = 0, n, total_tracks; u8 cmd_buff[12]; u16 toc_len = (dev->type == IDE_ATAPI) ? 804 : 408; // toc_len - размер TOC u8 data_buff[toc_len]; /* Формируем пакетную команду. Поле Track/Session Number содержит 0, * по команде READ TOC будет выдана информация обо всех треках диска, * начиная с первого */ memset((void *)cmd_buff, 0, 12); if (dev->type == IDE_ATAPI) { j = 1; cmd_buff[0] = ATAPI_CMD_READ_TOC; cmd_buff[7] = (u8)(toc_len >> 8); cmd_buff[8] = (u8) toc_len; } else { j = (dev->cd_info.disc_type == CD_GDROM) ? 2 : 1; cmd_buff[0] = SPI_CMD_READ_TOC; cmd_buff[3] = (u8)(toc_len >> 8); cmd_buff[4] = (u8) toc_len; } for (n = 0; n < j; n++) { //wait_while_ready(dev); /* Отправляем устройству сформированную пакетную команду */ if(send_packet_data_command(toc_len, cmd_buff, dev->drive, 0) < 0) { request_sense(dev->drive); return -1; } if (dev->type == IDE_ATAPI) { toc_len = swap16(IN16(G1_ATA_DATA)); /* Считываем результат */ for(i = 0; i < (toc_len >> 1); i++) ((u16 *)data_buff)[i] = IN16(G1_ATA_DATA); /* Номер последнего трека на диске */ total_tracks = data_buff[1]; for (i = 0; i < 99; i++) if (i < total_tracks) { dev->cd_info.tocs[0].entry[i] = (u32)((swap8(data_buff[i*8+2+1]) << 24) | (data_buff[i*8+2+5] << 16) | (data_buff[i*8+2+6] << 8 ) | data_buff[i*8+2+7]); //dev->cd_info.tocs[0].entry[i] += 150; } else dev->cd_info.tocs[0].entry[i] = (u32) -1; dev->cd_info.tocs[0].first = (u32)((swap8(data_buff[3]) << 24) | (data_buff[0] << 16) ); dev->cd_info.tocs[0].last = (u32)((swap8(data_buff[(total_tracks-1)*8+3]) << 24) | (data_buff[1] << 16) ); dev->cd_info.tocs[0].leadout_sector = (u32)((swap8(data_buff[total_tracks*8+2+1]) << 24) | (data_buff[total_tracks*8+2+5] << 16) | (data_buff[total_tracks*8+2+6] << 8 ) | data_buff[total_tracks*8+2+7] ); } else { for (i = 0; i < (toc_len >> 2); i++) { ((u32 *)&dev->cd_info.tocs[n])[i] = ((swap16(IN16(G1_ATA_DATA)) << 16) | swap16(IN16(G1_ATA_DATA))); } cmd_buff[1] = 1; } } #if 0 for (n = 0; n < j; n++) { /* Отобразим результаты чтения TOC */ LOGF("Session: %d\t", n); LOGF("First: %d\t", (u8) (dev->cd_info.tocs[n].first >> 16)); LOGF("Last: %d\n\n" , (u8) (dev->cd_info.tocs[n].last >> 16)); total_tracks = (s32)((dev->cd_info.tocs[n].last >> 16) & 0xFF); for(i = ((u8) (dev->cd_info.tocs[n].first >> 16)) - 1; i < total_tracks; i++) LOGF("track: %d\tlba: %05lu\tadr/cntl: %02X\n", (i + 1), (dev->cd_info.tocs[n].entry[i] & 0xffffff), (u8)(dev->cd_info.tocs[n].entry[i] >> 24)); LOGF("lead out \tlba: %lu\tadr/cntl: %02X\n\n", (dev->cd_info.tocs[n].leadout_sector & 0xffffff), (u8)(dev->cd_info.tocs[n].leadout_sector >> 24)); } #endif return 0; } s32 cdrom_get_status(s32 *status, u8 *disc_type, u8 drive) { struct ide_device *dev = &ide_devices[drive & 1]; u8 cmd_buff[12]; u8 stat, type; s32 i = 0; cd_sense_t *sense; memset((void *)cmd_buff, 0, 12); wait_while_ready(dev); if (dev->type == IDE_ATAPI) { cmd_buff[0] = ATAPI_CMD_MODE_SENSE; cmd_buff[2] = 0x0D; cmd_buff[8] = 4; while (send_packet_data_command(4, cmd_buff, dev->drive, 0) < 0) { i++; sense = request_sense(dev->drive); if (!sense) break; if (!(sense->sk == 6 && sense->asc == 0x29) || i > 20) return ERR_DISC_CHG; wait_while_ready(dev); } if (swap16(IN16(G1_ATA_DATA)) != 0x0E) return ERR_NO_DISC; type = (u8) IN16(G1_ATA_DATA); sense = request_sense(dev->drive); if (sense) return ERR_SYS; LOGFF("Disc type: %02X\n",type); if (type < 0x40) { switch (type & 0xF) { case 1: case 5: if (status) *status = CD_STATUS_PLAYING; if (disc_type) *disc_type = CD_CDROM; break; case 2: case 6: if (status) *status = CD_STATUS_PLAYING; if (disc_type) *disc_type = CD_CDDA; break; case 3: case 4: case 7: case 8: if (status) *status = CD_STATUS_PLAYING; if (disc_type) *disc_type = CD_CDROM_XA; break; default: if (status) *status = CD_STATUS_NODISC; return ERR_NO_DISC; break; } return ERR_OK; } else if ((type & 0xF0) == 0x40) { if (status) *status = CD_STATUS_PLAYING; if (disc_type) *disc_type = CD_DVDROM; return ERR_OK; } else if (type == 0x71) { if (status) *status = CD_STATUS_OPEN; return ERR_NO_DISC; } if (status) *status = CD_STATUS_NODISC; return ERR_NO_DISC; } else if (dev->type == IDE_SPI) { cmd_buff[0] = SPI_CMD_REQ_STAT; cmd_buff[4] = 2; if (send_packet_data_command(4, cmd_buff, dev->drive, 0) < 0) { sense = request_sense(dev->drive); if (sense) switch (sense->sk) { case 2: case 6: LOGFF("NO DISC\n"); if (status) *status = CD_STATUS_NODISC; return ERR_NO_DISC; break; default: LOGF("SK = %02X\tASC = %02X\tASCQ = %02X\n", sense->sk, sense->asc, sense->ascq); } return ERR_SYS; } u16 a = swap16(IN16(G1_ATA_DATA)); stat = ((a >> 8) & 0xF); type = ((a >> 4) & 0xF); sense = request_sense(dev->drive); if (sense) switch (sense->sk) { case 0: break; case 1: case 3: case 4: case 5: return ERR_SYS; break; case 2: case 6: LOGFF("NO DISC"); if (status) *status = CD_STATUS_NODISC; return ERR_NO_DISC; break; default: return ERR_SYS; break; } #ifdef DEBUG const s8 *status_name[] = { "BUSY", "PAUSE", "STANDBY", "PLAY", "SEEK", "SCAN", "OPEN", "NO DISC", "RETRY","ERROR" }; const s8 *disc_type_name[] = { "CD-DA", "CD-ROM", "CD-ROM XA", "CD-I", NULL, NULL, NULL, NULL, "GD-ROM" }; DBGF("Status: %s, disc type: %s\n", status_name[stat], disc_type_name[type]); #endif if (status) *status = stat; switch (stat) { case CD_STATUS_NODISC: return ERR_NO_DISC; break; } if (disc_type) *disc_type = type << 4; } else return ERR_SYS; return ERR_OK; } static s32 send_packet_dma_command(u8 *cmd_buff, u8 drive, s32 timeout, u8 async) { s32 i, err; g1_ata_wait_bsydrq(); /* Выбираем устройство */ OUT8(G1_ATA_DEVICE_SELECT, 0xA0 | (drive << 4)); g1_ata_wait_bsydrq(); OUT8(G1_ATA_FEATURES, 1); g1_ata_wait_bsydrq(); OUT8(G1_ATA_COMMAND_REG, ATAPI_CMD_PACKET); /* Ждём сброса бита BSY и установки DRQ */ ide_polling(0); /* В регистр данных записываем 12-байтный командный пакет */ for(i = 0; i < 6; i++) OUT16(G1_ATA_DATA, ((u16 *)cmd_buff)[i]); /*if ((err = ide_polling(1))) return err;*/ OUT8(G1_ATA_DMA_ENABLE, 1); OUT8(G1_ATA_DMA_STATUS, 1); (void)timeout; if (!async) { g1_ata_wait_dma(); OUT8(G1_ATA_DMA_ENABLE, 0); } err = ide_polling(1); return err; } static s32 g1_packet_read(struct ide_req *req) { s32 err; u8 cmd_buff[12]; u16 *buff = req->buff; u32 i, j, data_len; switch (req->dev->cd_info.sec_type) { case 0x10: data_len = 1024; break; case 0xF8: data_len = 1176; break; default: return 0; break; } memset((void *)cmd_buff, 0, 12); /* Формируем командный пакет */ if (req->dev->type == IDE_ATAPI) { cmd_buff[2] = (u8)(req->lba >> 24); cmd_buff[3] = (u8)(req->lba >> 16); cmd_buff[4] = (u8)(req->lba >> 8); cmd_buff[5] = (u8)(req->lba >> 0); if (req->dev->cd_info.disc_type != CD_DVDROM) { cmd_buff[0] = ATAPI_CMD_READ_CD; // код команды READ CD cmd_buff[1] = 0; // считываем сектор любого типа (Any Type) cmd_buff[6] = (u8)(req->count >> 16); cmd_buff[7] = (u8)(req->count >> 8); cmd_buff[8] = (u8)(req->count >> 0); cmd_buff[9] = req->dev->cd_info.sec_type; } else { cmd_buff[0] = ATAPI_CMD_READ; // код команды READ cmd_buff[6] = (u8)(req->count >> 24); cmd_buff[7] = (u8)(req->count >> 16); cmd_buff[8] = (u8)(req->count >> 8); cmd_buff[9] = (u8)(req->count >> 0); } } else { cmd_buff[0] = SPI_CMD_READ_CD; cmd_buff[1] = req->dev->cd_info.sec_type << 1; cmd_buff[2] = (u8)(req->lba >> 16); cmd_buff[3] = (u8)(req->lba >> 8); cmd_buff[4] = (u8)(req->lba >> 0); cmd_buff[8] = (u8)(req->count >> 16); cmd_buff[9] = (u8)(req->count >> 8); cmd_buff[10] =(u8)(req->count >> 0); } if (req->cmd & 2) { if ((u32)buff & 0x1f) { LOGFF("Unaligned output address: 0x%08lx (32 byte)\n", (u32)buff); err = -1; goto exit_packet_read; } g1_dma_abort(); OUT32(G1_ATA_DMA_PRO, G1_ATA_DMA_PRO_SYSMEM); OUT32(G1_ATA_DMA_ADDRESS, ((u32) buff) & 0x0FFFFFFF); OUT32(G1_ATA_DMA_LENGTH, req->bytes ? req->bytes : (req->count * (data_len << 1))); OUT8(G1_ATA_DMA_DIRECTION, G1_DMA_TO_MEMORY); send_packet_dma_command(cmd_buff, req->dev->drive, req->count*100+5000, req->async); } else { if ((u32)buff & 0x01) { LOGFF("Unaligned output address: 0x%08lx (2 byte)\n", (u32)buff); err = -1; goto exit_packet_read; } /* Посылаем устройству командный пакет */ if(send_packet_data_command((data_len << 1), cmd_buff, req->dev->drive, (req->cmd >> 1)) < 0) { request_sense(req->dev->drive); err = -1; goto exit_packet_read; } /* Считываем результат */ for (j = 0; j < req->count; j++) { if ((err = ide_polling(1))) goto exit_packet_read; for(i = 0; i < data_len; i++) { buff[(j*data_len)+i] = IN16(G1_ATA_DATA); } } } err = (!request_sense(req->dev->drive)) ? 0 : -1; exit_packet_read: return err; } static s32 spi_check_license(void) { u8 cmd_buff[12]; if (ide_devices[0].type != IDE_SPI) return -1; wait_while_ready(ide_devices); memset((void *)cmd_buff, 0, 12); cmd_buff[0] = 0x70; cmd_buff[1] = 0x1F; send_packet_command(cmd_buff, 0); return 0; } void cdrom_spin_down(u8 drive) { u8 cmd_buff[12]; drive &= 1; if (!ide_devices[drive].reserved) return; memset((void *)cmd_buff, 0, 12); if (ide_devices[drive].type == IDE_SPI) { cmd_buff[0] = SPI_CMD_SEEK; cmd_buff[1] = 3; } else if (ide_devices[drive].type == IDE_ATAPI) { cmd_buff[0] = ATAPI_CMD_EJECT; } else return; send_packet_command(cmd_buff, 0); } void spi_req_mode(void) { u8 cmd_buff[12]; s32 i; memset((void *)cmd_buff, 0, 12); cmd_buff[0] = SPI_CMD_REQ_MODE; cmd_buff[2] = 0x12; cmd_buff[4] = 8; wait_while_ready(ide_devices); send_packet_data_command(8, cmd_buff, 0, 0); for (i = 0; i < 4; i++) IN16(G1_ATA_DATA); } void packet_soft_reset(u8 drive) { drive &= 1; OUT8(G1_ATA_DEVICE_SELECT, 0xA0 | (drive << 4)); OUT8(G1_ATA_COMMAND_REG, 0x08); g1_ata_wait_nbsy(); } s32 cdrom_read_toc(CDROM_TOC *toc_buffer, u8 session, u8 drive) { struct ide_device *dev = &ide_devices[drive & 1]; if (!dev->reserved || (dev->type != IDE_ATAPI && dev->type != IDE_SPI)) return -1; session &= 1; if (session && dev->type != IDE_SPI) return -1; memcpy((void *) toc_buffer, (void *) &dev->cd_info.tocs[session], sizeof(CDROM_TOC)); return 0; } CDROM_TOC *cdrom_get_toc(u8 session, u8 drive) { struct ide_device *dev = &ide_devices[drive & 1]; if (!dev->reserved || (dev->type != IDE_ATAPI && dev->type != IDE_SPI)) return NULL; session &= 1; if (session && dev->type != IDE_SPI) return NULL; return &dev->cd_info.tocs[session]; } /* Locate the LBA sector of the data track; use after reading TOC */ u32 cdrom_locate_data_track(CDROM_TOC *toc) { s32 i, first, last; first = TOC_TRACK(toc->first); last = TOC_TRACK(toc->last); if(first < 1 || last > 99 || first > last) return -1; /* Find the last track which as a CTRL of 4 */ for(i = last; i >= first; i--) { if(TOC_CTRL(toc->entry[i - 1]) == 4 || TOC_CTRL(toc->entry[i - 1]) == 7) return TOC_LBA(toc->entry[i - 1]); } return -1; } void cdrom_set_sector_size(s32 sec_size, u8 drive) { switch (sec_size) { case 2352: ide_devices[drive&1].cd_info.sec_type = 0xF8; break; case 2048: default: ide_devices[drive&1].cd_info.sec_type = 0x10; } } s32 cdrom_reinit(s32 sec_size, u8 drive) { cdrom_set_sector_size(sec_size, drive); if (cdrom_get_status(NULL, &ide_devices[drive].cd_info.disc_type, drive)) return -2; if (ide_devices[drive&1].type == IDE_SPI) spi_check_license(); return read_toc(drive); } s32 cdrom_chk_disc_change(u8 drive) { wait_while_ready(&ide_devices[drive&1]); if (request_sense(drive)) return -1; return 0; } s32 cdrom_cdda_play(u32 start, u32 end, u32 loops, s32 mode) { (void) start; (void) end; (void) loops; (void) mode; return 0; } s32 cdrom_cdda_pause() { return 0; } s32 cdrom_cdda_resume() { return 0; } s32 cdrom_read_sectors(void *buffer, u32 sector, u32 cnt, u8 drive) { struct ide_req req; req.buff = buffer; req.count = cnt; req.dev = &ide_devices[drive & 1]; req.cmd = G1_READ_DMA; req.lba = sector; req.async = 0; g1_dma_part_avail = 0; if ((((u32) buffer) & 0x1f)) { LOGFF("PIO\n"); req.cmd = G1_READ_PIO; } else { LOGFF("DMA\n"); } return g1_packet_read(&req); } s32 cdrom_read_sectors_ex(void *buffer, u32 sector, u32 cnt, u8 async, u8 dma, u8 drive) { struct ide_req req; req.buff = buffer; req.count = cnt; req.bytes = 0; req.dev = &ide_devices[drive & 1]; req.cmd = dma ? G1_READ_DMA : G1_READ_PIO; req.lba = sector; req.async = async; g1_dma_part_avail = 0; if (dma && (((u32) buffer) & 0x1f)) { req.cmd = G1_READ_PIO; req.async = 0; } LOGFF("%s%s READ\n", async ? "ASYNC " : "", dma ? "DMA" : "PIO"); if (dma) { g1_dma_set_irq_mask(fs_dma_enabled() != FS_DMA_HIDDEN); } return g1_packet_read(&req); } s32 cdrom_read_sectors_part(void *buffer, u32 sector, size_t offset, size_t bytes, u8 drive) { if(offset && g1_dma_part_avail > 0) { g1_dma_part_avail -= bytes; g1_dma_start((u32)buffer, bytes); return 0; } g1_dma_part_avail = 512 - bytes; struct ide_req req; req.buff = buffer; req.count = 1; req.bytes = bytes; req.dev = &ide_devices[drive & 1]; req.cmd = G1_READ_DMA; req.lba = sector; req.async = 1; g1_dma_set_irq_mask(1); return g1_packet_read(&req); } s32 cdrom_pre_read_sectors(u32 sector, size_t bytes, u8 drive) { // TODO (void)sector; (void)bytes; (void)drive; return 0; } u8 cdrom_get_dev_type(u8 drive) { return ide_devices[drive].type; } #endif /* DEV_TYPE_GD */ <file_sep>/include/gl/kglx.h // (c) by <NAME> 2002 (http://a128.ch9.de) // under GPL or new BSD license #ifndef KALL_H #define KALL_H #include <kos.h> #include <GL/gl.h> typedef struct { uint32 flags; float x, y, z; float u, v; uint32 argb, oargb; } gl_vertex_t; extern GLuint vert_rgba; extern GLfloat vert_u,vert_v;//KGL-X gldraw.c extern gl_vertex_t *vtxbuf; /* Post-xformed vertex buffer */ extern int vbuf_top,vbuf_size; #define INLINE __inline INLINE void kglVertex3f(float xx,float yy,float zz){ // vtxbuf[vbuf_top].flags = PVR_CMD_VERTEX; vtxbuf[vbuf_top].x = xx; vtxbuf[vbuf_top].y = yy; vtxbuf[vbuf_top].z = zz; // vtxbuf[vbuf_top].w = 1; vtxbuf[vbuf_top].u = vert_u; vtxbuf[vbuf_top].v = vert_v; vtxbuf[vbuf_top].argb = vert_rgba; vtxbuf[vbuf_top++].oargb = 0xff000000; // //Normals // vtxbuf[vbuf_top].nx = nx; // vtxbuf[vbuf_top].ny = ny; // vtxbuf[vbuf_top].nz = nz; } INLINE void kglTexCoord2f(GLfloat u, GLfloat v) { vert_u = u; vert_v = v; } /* glopColor */ #define SET_COLOR(red,green,blue,alpha) \ vert_rgba = ((alpha) << 24) | ((red) << 16) | ((green) << 8) | (blue); INLINE void kglColor4f(GLfloat r, GLfloat g, GLfloat b, GLfloat a) { SET_COLOR((int)(r*0xff),(int)(g*0xff),(int)(b*0xff),(int)(a*0xff)) } INLINE void kglColor3f(GLfloat red, GLfloat green, GLfloat blue) { kglColor4f(red,green,blue,1.0f); } #endif <file_sep>/firmware/aica/codec/play_mp3.c /* Copyright (C) 2006 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <assert.h> #include <stdio.h> #include <string.h> #include "AT91SAM7S64.h" #include "play_mp3.h" #include "mp3dec.h" #include "ff.h" #include "dac.h" #include "profile.h" #define debug_printf static HMP3Decoder hMP3Decoder; static MP3FrameInfo mp3FrameInfo; static unsigned char *read_ptr; static int bytes_left=0, bytes_leftBeforeDecoding=0, err, offset; static int nFrames = 0; static unsigned char *mp3buf; static unsigned int mp3buf_size; static unsigned char allocated = 0; void mp3_init(unsigned char *buffer, unsigned int buffer_size) { mp3buf = buffer; mp3buf_size = buffer_size; mp3_reset(); } void mp3_reset() { read_ptr = NULL; bytes_leftBeforeDecoding = bytes_left = 0; nFrames = 0; } void mp3_alloc() { if (!allocated) assert(hMP3Decoder = MP3InitDecoder()); allocated = 1; } void mp3_free() { if (allocated) MP3FreeDecoder(hMP3Decoder); allocated = 0; } int mp3_refill_inbuffer(FIL *mp3file) { WORD bytes_read; int bytes_to_read; debug_printf("left: %d. refilling inbuffer...\n", bytes_left); if (bytes_left > 0) { // after fseeking backwards the FAT has to be read from the beginning -> S L O W //assert(f_lseek(mp3file, mp3file->fptr - bytes_leftBeforeDecoding) == FR_OK); // better: move unused rest of buffer to the start // no overlap as long as (1024 <= mp3buf_size/2), so no need to use memove memcpy(mp3buf, read_ptr, bytes_left); } bytes_to_read = mp3buf_size - bytes_left; assert(f_read(mp3file, (BYTE *)mp3buf + bytes_left, bytes_to_read, &bytes_read) == FR_OK); if (bytes_read == bytes_to_read) { read_ptr = mp3buf; offset = 0; bytes_left = mp3buf_size; debug_printf("ok. read: %d. left: %d\n", bytes_read, bytes_left); return 0; } else { puts("can't read more data"); return -1; } } int mp3_process(FIL *mp3file) { int writeable_buffer; if (read_ptr == NULL) { if(mp3_refill_inbuffer(mp3file) != 0) return -1; } offset = MP3FindSyncWord(read_ptr, bytes_left); if (offset < 0) { puts("Error: MP3FindSyncWord returned <0"); if(mp3_refill_inbuffer(mp3file) != 0) return -1; } read_ptr += offset; bytes_left -= offset; bytes_leftBeforeDecoding = bytes_left; // check if this is really a valid frame // (the decoder does not seem to calculate CRC, so make some plausibility checks) if (MP3GetNextFrameInfo(hMP3Decoder, &mp3FrameInfo, read_ptr) == 0 && mp3FrameInfo.nChans == 2 && mp3FrameInfo.version == 0) { debug_printf("Found a frame at offset %x\n", offset + read_ptr - mp3buf + mp3file->fptr); } else { puts("this is no valid frame"); // advance data pointer // TODO: handle bytes_left == 0 assert(bytes_left > 0); bytes_left -= 1; read_ptr += 1; return 0; } if (bytes_left < 1024) { if(mp3_refill_inbuffer(mp3file) != 0) return -1; } debug_printf("bytes_leftBeforeDecoding: %i\n", bytes_leftBeforeDecoding); while (dac_fill_dma() == 0); writeable_buffer = dac_get_writeable_buffer(); if (writeable_buffer == -1) { return 0; } debug_printf("wb %i\n", writeable_buffer); //PROFILE_START("MP3Decode"); err = MP3Decode(hMP3Decoder, &read_ptr, &bytes_left, dac_buffer[writeable_buffer], 0); //PROFILE_END(); nFrames++; if (err) { switch (err) { case ERR_MP3_INDATA_UNDERFLOW: puts("ERR_MP3_INDATA_UNDERFLOW"); bytes_left = 0; if(mp3_refill_inbuffer(mp3file) != 0) return -1; break; case ERR_MP3_MAINDATA_UNDERFLOW: /* do nothing - next call to decode will provide more mainData */ puts("ERR_MP3_MAINDATA_UNDERFLOW"); break; default: iprintf("unknown error: %i\n", err); // skip this frame if (bytes_left > 0) { bytes_left --; read_ptr ++; } else { // TODO assert(0); } break; } dac_buffer_size[writeable_buffer] = 0; } else { /* no error */ MP3GetLastFrameInfo(hMP3Decoder, &mp3FrameInfo); debug_printf("Bitrate: %i\r\n", mp3FrameInfo.bitrate); debug_printf("%i samples\n", mp3FrameInfo.outputSamps); debug_printf("Words remaining in first DMA buffer: %i\n", *AT91C_SSC_TCR); debug_printf("Words remaining in next DMA buffer: %i\n", *AT91C_SSC_TNCR); dac_buffer_size[writeable_buffer] = mp3FrameInfo.outputSamps; debug_printf("%lu Hz, %i kbps\n", mp3FrameInfo.samprate, mp3FrameInfo.bitrate/1000); if (dac_set_srate(mp3FrameInfo.samprate) != 0) { iprintf("unsupported sample rate: %lu\n", mp3FrameInfo.samprate); return -1; } } while (dac_fill_dma() == 0); return 0; } <file_sep>/firmware/isoldr/loader/dev/sd/spi.c /** * Copyright (c) 2011-2016 SWAT <http://www.dc-swat.ru> * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Dreamcast SCIF <=> SPI interface * * SCIF SD Card * ----------------------- * RTS (SPI CS) --> /CS * CTS (SPI CLK) --> CLK * TX (SPI DOUT) --> DIN * RX (SPI DIN) <-- DOUT */ #include "spi.h" #include "drivers/sh7750_regs.h" //#define SPI_DEBUG //#define SPI_DEBUG_RW #define MSB 0x80 static uint16 pwork = 0; #define spi_max_speed_delay() /*__asm__("nop\n\tnop\n\tnop\n\tnop\n\tnop")*/ #define RX_BIT() (uint8)(reg_read_16(SCSPTR2) & SCSPTR2_SPB2DT) #define TX_BIT() _pwork = b & MSB ? (_pwork | SCSPTR2_SPB2DT) : (_pwork & ~SCSPTR2_SPB2DT); reg_write_16(SCSPTR2, _pwork) #define CTS_ON() reg_write_16(SCSPTR2, _pwork | SCSPTR2_CTSDT); spi_max_speed_delay() #define CTS_ON_FAST CTS_ON #define CTS_OFF() reg_write_16(SCSPTR2, _pwork & ~SCSPTR2_CTSDT) /** * Initializes the SPI interface. * */ int spi_init() { // TX:1 CTS:0 RTS:1 (spiout:1 spiclk:0 spics:1) pwork = SCSPTR2_SPB2IO | SCSPTR2_CTSIO | SCSPTR2_RTSIO | SCSPTR2_SPB2DT | SCSPTR2_RTSDT; reg_write_16(SCSCR2, 0); reg_write_16(SCSMR2, 0); reg_write_16(SCFCR2, 0); reg_write_16(SCSPTR2, pwork); reg_write_16(SCSSR2, 0); reg_write_16(SCLSR2, 0); reg_write_16(SCSCR2, 0); spi_cs_off(); return 0; } //int spi_shutdown() { // return 0; //} #ifndef NO_SD_INIT // 1.5uSEC delay static void spi_low_speed_delay(void) { // timer_prime(TMU2, 2000000, 0); // timer_clear(TMU2); // timer_start(TMU2); // // while(!timer_clear(TMU2)); // while(!timer_clear(TMU2)); // while(!timer_clear(TMU2)); // timer_stop(TMU2); for (int i = 0; i < 100; ++i) __asm__("nop\n"); } #endif void spi_cs_on() { pwork &= ~SCSPTR2_RTSDT; reg_write_16(SCSPTR2, pwork); } void spi_cs_off() { pwork |= SCSPTR2_RTSDT; reg_write_16(SCSPTR2, pwork); } /** * Sends a byte over the SPI bus. * * \param[in] b The byte to send. */ void spi_send_byte(register uint8 b) { register uint16 _pwork; _pwork = pwork; TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ } /** * Receives a byte from the SPI bus. * * \returns The received byte. */ uint8 spi_rec_byte() { register uint8 b; register uint16 _pwork; _pwork = pwork; b = 0xff; TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ return b; } /** * Send and receive a byte to/from the SPI bus. * * \param[in] b The byte to send. * \returns The received byte. */ uint8 spi_sr_byte(register uint8 b) { register uint16 _pwork; _pwork = pwork; TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ return b; } #ifndef NO_SD_INIT /** * Slow send and receive a byte to/from the SPI bus. * * \param[in] b The byte to send. * \returns The received byte. */ uint8 spi_slow_sr_byte(register uint8 b) { register int cnt; for (cnt = 0; cnt < 8; cnt++) { pwork = b & MSB ? (pwork | SCSPTR2_SPB2DT) : (pwork & ~SCSPTR2_SPB2DT); reg_write_16(SCSPTR2, pwork); spi_low_speed_delay(); pwork |= SCSPTR2_CTSDT; reg_write_16(SCSPTR2, pwork); b = (b << 1) | RX_BIT(); spi_low_speed_delay(); pwork &= ~SCSPTR2_CTSDT; reg_write_16(SCSPTR2, pwork); } return b; } #endif #if _FS_READONLY == 0 /** * Sends data contained in a buffer over the SPI bus. * * \param[in] data A pointer to the buffer which contains the data to send. * \param[in] len The number of bytes to send. */ void spi_send_data(const uint8* data, uint16 len) { #if 0 register uint8 b; register uint16 _pwork; _pwork = pwork; /* Used send/receive byte because only receive works unstable */ while(len) { b = data[0]; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ b = data[1]; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ b = data[2]; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ b = data[3]; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ data += 4; len -= 4; } #else while(len--) spi_send_byte(*data++); #endif } #endif /** * Receives multiple bytes from the SPI bus and writes them to a buffer. * * \param[out] buffer A pointer to the buffer into which the data gets written. * \param[in] len The number of bytes to read. */ void spi_rec_data(uint8* buffer, uint16 len) { register uint8 b; register uint16 _pwork; _pwork = pwork; while(len) { b = 0xff; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ buffer[0] = b; b = 0xff; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ buffer[1] = b; b = 0xff; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ buffer[2] = b; b = 0xff; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ buffer[3] = b; buffer += 4; len -= 4; } } <file_sep>/modules/mp3/libmp3/xingmp3/iup.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** iup.c *************************************************** MPEG audio decoder Layer I/II, mpeg1 and mpeg2 should be portable ANSI C, should be endian independent icup integer version of cup.c mod 10/18/95 mod grouped sample unpack for: Overflow possible in grouped if native int is 16 bit. Rare occurance. 16x16-->32 mult needed. mods 11/15/95 for Layer I 1/5/95 Quick fix, cs_factor can overflow int16 (why?). Typed to int32. mods 1/7/97 warnings ******************************************************************/ /****************************************************************** MPEG audio software decoder portable ANSI c. Decodes all Layer II to 16 bit linear pcm. Optional stereo to mono conversion. Optional output sample rate conversion to half or quarter of native mpeg rate. ------------------------------------- int i_audio_decode_init(MPEG *m, MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit) initilize decoder: return 0 = fail, not 0 = success MPEG_HEAD *h input, mpeg header info (returned by call to head_info) framebytes input, mpeg frame size (returned by call to head_info) reduction_code input, sample rate reduction code 0 = full rate 1 = half rate 0 = quarter rate transform_code input, ignored convert_code input, channel conversion convert_code: 0 = two chan output 1 = convert two chan to mono 2 = convert two chan to left chan 3 = convert two chan to right chan freq_limit input, limits bandwidth of pcm output to specified frequency. Special use. Set to 24000 for normal use. --------------------------------- void i_audio_decode_info( MPEG *m, DEC_INFO *info) information return: Call after audio_decode_init. See mhead.h for information returned in DEC_INFO structure. --------------------------------- IN_OUT i_audio_decode(MPEG *m, unsigned char *bs, void *pcmbuf) decode one mpeg audio frame: bs input, mpeg bitstream, must start with sync word. Caution: may read up to 3 bytes beyond end of frame. pcmbuf output, pcm samples. IN_OUT structure returns: Number bytes conceptually removed from mpeg bitstream. Returns 0 if sync loss. Number bytes of pcm output. *******************************************************************/ /* #include <stdlib.h> */ #include <string.h> #include <stdio.h> #include <float.h> #include <math.h> #include "L3.h" #include "mhead.h" /* mpeg header structure */ #include "jdw.h" /*------------------------------------------------------- NOTE: Decoder may read up to three bytes beyond end of frame. Calling application must ensure that this does not cause a memory access violation (protection fault) ---------------------------------------------------------*/ #ifdef _MSC_VER #pragma warning(disable: 4709) #endif /* Okay to be global -- is read/only */ static int look_joint[16] = { /* lookup stereo sb's by mode+ext */ 64, 64, 64, 64, /* stereo */ 2 * 4, 2 * 8, 2 * 12, 2 * 16, /* joint */ 64, 64, 64, 64, /* dual */ 32, 32, 32, 32, /* mono */ }; /* Okay to be global -- is read/only */ static int bat_bit_master[] = { 0, 5, 7, 9, 10, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48}; void i_sbt_mono(SAMPLEINT * sample, short *pcm, int n); void i_sbt_dual(SAMPLEINT * sample, short *pcm, int n); static void unpack(); /*------------- initialize bit getter -------------*/ static void load_init(MPEGI *m, unsigned char *buf) { m->iup.bs_ptr = buf; m->iup.bits = 0; m->iup.bitbuf = 0; } /*------------- get n bits from bitstream -------------*/ static INT32 load(MPEGI *m, int n) { UINT32 x; if (m->iup.bits < n) { /* refill bit buf if necessary */ while (m->iup.bits <= 24) { m->iup.bitbuf = (m->iup.bitbuf << 8) | *m->iup.bs_ptr++; m->iup.bits += 8; } } m->iup.bits -= n; x = m->iup.bitbuf >> m->iup.bits; m->iup.bitbuf -= x << m->iup.bits; return x; } /*------------- skip over n bits in bitstream -------------*/ static void skip(MPEGI *m, int n) { int k; if (m->iup.bits < n) { n -= m->iup.bits; k = n >> 3; /*--- bytes = n/8 --*/ m->iup.bs_ptr += k; n -= k << 3; m->iup.bitbuf = *m->iup.bs_ptr++; m->iup.bits = 8; } m->iup.bits -= n; m->iup.bitbuf -= (m->iup.bitbuf >> m->iup.bits) << m->iup.bits; } /*--------------------------------------------------------------*/ #define mac_load_check(n) \ if( m->iup.bits < (n) ) { \ while( m->iup.bits <= 24 ) { \ m->iup.bitbuf = (m->iup.bitbuf << 8) | *m->iup.bs_ptr++; \ m->iup.bits += 8; \ } \ } /*--------------------------------------------------------------*/ #define mac_load(n) \ ( m->iup.bits -= n, \ m->iup.bitval = m->iup.bitbuf >> m->iup.bits, \ m->iup.bitbuf -= m->iup.bitval << m->iup.bits, \ m->iup.bitval ) /*======================================================================*/ static void unpack_ba(MPEGI *m) { int i, j, k; static int nbit[4] = {4, 4, 3, 2}; int nstereo; int n; m->iup.bit_skip = 0; nstereo = m->iup.stereo_sb; k = 0; for (i = 0; i < 4; i++) { for (j = 0; j < m->iup.nbat[i]; j++, k++) { mac_load_check(4); n = m->iup.ballo[k] = m->iup.samp_dispatch[k] = m->iup.bat[i][mac_load(nbit[i])]; if (k >= m->iup.nsb_limit) m->iup.bit_skip += bat_bit_master[m->iup.samp_dispatch[k]]; m->iup.c_value[k] = m->iup.look_c_value[n]; m->iup.c_shift[k] = m->iup.look_c_shift[n]; if (--nstereo < 0) { m->iup.ballo[k + 1] = m->iup.ballo[k]; m->iup.samp_dispatch[k] += 18; /* flag as joint */ m->iup.samp_dispatch[k + 1] = m->iup.samp_dispatch[k]; /* flag for sf */ m->iup.c_value[k + 1] = m->iup.c_value[k]; m->iup.c_shift[k + 1] = m->iup.c_shift[k]; k++; j++; } } } m->iup.samp_dispatch[m->iup.nsb_limit] = 37; /* terminate the dispatcher with skip */ m->iup.samp_dispatch[k] = 36; /* terminate the dispatcher */ } /*-------------------------------------------------------------------------*/ static void unpack_sfs(MPEGI *m) /* unpack scale factor selectors */ { int i; for (i = 0; i < m->iup.max_sb; i++) { mac_load_check(2); if (m->iup.ballo[i]) m->iup.sf_dispatch[i] = mac_load(2); else m->iup.sf_dispatch[i] = 4; /* no allo */ } m->iup.sf_dispatch[i] = 5; /* terminate dispatcher */ } /*-------------------------------------------------------------------------*/ /*--- multiply note -------------------------------------------------------*/ /*--- 16bit x 16bit mult --> 32bit >> 15 --> 16 bit or better -----------*/ static void unpack_sf(MPEGI *m) /* unpack scale factor */ { /* combine dequant and scale factors */ int i, n; INT32 tmp; /* only reason tmp is 32 bit is to get 32 bit mult result */ i = -1; dispatch:switch (m->iup.sf_dispatch[++i]) { case 0: /* 3 factors 012 */ mac_load_check(18); tmp = m->iup.c_value[i]; n = m->iup.c_shift[i]; m->iup.cs_factor[0][i] = (tmp * m->iup.sf_table[mac_load(6)]) >> n; m->iup.cs_factor[1][i] = (tmp * m->iup.sf_table[mac_load(6)]) >> n; m->iup.cs_factor[2][i] = (tmp * m->iup.sf_table[mac_load(6)]) >> n; goto dispatch; case 1: /* 2 factors 002 */ mac_load_check(12); tmp = m->iup.c_value[i]; n = m->iup.c_shift[i]; m->iup.cs_factor[1][i] = m->iup.cs_factor[0][i] = (tmp * m->iup.sf_table[mac_load(6)]) >> n; m->iup.cs_factor[2][i] = (tmp * m->iup.sf_table[mac_load(6)]) >> n; goto dispatch; case 2: /* 1 factor 000 */ mac_load_check(6); tmp = m->iup.c_value[i]; n = m->iup.c_shift[i]; m->iup.cs_factor[2][i] = m->iup.cs_factor[1][i] = m->iup.cs_factor[0][i] = (tmp * m->iup.sf_table[mac_load(6)]) >> n; goto dispatch; case 3: /* 2 factors 022 */ mac_load_check(12); tmp = m->iup.c_value[i]; n = m->iup.c_shift[i]; m->iup.cs_factor[0][i] = (tmp * m->iup.sf_table[mac_load(6)]) >> n; m->iup.cs_factor[2][i] = m->iup.cs_factor[1][i] = (tmp * m->iup.sf_table[mac_load(6)]) >> n; goto dispatch; case 4: /* no allo */ goto dispatch; case 5: /* all done */ ; } /* end switch */ } /*-------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------*/ /*--- unpack multiply note ------------------------------------------------*/ /*--- 16bit x 16bit mult --> 32bit or better required---------------------*/ #define UNPACK_N(n) \ s[k] = ((m->iup.cs_factor[i][k]*(load(m,n)-((1 << (n-1)) -1)))>>(n-1)); \ s[k+64] = ((m->iup.cs_factor[i][k]*(load(m,n)-((1 << (n-1)) -1)))>>(n-1)); \ s[k+128] = ((m->iup.cs_factor[i][k]*(load(m,n)-((1 << (n-1)) -1)))>>(n-1)); \ goto dispatch; #define UNPACK_N2(n) \ mac_load_check(3*n); \ s[k] = (m->iup.cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)))>>(n-1); \ s[k+64] = (m->iup.cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)))>>(n-1); \ s[k+128] = (m->iup.cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)))>>(n-1); \ goto dispatch; #define UNPACK_N3(n) \ mac_load_check(2*n); \ s[k] = (m->iup.cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)))>>(n-1); \ s[k+64] = (m->iup.cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)))>>(n-1); \ mac_load_check(n); \ s[k+128] = (m->iup.cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)))>>(n-1); \ goto dispatch; #define UNPACKJ_N(n) \ tmp = (load(m,n)-((1 << (n-1)) -1)); \ s[k] = (m->iup.cs_factor[i][k]*tmp)>>(n-1); \ s[k+1] = (m->iup.cs_factor[i][k+1]*tmp)>>(n-1); \ tmp = (load(m,n)-((1 << (n-1)) -1)); \ s[k+64] = (m->iup.cs_factor[i][k]*tmp)>>(n-1); \ s[k+64+1] = (m->iup.cs_factor[i][k+1]*tmp)>>(n-1); \ tmp = (load(m,n)-((1 << (n-1)) -1)); \ s[k+128] = (m->iup.cs_factor[i][k]*tmp)>>(n-1); \ s[k+128+1] = (m->iup.cs_factor[i][k+1]*tmp)>>(n-1); \ k++; /* skip right chan dispatch */ \ goto dispatch; /*-------------------------------------------------------------------------*/ static void unpack_samp(MPEGI *m) /* unpack samples */ { int i, j, k; SAMPLEINT *s; int n; INT32 tmp; s = m->iup.sample; for (i = 0; i < 3; i++) { /* 3 groups of scale factors */ for (j = 0; j < 4; j++) { k = -1; dispatch:switch (m->iup.samp_dispatch[++k]) { case 0: s[k + 128] = s[k + 64] = s[k] = 0; goto dispatch; case 1: /* 3 levels grouped 5 bits */ mac_load_check(5); n = mac_load(5); s[k] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group3_table[n][0]) >> 1; s[k + 64] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group3_table[n][1]) >> 1; s[k + 128] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group3_table[n][2]) >> 1; goto dispatch; case 2: /* 5 levels grouped 7 bits */ mac_load_check(7); n = mac_load(7); s[k] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group5_table[n][0]) >> 2; s[k + 64] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group5_table[n][1]) >> 2; s[k + 128] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group5_table[n][2]) >> 2; goto dispatch; case 3: UNPACK_N2(3) /* 7 levels */ case 4: /* 9 levels grouped 10 bits */ mac_load_check(10); n = mac_load(10); s[k] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group9_table[n][0]) >> 3; s[k + 64] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group9_table[n][1]) >> 3; s[k + 128] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group9_table[n][2]) >> 3; goto dispatch; case 5: UNPACK_N2(4) /* 15 levels */ case 6: UNPACK_N2(5) /* 31 levels */ case 7: UNPACK_N2(6) /* 63 levels */ case 8: UNPACK_N2(7) /* 127 levels */ case 9: UNPACK_N2(8) /* 255 levels */ case 10: UNPACK_N3(9) /* 511 levels */ case 11: UNPACK_N3(10) /* 1023 levels */ case 12: UNPACK_N3(11) /* 2047 levels */ case 13: UNPACK_N3(12) /* 4095 levels */ case 14: UNPACK_N(13) /* 8191 levels */ case 15: UNPACK_N(14) /* 16383 levels */ case 16: UNPACK_N(15) /* 32767 levels */ case 17: UNPACK_N(16) /* 65535 levels */ /* -- joint ---- */ case 18 + 0: s[k + 128 + 1] = s[k + 128] = s[k + 64 + 1] = s[k + 64] = s[k + 1] = s[k] = 0; k++; /* skip right chan dispatch */ goto dispatch; case 18 + 1: /* 3 levels grouped 5 bits */ n = load(m,5); s[k] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group3_table[n][0]) >> 1; s[k + 1] = ((INT32) m->iup.cs_factor[i][k + 1] * m->iup.group3_table[n][0]) >> 1; s[k + 64] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group3_table[n][1]) >> 1; s[k + 64 + 1] = ((INT32) m->iup.cs_factor[i][k + 1] * m->iup.group3_table[n][1]) >> 1; s[k + 128] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group3_table[n][2]) >> 1; s[k + 128 + 1] = ((INT32) m->iup.cs_factor[i][k + 1] * m->iup.group3_table[n][2]) >> 1; k++; /* skip right chan dispatch */ goto dispatch; case 18 + 2: /* 5 levels grouped 7 bits */ n = load(m,7); s[k] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group5_table[n][0]) >> 2; s[k + 1] = ((INT32) m->iup.cs_factor[i][k + 1] * m->iup.group5_table[n][0]) >> 2; s[k + 64] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group5_table[n][1]) >> 2; s[k + 64 + 1] = ((INT32) m->iup.cs_factor[i][k + 1] * m->iup.group5_table[n][1]) >> 2; s[k + 128] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group5_table[n][2]) >> 2; s[k + 128 + 1] = ((INT32) m->iup.cs_factor[i][k + 1] * m->iup.group5_table[n][2]) >> 2; k++; /* skip right chan dispatch */ goto dispatch; case 18 + 3: UNPACKJ_N(3) /* 7 levels */ case 18 + 4: /* 9 levels grouped 10 bits */ n = load(m,10); s[k] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group9_table[n][0]) >> 3; s[k + 1] = ((INT32) m->iup.cs_factor[i][k + 1] * m->iup.group9_table[n][0]) >> 3; s[k + 64] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group9_table[n][1]) >> 3; s[k + 64 + 1] = ((INT32) m->iup.cs_factor[i][k + 1] * m->iup.group9_table[n][1]) >> 3; s[k + 128] = ((INT32) m->iup.cs_factor[i][k] * m->iup.group9_table[n][2]) >> 3; s[k + 128 + 1] = ((INT32) m->iup.cs_factor[i][k + 1] * m->iup.group9_table[n][2]) >> 3; k++; /* skip right chan dispatch */ goto dispatch; case 18 + 5: UNPACKJ_N(4) /* 15 levels */ case 18 + 6: UNPACKJ_N(5) /* 31 levels */ case 18 + 7: UNPACKJ_N(6) /* 63 levels */ case 18 + 8: UNPACKJ_N(7) /* 127 levels */ case 18 + 9: UNPACKJ_N(8) /* 255 levels */ case 18 + 10: UNPACKJ_N(9) /* 511 levels */ case 18 + 11: UNPACKJ_N(10) /* 1023 levels */ case 18 + 12: UNPACKJ_N(11) /* 2047 levels */ case 18 + 13: UNPACKJ_N(12) /* 4095 levels */ case 18 + 14: UNPACKJ_N(13) /* 8191 levels */ case 18 + 15: UNPACKJ_N(14) /* 16383 levels */ case 18 + 16: UNPACKJ_N(15) /* 32767 levels */ case 18 + 17: UNPACKJ_N(16) /* 65535 levels */ /* -- end of dispatch -- */ case 37: skip(m, m->iup.bit_skip); case 36: s += 3 * 64; } /* end switch */ } /* end j loop */ } /* end i loop */ } /*-------------------------------------------------------------------------*/ static void unpack(MPEGI *m) { int prot; /* at entry bit getter points at id, sync skipped by caller */ load(m,3); /* skip id and option (checked by init) */ prot = load(m,1); /* load prot bit */ load(m,6); /* skip to pad */ m->iup.pad = load(m,1); load(m,1); /* skip to mode */ m->iup.stereo_sb = look_joint[load(m,4)]; if (prot) load(m,4); /* skip to data */ else load(m,20); /* skip crc */ unpack_ba(m); /* unpack bit allocation */ unpack_sfs(m); /* unpack scale factor selectors */ unpack_sf(m); /* unpack scale factor */ unpack_samp(m); /* unpack samples */ } /*-------------------------------------------------------------------------*/ IN_OUT i_audio_decode(MPEGI *m, unsigned char *bs, signed short *pcm) { int sync; IN_OUT in_out; load_init(m,bs); /* initialize bit getter */ /* test sync */ in_out.in_bytes = 0; /* assume fail */ in_out.out_bytes = 0; sync = load(m,12); if (sync != 0xFFF) return in_out; /* sync fail */ /*-----------*/ m->iup.unpack_routine(); m->iup.sbt(m->iup.sample, pcm, m->iup.nsbt); /*-----------*/ in_out.in_bytes = m->iup.framebytes + m->iup.pad; in_out.out_bytes = m->iup.outbytes; return in_out; } /*-------------------------------------------------------------------------*/ #include "iupini.c" /* initialization */ #include "iupL1.c" /* Layer 1 */ /*-------------------------------------------------------------------------*/ <file_sep>/modules/mp3/libmp3/xingmp3/iupL1.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** iupL1.c *************************************************** MPEG audio decoder Layer I mpeg1 and mpeg2 should be portable ANSI C, should be endian independent icupL1 integer version of cupL1.c ******************************************************************/ /*======================================================================*/ /* Read Only */ static int bat_bit_masterL1[] = { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; /*======================================================================*/ static void unpack_baL1(MPEGI *m) { int k; int nstereo; int n; m->iup.bit_skip = 0; nstereo = m->iup.stereo_sb; for (k = 0; k < m->iup.nbatL1; k++) { mac_load_check(4); n = m->iup.ballo[k] = m->iup.samp_dispatch[k] = mac_load(4); if (k >= m->iup.nsb_limit) m->iup.bit_skip += bat_bit_masterL1[m->iup.samp_dispatch[k]]; m->iup.c_value[k] = m->iup.look_c_valueL1[n]; m->iup.c_shift[k] = m->iup.look_c_shiftL1[n]; if (--nstereo < 0) { m->iup.ballo[k + 1] = m->iup.ballo[k]; m->iup.samp_dispatch[k] += 15; /* flag as joint */ m->iup.samp_dispatch[k + 1] = m->iup.samp_dispatch[k]; /* flag for sf */ m->iup.c_value[k + 1] = m->iup.c_value[k]; m->iup.c_shift[k + 1] = m->iup.c_shift[k]; k++; } } m->iup.samp_dispatch[m->iup.nsb_limit] = 31; /* terminate the dispatcher with skip */ m->iup.samp_dispatch[k] = 30; /* terminate the dispatcher */ } /*-------------------------------------------------------------------------*/ static void unpack_sfL1(MPEGI *m) /* unpack scale factor */ { /* combine dequant and scale factors */ int i, n; INT32 tmp; /* only reason tmp is 32 bit is to get 32 bit mult result */ for (i = 0; i < m->iup.nbatL1; i++) { if (m->iup.ballo[i]) { mac_load_check(6); tmp = m->iup.c_value[i]; n = m->iup.c_shift[i]; m->iup.cs_factorL1[i] = (tmp * m->iup.sf_table[mac_load(6)]) >> n; } } /*-- done --*/ } /*-------------------------------------------------------------------------*/ #define UNPACKL1_N(n) s[k] = (m->iup.cs_factorL1[k]*(load(m,n)-((1 << (n-1)) -1)))>>(n-1); \ goto dispatch; #define UNPACKL1J_N(n) tmp = (load(m,n)-((1 << (n-1)) -1)); \ s[k] = (m->iup.cs_factorL1[k]*tmp)>>(n-1); \ s[k+1] = (m->iup.cs_factorL1[k+1]*tmp)>>(n-1); \ k++; /* skip right chan dispatch */ \ goto dispatch; /*-------------------------------------------------------------------------*/ static void unpack_sampL1(MPEGI *m) /* unpack samples */ { int j, k; SAMPLEINT *s; INT32 tmp; s = m->iup.sample; for (j = 0; j < 12; j++) { k = -1; dispatch:switch (m->iup.samp_dispatch[++k]) { case 0: s[k] = 0; goto dispatch; case 1: UNPACKL1_N(2) /* 3 levels */ case 2: UNPACKL1_N(3) /* 7 levels */ case 3: UNPACKL1_N(4) /* 15 levels */ case 4: UNPACKL1_N(5) /* 31 levels */ case 5: UNPACKL1_N(6) /* 63 levels */ case 6: UNPACKL1_N(7) /* 127 levels */ case 7: UNPACKL1_N(8) /* 255 levels */ case 8: UNPACKL1_N(9) /* 511 levels */ case 9: UNPACKL1_N(10) /* 1023 levels */ case 10: UNPACKL1_N(11) /* 2047 levels */ case 11: UNPACKL1_N(12) /* 4095 levels */ case 12: UNPACKL1_N(13) /* 8191 levels */ case 13: UNPACKL1_N(14) /* 16383 levels */ case 14: UNPACKL1_N(15) /* 32767 levels */ /* -- joint ---- */ case 15 + 0: s[k + 1] = s[k] = 0; k++; /* skip right chan dispatch */ goto dispatch; /* -- joint ---- */ case 15 + 1: UNPACKL1J_N(2) /* 3 levels */ case 15 + 2: UNPACKL1J_N(3) /* 7 levels */ case 15 + 3: UNPACKL1J_N(4) /* 15 levels */ case 15 + 4: UNPACKL1J_N(5) /* 31 levels */ case 15 + 5: UNPACKL1J_N(6) /* 63 levels */ case 15 + 6: UNPACKL1J_N(7) /* 127 levels */ case 15 + 7: UNPACKL1J_N(8) /* 255 levels */ case 15 + 8: UNPACKL1J_N(9) /* 511 levels */ case 15 + 9: UNPACKL1J_N(10) /* 1023 levels */ case 15 + 10: UNPACKL1J_N(11) /* 2047 levels */ case 15 + 11: UNPACKL1J_N(12) /* 4095 levels */ case 15 + 12: UNPACKL1J_N(13) /* 8191 levels */ case 15 + 13: UNPACKL1J_N(14) /* 16383 levels */ case 15 + 14: UNPACKL1J_N(15) /* 32767 levels */ /* -- end of dispatch -- */ case 31: skip(m, m->iup.bit_skip); case 30: s += 64; } /* end switch */ } /* end j loop */ /*-- done --*/ } /*-------------------------------------------------------------------------*/ static void unpackL1(MPEGI *m) { int prot; /* at entry bit getter points at id, sync skipped by caller */ load(m,3); /* skip id and option (checked by init) */ prot = load(m,1); /* load prot bit */ load(m,6); /* skip to pad */ m->iup.pad = load(m,1) << 2; load(m,1); /* skip to mode */ m->iup.stereo_sb = look_joint[load(m,4)]; if (prot) load(m,4); /* skip to data */ else load(m,20); /* skip crc */ unpack_baL1(m); /* unpack bit allocation */ unpack_sfL1(m); /* unpack scale factor */ unpack_sampL1(m); /* unpack samples */ } /*-------------------------------------------------------------------------*/ #ifdef _MSC_VER #pragma warning(disable: 4056) #endif int i_audio_decode_initL1(MPEGI *m, MPEG_HEAD * h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit) { int i, k; long samprate; int limit; int stepbit; long step; int bit_code; /*--- sf table built by Layer II init ---*/ if (m->iup.first_pass_L1) { stepbit = 2; step = 4; for (i = 1; i < 16; i++) { m->iup.look_c_valueL1[i] = (int) (32768.0 * 2.0 / (step - 1)); m->iup.look_c_shiftL1[i] = 16 - stepbit; stepbit++; step <<= 1; } m->iup.first_pass_L1 = 0; } m->iup.unpack_routine = unpackL1; transform_code = transform_code; /* not used, asm compatability */ bit_code = 0; if (convert_code & 8) bit_code = 1; convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ if (reduction_code < 0) reduction_code = 0; if (reduction_code > 2) reduction_code = 2; if (freq_limit < 1000) freq_limit = 1000; m->iup.framebytes = framebytes_arg; /* check if code handles */ if (h->option != 3) return 0; /* layer I only */ m->iup.nbatL1 = 32; m->iup.max_sb = m->iup.nbatL1; /*----- compute nsb_limit --------*/ samprate = sr_table[4 * h->id + h->sr_index]; m->iup.nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; /*- caller limit -*/ /*---- limit = 0.94*(32>>reduction_code); ----*/ limit = (32 >> reduction_code); if (limit > 8) limit--; if (m->iup.nsb_limit > limit) m->iup.nsb_limit = limit; if (m->iup.nsb_limit > m->iup.max_sb) m->iup.nsb_limit = m->iup.max_sb; m->iup.outvalues = 384 >> reduction_code; if (h->mode != 3) { /* adjust for 2 channel modes */ m->iup.nbatL1 *= 2; m->iup.max_sb *= 2; m->iup.nsb_limit *= 2; } /* set sbt function */ m->iup.nsbt = 12; k = 1 + convert_code; if (h->mode == 3) { k = 0; } m->iup.sbt = sbt_table[bit_code][reduction_code][k]; m->iup.outvalues *= out_chans[k]; if (bit_code != 0) m->iup.outbytes = m->iup.outvalues; else m->iup.outbytes = sizeof(short) * m->iup.outvalues; m->iup.decinfo.channels = out_chans[k]; m->iup.decinfo.outvalues = m->iup.outvalues; m->iup.decinfo.samprate = samprate >> reduction_code; if (bit_code != 0) m->iup.decinfo.bits = 8; else m->iup.decinfo.bits = sizeof(short) * 8; m->iup.decinfo.framebytes = m->iup.framebytes; m->iup.decinfo.type = 0; /* clear sample buffer, unused sub bands must be 0 */ for (i = 0; i < 768; i++) m->iup.sample[i] = 0; /* init sub-band transform */ i_sbt_init(); return 1; } #ifdef _MSC_VER #pragma warning(default: 4056) #endif /*---------------------------------------------------------*/ <file_sep>/firmware/isoldr/loader/asic.c /** * DreamShell ISO Loader * ASIC IRQ handling * (c)2014-2022 SWAT <http://www.dc-swat.ru> * Based on Netplay VOOT code by <NAME> <<EMAIL>> */ #include <main.h> #include <exception.h> #include <asic.h> #include <cdda.h> #ifdef NO_ASIC_LT void* g1_dma_handler(void *passer, register_stack *stack, void *current_vector); void* maple_dma_handler(void *passer, register_stack *stack, void *current_vector); void* aica_dma_handler(void *passer, register_stack *stack, void *current_vector); void *aica_vsync_handler(void *passer, register_stack *stack, void *current_vector); #endif static asic_lookup_table asic_table; static exception_handler_f old_handler; static void* asic_handle_exception(register_stack *stack, void *current_vector) { uint32 code = *REG_INTEVT; #if 0//def LOG uint32 st = ASIC_IRQ_STATUS[ASIC_MASK_NRM_INT]; if(code == EXP_CODE_INT13 || code == EXP_CODE_INT11 || code == EXP_CODE_INT9) { LOGF("IRQ: 0x%lx NRM: 0x%08lx EXT: 0x%08lx ERR: 0x%08lx\n", *REG_INTEVT & 0x0fff, st, ASIC_IRQ_STATUS[ASIC_MASK_EXT_INT], ASIC_IRQ_STATUS[ASIC_MASK_ERR_INT]); } // dump_regs(stack); #endif #ifdef NO_ASIC_LT /** * Use ASIC handlers directly instead of lookup table */ (void)stack; void *back_vector = current_vector; const uint32 status = ASIC_IRQ_STATUS[ASIC_MASK_NRM_INT]; # if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) const uint32 statusExt = ASIC_IRQ_STATUS[ASIC_MASK_EXT_INT]; const uint32 statusErr = ASIC_IRQ_STATUS[ASIC_MASK_ERR_INT]; if ((status & ASIC_NRM_GD_DMA) || (statusExt & ASIC_EXT_GD_CMD) || (statusErr & (ASIC_ERR_G1DMA_ILLEGAL | ASIC_ERR_G1DMA_OVERRUN | ASIC_ERR_G1DMA_ROM_FLASH)) ) { back_vector = g1_dma_handler(NULL, stack, current_vector); } # endif if (code == EXP_CODE_INT13 || code == EXP_CODE_INT11 || code == EXP_CODE_INT9) { # ifdef HAVE_CDDA if(status & ASIC_NRM_AICA_DMA) { back_vector = aica_dma_handler(NULL, stack, back_vector); } else if ((status & (ASIC_NRM_VSYNC | ASIC_NRM_MAPLE_DMA | ASIC_NRM_GD_DMA))) { back_vector = aica_vsync_handler(NULL, stack, back_vector); } # endif if (status & ASIC_NRM_VSYNC) { apply_patch_list(); } # if defined(HAVE_MAPLE) if(status & ASIC_NRM_MAPLE_DMA) { back_vector = maple_dma_handler(NULL, stack, back_vector); } # endif } // LOGFF("0x%08lx\n", (uint32)back_vector); return back_vector; #else void *new_vector = current_vector; /* Handle exception table */ for (uint32 index = 0; index < ASIC_TABLE_SIZE; index++) { asic_lookup_table_entry passer; /* Technically, this can cause matches on exceptions in cases where the SH4 combines them and/or the exceptions have been placed in a queue. However, this doesn't bother me too much. */ for (int i = 0; i < 3; i++) { passer.mask[i] = ASIC_IRQ_STATUS[i] & asic_table.table[index].mask[i]; } passer.irq = code; passer.clear_irq = asic_table.table[index].clear_irq; if ((passer.mask[ASIC_MASK_NRM_INT] || passer.mask[ASIC_MASK_EXT_INT] || passer.mask[ASIC_MASK_ERR_INT]) && (asic_table.table[index].irq == passer.irq || asic_table.table[index].irq == EXP_CODE_ALL)) { new_vector = asic_table.table[index].handler(&passer, stack, new_vector); /* Clear the IRQ by default - but the option is controllable. */ if (passer.clear_irq) { if(passer.mask[ASIC_MASK_NRM_INT]) { ASIC_IRQ_STATUS[ASIC_MASK_NRM_INT] = passer.mask[ASIC_MASK_NRM_INT]; } if(passer.mask[ASIC_MASK_ERR_INT]) { ASIC_IRQ_STATUS[ASIC_MASK_ERR_INT] = passer.mask[ASIC_MASK_ERR_INT]; } } } } /* Return properly, depending if there is an older handler. */ if (old_handler) return old_handler(stack, new_vector); else return new_vector; #endif } void asic_enable_irq(const asic_lookup_table_entry *entry) { volatile uint32 *mask_base; int i; /* Determine which ASIC IRQ bank, if any, the given mask will be enabled on. */ switch (entry->irq) { case EXP_CODE_INT9: mask_base = ASIC_IRQ9_MASK; break; case EXP_CODE_INT11: mask_base = ASIC_IRQ11_MASK; break; case EXP_CODE_INT13: mask_base = ASIC_IRQ13_MASK; break; case EXP_CODE_ALL: { /* Mask the first two ASIC banks. */ mask_base = ASIC_IRQ9_MASK; for(i = 0; i < 3; i++) { mask_base[i] |= entry->mask[i]; } mask_base = ASIC_IRQ11_MASK; for(i = 0; i < 3; i++) { mask_base[i] |= entry->mask[i]; } /* Have the code further on take care of the last mask. */ mask_base = ASIC_IRQ13_MASK; break; } /* Probably an empty entry. Either way, we can't do anything. */ default: mask_base = NULL; break; } /* Enable the selected G2 IRQs on the ASIC. */ if (mask_base) { for(i = 0; i < 3; i++) { mask_base[i] |= entry->mask[i]; } } } #ifndef NO_ASIC_LT int asic_add_handler(const asic_lookup_table_entry *new_entry, asic_handler_f *parent_handler, int enable_irq) { uint32 index; /* Don't allow adding of handlers until we've initialized. */ if (!asic_table.inited) return 0; /* Scan the entire ASIC table an empty slot. */ for (index = 0; index < ASIC_TABLE_SIZE; index++) { if ((asic_table.table[index].irq == new_entry->irq) && (asic_table.table[index].mask[ASIC_MASK_NRM_INT] == new_entry->mask[ASIC_MASK_NRM_INT]) && (asic_table.table[index].mask[ASIC_MASK_EXT_INT] == new_entry->mask[ASIC_MASK_EXT_INT]) && (asic_table.table[index].mask[ASIC_MASK_ERR_INT] == new_entry->mask[ASIC_MASK_ERR_INT])) { if(parent_handler) *parent_handler = asic_table.table[index].handler; asic_table.table[index].handler = new_entry->handler; return 1; } else if (!(asic_table.table[index].irq)) { /* Ensure there isn't any parent handler given back. */ if(parent_handler) *parent_handler = NULL; /* Enable the IRQ bank on the ASIC as specified by the entry. */ if(enable_irq) asic_enable_irq(new_entry); /* Copy the new entry into our table. */ memcpy(&asic_table.table[index], new_entry, sizeof(asic_lookup_table_entry)); return 1; } } return 0; } #endif void asic_init(void) { exception_table_entry new_entry; /* Ensure we can't initialize ourselves twice. */ if (asic_table.inited) { #ifndef NO_ASIC_LT /* Reinitialize the active IRQs on the ASIC. */ // for (int index = 0; index < ASIC_TABLE_SIZE; index++) // asic_enable_irq(&asic_table.table[index]); #endif return; } /* Works for all the interrupt types... */ new_entry.type = EXP_TYPE_INT; new_entry.handler = asic_handle_exception; /* ASIC handling of all interrupts. In our case, the handler itself checks the exception code and matches it to the interrupt. */ new_entry.code = EXP_CODE_ALL; asic_table.inited = exception_add_handler(&new_entry, &old_handler); } <file_sep>/include/cfg+.h /* * libcfg+ - precise command line & config file parsing library * * cfg+.h - main implementation header file * ____________________________________________________________ * * Developed by <NAME> <<EMAIL>> * and <NAME> <<EMAIL>> * Copyright (c) 2001-2004 Platon SDG, http://platon.sk/ * All rights reserved. * * See README file for more information about this software. * See COPYING file for license information. * * Download the latest version from * http://platon.sk/projects/libcfg+/ */ /* $Platon: libcfg+/src/cfg+.h,v 1.60 2004/01/12 06:03:08 nepto Exp $ */ /** * @file cfg+.h * @brief main implementation header file * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @version \$Platon: libcfg+/src/cfg+.h,v 1.60 2004/01/12 06:03:08 nepto Exp $ * @date 2001-2004 */ #ifndef _PLATON_CFG_H #define _PLATON_CFG_H #include <stdio.h> /** End of options list marker */ #define CFG_END_OPTION { NULL, '\0', NULL, CFG_END, NULL, 0 } #define CFG_END_OF_LIST CFG_END_OPTION /**< Alias for @ref CFG_END_OPTION */ /** * @name Error codes */ /*@{*/ /** * Possible return values returned by parsing functions. */ enum cfg_error { /* {{{ */ /*@{*/ /** OK, all is right. */ CFG_ERR_OK = 0, CFG_ERROR_OK = 0, CFG_OK = 0, /*@}*/ /** An argument is missing for an option. */ CFG_ERR_NOARG = -1, CFG_ERROR_NOARG = -1, /** An argument is not allowed for an option. */ CFG_ERR_NOTALLOWEDARG = -2, CFG_ERROR_NOTALLOWEDARG = -2, /** An option's argument could not be parsed. */ CFG_ERR_BADOPT = -3, CFG_ERROR_BADOPT = -3, /** Error in quotations. */ CFG_ERR_BADQUOTE = -4, CFG_ERROR_BADQUOTE = -4, /** An option could not be converted to appropriate numeric type. */ CFG_ERR_BADNUMBER = -5, CFG_ERROR_BADNUMBER = -5, /** A given number was too big or too small. */ CFG_ERR_OVERFLOW = -6, CFG_ERROR_OVERFLOW = -6, /** Multiple arguments used for single option. */ CFG_ERR_MULTI = -7, CFG_ERROR_MULTI = -7, /** Not enough memory. */ CFG_ERR_NOMEM = -8, CFG_ERROR_NOMEM = -8, /** Stop string was found. */ CFG_ERR_STOP_STR = -9, CFG_ERR_STOP_STR_FOUND = -9, CFG_ERROR_STOP_STR = -9, CFG_ERROR_STOP_STR_FOUND = -9, /** No equal sign on the line. */ CFG_ERR_NOEQUAL = -10, CFG_ERROR_NOEQUAL = -10, /** An unknown option. */ CFG_ERR_UNKNOWN = -11, CFG_ERROR_UNKNOWN = -11, /** File not found error. */ CFG_ERR_FILE_NOT_FOUND = -12, CFG_ERROR_FILE_NOT_FOUND = -12, /** Seek error (fseek() failure). */ CFG_ERR_SEEK_ERROR = -13, CFG_ERROR_SEEK_ERROR = -13, /** Internal error. */ CFG_ERR_INTERNAL = -20, CFG_ERROR_INTERNAL = -20 }; /* }}} */ /*@}*/ /** * @name Context flags */ /*@{*/ /** * By default are @ref CFG_PROCESS_FIRST, @ref CFG_POSIXLY_LEFTOVERS and * @ref CFG_NORMAL_LEFTOVERS initialized. * @todo CFG_APPEND, CFG_OVERWRITE, CFG_APPEND_MULTI_ONLY */ enum cfg_flag { /* {{{ */ /** Ignore multiple arguments for single option. */ CFG_IGNORE_MULTI = 1, /** Ignore unknown options. */ CFG_IGNORE_UNKNOWN = 2, /** Process also the first argument on command line. */ CFG_PROCESS_FIRST = 0, /** Skip processing of the first argument on command line. */ CFG_SKIP_FIRST = 4, /** Posixly correct leftover arguments. */ CFG_POSIXLY_LEFTOVERS = 0, /** Advanced leftover arguments. */ CFG_ADVANCED_LEFTOVERS = 8, /** Normal leftover arguments initialization in file. This flag is not used and it is kept from historical reasons. */ CFG_NORMAL_LEFTOVERS = 0, /** Strict leftover arguments initialization in file. This flag is not used and it is kept from historical reasons. */ CFG_STRICT_LEFTOVERS = 16, /** Byte type position usage in file. */ CFG_FILE_BYTE_POS_USAGE = 0, /** Line type position usage in file. */ CFG_FILE_LINE_POS_USAGE = 32 /* Ignore all quotations in options arguments. */ /* CFG_USE_QUOTE = 0, CFG_IGNORE_QUOTE = 16 */ /* Advanced quotations are things like option = va"'l'"ue which resolves to va'l'ue. We really want this strange stuff? Any volunter? CFG_ADVANCED_QUOTE = 32 + 16 */ }; /* }}} */ /*@}*/ /** * @name Option types */ /*@{*/ /** * Possible types of options * @todo Thinking about case insensitivy of option * ("--input" is the same as "--INPUT") */ enum cfg_option_type { /* {{{ */ /** Boolean */ CFG_BOOL = 1, CFG_BOOLEAN = 1, /** Integer */ CFG_INT = 2, CFG_INTEGER = 2, /** Unsigned int */ CFG_UINT = 3, CFG_UNSIGNED = 3, CFG_UNSIGNED_INT = 3, /** Long */ CFG_LONG = 4, /** Unsigned long */ CFG_ULONG = 5, CFG_UNSIGNED_LONG = 5, /** Float */ CFG_FLOAT = 6, /** Double */ CFG_DOUBLE = 7, /** String */ CFG_STR = 8, CFG_STRING = 8, /** End (to mark last item in list) */ CFG_END = 0, /** Data type mask (used internally) */ CFG_DATA_TYPE_MASK = 31, /** * Single, multi or multi separated. Single by default. * Tells if option can be repeated. * In multi case value is array of poiters to type ended with NULL. */ CFG_SINGLE = 0, CFG_MULTI = 32, CFG_MULTI_ARRAY = 32, CFG_MULTI_SEPARATED = 32 + 64, /** * Leftover arguments specification. * Mark option which will contain leftover arguments. */ CFG_LAST_ARGS = 128, CFG_LAST_ARGUMENTS = 128, CFG_LEFTOVER_ARGS = 128, CFG_LEFTOVER_ARGUMENTS = 128 }; /* }}} */ /*@}*/ /** * @name Property types */ /*@{*/ enum cfg_property_type { /* {{{ */ /** * @name Property codes */ /*@{*/ /** Array of strings which forces to stop command line parsing. By default it is empty. */ CFG_LINE_STOP_STRING = 0, /** Command line short option prefix. By default is "-" initialized. */ CFG_LINE_SHORT_OPTION_PREFIX = 1, /** Command line long option prefix. By default is "--" initialized. */ CFG_LINE_LONG_OPTION_PREFIX = 2, /** Command line option argument separator. By default is "=" initialized. */ CFG_LINE_OPTION_ARG_SEPARATOR = 3, /** Command line multi values separator. By default are "," and ";" initialized. */ CFG_LINE_NORMAL_MULTI_VALS_SEPARATOR = 4, /** Command line multi values leftover arguments separator. By default it is empty. */ CFG_LINE_LEFTOVER_MULTI_VALS_SEPARATOR = 5, /** Command line quote prefix & postfix. By default are apostrophes (') and quotations (") initlized for both.*/ CFG_LINE_QUOTE_PREFIX = 6, CFG_LINE_QUOTE_POSTFIX = 7, /** Array of strings prefixes which forces to stop config file parsing. By default it is empty. */ CFG_FILE_STOP_PREFIX = 8, /** Array of string prefixes which mark comment line. By default are "#" and ";" initialized. */ CFG_FILE_COMMENT_PREFIX = 9, /** Array of string postfixes to determine multi lines. By default is "\\" initialized. */ CFG_FILE_MULTI_LINE_POSTFIX = 10, /** Config file option argument separator. By default is "=" initialized. */ CFG_FILE_OPTION_ARG_SEPARATOR = 11, /** Config file multi values separator. By default are ",", ";" and " " initialized. */ CFG_FILE_NORMAL_MULTI_VALS_SEPARATOR = 12, /** Command line multi values leftover arguments separator. By default is " " initialized. */ CFG_FILE_LEFTOVER_MULTI_VALS_SEPARATOR = 13, /** Config file quote prefix & postfix. By default are apostrophes (') and quotations (\") initlized for both.*/ CFG_FILE_QUOTE_PREFIX = 14, CFG_FILE_QUOTE_POSTFIX = 15, /*@}*/ /** * @name Count of normal properties */ /*@{*/ /** Special properties count */ CFG_N_PROPS = 16, /*@}*/ /** * @name Virtual property codes */ /*@{*/ /** File quote prefix & postfix */ CFG_QUOTE = 50, CFG_LINE_QUOTE = 51, CFG_FILE_QUOTE = 52, CFG_QUOTE_PREFIX = 53, CFG_QUOTE_POSTFIX = 54, /** Multi values separator */ CFG_MULTI_VALS_SEPARATOR = 55, CFG_FILE_MULTI_VALS_SEPARATOR = 56, CFG_LINE_MULTI_VALS_SEPARATOR = 57, CFG_NORMAL_MULTI_VALS_SEPARATOR = 58, CFG_LEFTOVER_MULTI_VALS_SEPARATOR = 59, /** Option argument separator */ CFG_OPTION_ARG_SEPARATOR = 60 /*@}*/ }; /* }}} */ /** * Terminators of variable number arguments in functions cfg_add_properties(), * cfg_set_properties(), cfg_get_properties() and similar. */ #define CFG_EOT CFG_N_PROPS #define CFG_END_TYPE CFG_N_PROPS /*@}*/ /** * @name Internal enumerations */ /*@{*/ /** * Context type * * Possible types of context (used internally) */ enum cfg_context_type { /* {{{ */ /** No context */ CFG_NO_CONTEXT = 0, /** Command line context type */ CFG_CMDLINE = 1, CFG_LINE = 1, /** Config file context type */ CFG_CFGFILE = 2, CFG_FILE = 2 }; /* }}} */ /** * Command line option type. * * Possible types of command line option (used internally) */ enum cfg_line_option_type { /* {{{ */ /** Not long and not short option */ CFG_NONE_OPTION = 0, /** Short command line option */ CFG_SHORT_OPTION = 1, /** Long command line option */ CFG_LONG_OPTION = 2, /** Short command line options */ CFG_SHORT_OPTIONS = 4, /** Long command line option argument initialized with separator */ CFG_LONG_SEPINIT = 8, /** Long command line option argument initialized without separator (default) */ CFG_LONG_NOSEPINIT = 0 }; /* }}} */ /*@}*/ /** * @brief Structure for defining one config option */ struct cfg_option { /* {{{ */ /** Command line long name (may be NULL) */ const char *cmdline_long_name; /** Command line short name (may be '\0') */ const char cmdline_short_name; /** Config file name (may be NULL) */ const char *cfgfile_name; /** Option type @see cfg_option_type */ const enum cfg_option_type type; /** Pointer where to store value of option */ void *value; /** Return value (set to 0 for not return) */ int val; }; /* }}} */ /** * @brief Main structure for defining context */ struct cfg_context { /* {{{ */ /** * @name Shared properties */ /*@{*/ /** Context type (command line or config file) */ enum cfg_context_type type; /** Flags */ int flags; /** Options table */ const struct cfg_option *options; /** Starting parsing position */ long begin_pos; /** Number of elements (array arguments, bytes or lines) to parse (value of -1 means infinite) */ long size; /** Array of used options indexes */ int *used_opt_idx; /** Error code of last occured error. */ enum cfg_error error_code; /** Special properties */ char **prop[CFG_N_PROPS]; /** Currents */ long cur_idx; long cur_idx_tmp; int cur_opt_type; /** Current option string */ char *cur_opt; /** Current option argument*/ char *cur_arg; /*@}*/ /** * @name Command line specific properties */ /*@{*/ /** Flag to detect if parsing already started */ int parsing_started:1; /** NULL terminated array of argument */ char **argv; /*@}*/ /** * @name Config file specific properties. */ /*@{*/ /** Filename (name of file) */ char *filename; /** Pointer to FILE* structure of parsed file */ FILE *fhandle; /*@}*/ }; /* }}} */ /** * @brief Context data type */ typedef struct cfg_context * CFG_CONTEXT; /* * Functions */ #ifdef __cplusplus extern "C" { #endif /** * @name Functions and macros for creating and manipulating context */ /*@{*/ /* {{{ */ /** * Initialize core context * * @param options pointer to options table * @return initialized core context; further specification * to command line or config file is required */ CFG_CONTEXT cfg_get_context(struct cfg_option *options); /** * Initialize command line context * * @param begin_pos index of beginning argument of arguments array * @param size maximal number of array elements to parse * (set value of -1 for infinite) * @param argv arguments array * @param options pointer to options table * @return initialized command line context */ CFG_CONTEXT cfg_get_cmdline_context( long begin_pos, long size, char **argv, struct cfg_option *options); #define cfg_get_cmdline_context_pos(begin_pos, end_pos, argv, options) \ cfg_get_cmdline_context( \ begin_pos, \ end_pos - begin_pos + 1, \ argv, \ options) /** * Initialize command line context by argc and argv passed to main() * * @param argc argumet count (argc) passed to function main() * @param argv arguments array (argv) passed to function main() * @param options pointer to options table * @return initialized command line context */ CFG_CONTEXT cfg_get_cmdline_context_argc( int argc, char **argv, struct cfg_option *options); /** * Initialize configuration file context * * @param begin_pos starting position in file to parse * @param size maximal number of bytes/lines in file to parse * (set value of -1 for infinite) * @param filename parsed filename * @param options pointer to options table * @return initialized command line context */ CFG_CONTEXT cfg_get_cfgfile_context( long begin_pos, long size, char *filename, struct cfg_option *options); #define cfg_get_cfgfile_context_pos(begin_pos, end_pos, argv, options) \ cfg_get_cfgfile_context( \ begin_pos, \ end_pos - begin_pos + 1, \ argv, \ options) /** * Set context to command line * * @param con initialized context * @param begin_pos index of beginning argument of arguments array * @param size maximal number of array elements to parse * (set value of -1 for infinite) * @param argv arguments array * @return void */ void cfg_set_cmdline_context( const CFG_CONTEXT con, long begin_pos, long size, char **argv); #define cfg_set_cmdline_context_pos(con, begin_pos, end_pos, argv) \ cfg_get_cmdline_context( \ con \ begin_pos, \ end_pos - begin_pos + 1, \ argv) /** * Set context to command line by argc and argv passed to main() * * @param con initialized context * @param argc argumet count (argc) passed to function main() * @param argv arguments array (argv) passed to function main() * @return initialized command line context */ void cfg_set_cmdline_context_argc( const CFG_CONTEXT con, int argc, char **argv); /** * Set context to configuration file * * @param con initialized context * @param begin_pos starting position in file to parse * @param size maximal number of bytes/lines in file to parse * (set value of -1 for infinite) * @param filename parsed filename * @return void */ void cfg_set_cfgfile_context( const CFG_CONTEXT con, long begin_pos, long size, char *filename); #define cfg_set_cfgfile_context_pos(con, begin_pos, end_pos, argv) \ cfg_get_cfgfile_context( \ con \ begin_pos, \ end_pos - begin_pos + 1, \ argv) /** * Reinitialize popt context * * @param con initialized context * @return void */ void cfg_reset_context(const CFG_CONTEXT con); /** * Destroy context * * @param con initialized context * @return void */ void cfg_free_context(const CFG_CONTEXT con); /* }}} */ /*@}*/ /** * @name Functions for setting and clearing context flags */ /*@{*/ /* {{{ */ /** * Set context flag * * @param con initialized context * @param flag context flag * @return void */ void cfg_set_context_flag(const CFG_CONTEXT con, int flag); /** * Clear context flag * * @param con initialized context * @param flag context flag * @return void */ void cfg_clear_context_flag(const CFG_CONTEXT con, int flag); /** * Get context flag * * @param con initialized context * @param flag context flag * @return 0 on false, non-zero on true */ int cfg_get_context_flag(const CFG_CONTEXT con, int flag); #define cfg_is_context_flag(con, flag) cfg_get_context_flag(con, flag) /** * Overwrite context flags * * @param con initialized context * @param flags context flags * @return void */ void cfg_set_context_flags(const CFG_CONTEXT con, int flags); /** * Get all context flags * * @param con initialized context * @return all context flags */ int cfg_get_context_flags(const CFG_CONTEXT con); /* }}} */ /*@}*/ /** * @name Functions and macros for properties manipulation */ /*@{*/ /* {{{ */ /** * Clear all strings of property * * @param con initialized context * @param type property type * @return 1 on success, 0 on not enough memory error * @see cfg_property_type */ int cfg_clear_property( const CFG_CONTEXT con, enum cfg_property_type type); /** * Clear all strings of property * * @param con initialized context * @param type property type * @return 1 on success, 0 on not enough memory error * @see cfg_property_type */ int cfg_clear_properties( const CFG_CONTEXT con, enum cfg_property_type type, ...); /** * Add string to property * * @param con initialized context * @param type property type * @param str string for addition * @return 1 on success, 0 on not enough memory error * @see cfg_property_type */ int cfg_add_property( const CFG_CONTEXT con, enum cfg_property_type type, char *str); /** * Add multiple strings to particular properties * * @param con initialized context * @param type property type(s) * @param str string(s) for addition * @return 1 on success, 0 on not enough memory error * @see cfg_property_type * * Argument list must be terminated with typeN = CFG_EOT or strN = NULL. * Use constructions like this:<br> * cfg_add_properties(con, type1, str1, type2, str2, type3=CFG_EOT) */ int cfg_add_properties( const CFG_CONTEXT con, enum cfg_property_type type, char *str, ...); /** * Add string to multiple properties * * @param con initialized context * @param str string for addition * @param type property type(s) * @return 1 on success, 0 on not enough memory error * @see cfg_property_type * * Argument list must be terminated with typeN = CFG_EOT. Use constructions * like this:<br> * cfg_add_properties(con, str, type1, type2, type3=CFG_EOT) */ int cfg_add_properties_str( const CFG_CONTEXT con, char *str, enum cfg_property_type type, ...); /** * Add multiple strings to one property * * @param con initialized context * @param type property type * @param str string(s) for addition * @return 1 on success, 0 on not enough memory error * @see cfg_property_type * * Argument list must be terminated with strN = NULL. Use constructions * like this:<br> * cfg_add_properties(con, type, str1, str2, str3=NULL) */ int cfg_add_properties_type( const CFG_CONTEXT con, enum cfg_property_type type, char *str, ...); /** * Remove string from property * * @param con initialized context * @param type property type * @param str string for removal * @return 1 on success, 0 on not enough memory error * @see cfg_property_type */ int cfg_remove_property( const CFG_CONTEXT con, enum cfg_property_type type, char *str); /** * Remove multiple strings from particular properties * * @param con initialized context * @param type property type(s) * @param str string(s) for removal * @return 1 on success, 0 on not enough memory error * @see cfg_property_type * * Argument list must be terminated with typeN = CFG_EOT or strN = NULL. * Use constructions like this:<br> * cfg_remove_properties(con, type1, str1, type2, str2, type3=CFG_EOT) */ int cfg_remove_properties( const CFG_CONTEXT con, enum cfg_property_type type, char *str, ...); /** * Remove string from multiple properties * * @param con initialized context * @param str string for removal * @param type property type(s) * @return 1 on success, 0 on not enough memory error * @see cfg_property_type * * Argument list must be terminated with typeN = CFG_EOT. Use constructions * like this:<br> * cfg_remove_properties(con, str, type1, type2, type3=CFG_EOT) */ int cfg_remove_properties_str( const CFG_CONTEXT con, char *str, enum cfg_property_type type, ...); /** * Remove multiple strings from one property * * @param con initialized context * @param type property type * @param str string(s) for removal * @return 1 on success, 0 on not enough memory error * @see cfg_property_type * * Argument list must be terminated with strN = NULL. Use constructions * like this:<br> * cfg_add_properties(con, type, str1, str2, str3=NULL) */ int cfg_remove_properties_type( const CFG_CONTEXT con, enum cfg_property_type type, char *str, ...); /* }}} */ /*@}*/ /** * @name Functions for processing context options */ /*@{*/ /* {{{ */ /** * Parse context * * @param con initialized context * @return code of error (CFG_ERROR_*) * or CFG_OK if parsing was sucessfull * @see cfg_error */ int cfg_parse(const CFG_CONTEXT con); /** * Parse next option(s) and return its value (if non-zero) or error code. * * @param con initialized context * @return next option val, code of error (CFG_ERROR_*) * or CFG_OK on end * @see cfg_error * @see cfg_context */ int cfg_get_next_opt(const CFG_CONTEXT con); /** * Return currently processed option name * * @param con initialized context * @return pointer to current option name */ char *cfg_get_cur_opt(const CFG_CONTEXT con); /** * Return currently processed option argument * * @param con initialized context * @return pointer to current option argument */ char *cfg_get_cur_arg(const CFG_CONTEXT con); /** * Return currently processed option index (argv index in command line * context, file byte position or line position in config file context) * * @param con initialized context @return index of current option */ int cfg_get_cur_idx(const CFG_CONTEXT con); /* }}} */ /*@}*/ /** * @name Error handling functions */ /*@{*/ /* {{{ */ /** * Print error string to stderr * * @param con initialized context * @return void */ void cfg_print_error(const CFG_CONTEXT con); /** * Print error string to stream * * @param con initialized context * @param fh stream opened for writting * @return void */ void cfg_fprint_error(const CFG_CONTEXT con, FILE *fh); /** * Get error string; error string is dynamically allocated, it needs to be * freed after use. * * @param con initialized context * @return dynamically allocated error string */ char *cfg_get_error_str(const CFG_CONTEXT con); /** * Get static error string * * @param errorcode code of libcfg error * @return static error string */ char *cfg_get_static_error_str(const int errorcode); /* }}} */ /*@}*/ #ifdef __cplusplus } #endif #endif /* _PLATON_CFG_H */ /* Modeline for ViM {{{ * vim:set ts=4: * vim600:fdm=marker fdl=0 fdc=0: * }}} */ <file_sep>/include/events.h /** * \file events.h * \brief DreamShell event system * \date 2007-2014 * \author SWAT www.dc-swat.ru */ #ifndef _DS_EVENTS_H #define _DS_EVENTS_H #include "video.h" #define EVENT_STATE_ACTIVE 0 #define EVENT_STATE_SLEEP 1 #define EVENT_ACTION_RENDER 0 #define EVENT_ACTION_UPDATE 1 #define EVENT_TYPE_INPUT 0 #define EVENT_TYPE_VIDEO 1 /** * Event_t, data, action */ typedef void Event_func(void *, void *, int); typedef struct Event { const char *name; uint32 id; Event_func *event; void *param; uint16 state; uint16 type; } Event_t; #ifdef SDL_Rect #define VideoEventUpdate_t SDL_Rect; #else typedef struct VideoEventUpdate { int16 x; int16 y; uint16 w; uint16 h; } VideoEventUpdate_t; #endif /** * Initialize and shutdown event system */ int InitEvents(); void ShutdownEvents(); /** * Add event to list * * return NULL on error */ Event_t *AddEvent(const char *name, uint16 type, Event_func *event, void *param); /** * Remove event from list */ int RemoveEvent(Event_t *e); /** * Setup event state */ int SetEventState(Event_t *e, uint16 state); /** * Events list utils */ Item_list_t *GetEventList(); Event_t *GetEventById(uint32 id); Event_t *GetEventByName(const char *name); /** * Processing input events in main thread */ void ProcessInputEvents(SDL_Event *event); /** * Processing video rendering events in video thread */ void ProcessVideoEventsRender(); /** * Manual processing for forcing screen update in another video events */ void ProcessVideoEventsUpdate(VideoEventUpdate_t *area); #endif <file_sep>/src/settings.c /**************************** * DreamShell ##version## * * settings.c * * DreamShell settings * * Created by SWAT * * http://www.dc-swat.ru * ***************************/ #include <ds.h> static const char vmu_file[] = "/vmu/a1/DS_CORE4.CFG"; static const char raw_file[] = "DS_CORE.CFG"; static Settings_t current_set; static int loaded = 0; const static unsigned short DS_pal[16]= { 0xF000,0xF655,0xF300,0xFECC,0xFCBB,0xF443,0xFA99,0xF222, 0xFA88,0xF500,0xF988,0xF100,0xF877,0xF844,0xF700,0xF500 }; const static unsigned char DS_data[32*32/2]= { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x22,0xB0,0x00,0x00,0x00,0x55,0x5B,0x00,0x00,0xB1,0x17,0x00,0x00,0x00,0x00,0x00, 0xB2,0x22,0x22,0xB0,0x05,0x38,0x63,0x10,0x05,0x3A,0xC4,0x50,0x00,0x00,0x00,0x00, 0x00,0x00,0xB2,0x29,0x25,0x40,0x07,0x37,0x04,0x10,0x00,0x00,0x00,0x00,0x00,0x00, 0x22,0x22,0x22,0x22,0xFD,0x4E,0x92,0x88,0x04,0xCB,0xBB,0xBB,0xB0,0x00,0x00,0x00, 0x00,0xBB,0xBB,0xBB,0xB5,0x42,0x9F,0x14,0x2D,0x34,0xC9,0x22,0x99,0x92,0x22,0x22, 0x00,0x00,0x00,0x00,0x05,0x40,0x00,0x14,0xBB,0x91,0x43,0x52,0x22,0x99,0x92,0x22, 0x00,0x00,0x00,0x00,0x05,0x40,0x00,0xC6,0x00,0x00,0xBA,0x42,0x22,0x22,0x22,0x22, 0x00,0x00,0x00,0x00,0x05,0x40,0x00,0x35,0x00,0x00,0x01,0x40,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x05,0x31,0x14,0xA0,0x06,0x15,0x13,0x50,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x0B,0x1C,0xC5,0x00,0x05,0xC6,0xA7,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }; Settings_t *GetSettings() { if(!loaded) { LoadSettings(); } if(!loaded) { ResetSettings(); } return &current_set; } void SetSettings(Settings_t *settings) { if(settings != (Settings_t *)&current_set) { memcpy(&current_set, settings, sizeof(current_set)); } loaded = 1; } void ResetSettings() { Settings_t *cur = &current_set; VideoSettings_t *vid = &current_set.video; memset(&current_set, 0, sizeof(current_set)); vid->bpp = 16; vid->tex_width = 1024; vid->tex_height = 512; vid->tex_filter = -1; vid->virt_width = 640; vid->virt_height = 480; strncpy(cur->app, "Main", 4); cur->app[4] = '\0'; strncpy(cur->startup, "/lua/startup.lua", 16); cur->startup[16] = '\0'; cur->version = GetVersion(); loaded = 1; } static int LoadSettingsVMU() { uint8 *data; vmu_pkg_t pkg; size_t size; file_t fd; int res; fd = fs_open(vmu_file, O_RDONLY); if(fd == FILEHND_INVALID) { return 0; } size = fs_total(fd); data = calloc(1, size); if(!data) { fs_close(fd); return 0; } memset(&pkg, 0, sizeof(pkg)); res = fs_read(fd, data, size); fs_close(fd); if (res <= 0) { free(data); return 0; } if(vmu_pkg_parse(data, &pkg) < 0) { free(data); return 0; } size = sizeof(current_set); memcpy(&current_set, pkg.data, pkg.data_len > size ? size : pkg.data_len); free(data); return 1; } static int LoadSettingsFile(const char *filename) { Settings_t sets; file_t fd; ssize_t res; fd = fs_open(filename, O_RDONLY); if(fd == FILEHND_INVALID) { return 0; } res = fs_read(fd, &sets, sizeof(Settings_t)); fs_close(fd); if (res <= 0) { return 0; } memcpy(&current_set, &sets, sizeof(Settings_t)); return 1; } int LoadSettings() { char fn[NAME_MAX]; loaded = LoadSettingsVMU(); if (!loaded) { snprintf(fn, NAME_MAX, "%s/%s", getenv("PATH"), raw_file); loaded = LoadSettingsFile(fn); } if(loaded && current_set.version != GetVersion()) { dbglog(DBG_DEBUG, "%s: Settings file version is different from current version\n", __func__); } return loaded; } static int SaveSettingsVMU() { uint8 *pkg_out; vmu_pkg_t pkg; int pkg_size; file_t fd; fd = fs_open(vmu_file, O_WRONLY | O_TRUNC); if(fd == FILEHND_INVALID) { dbglog(DBG_DEBUG, "%s: Can't open for write %s\n", __func__, vmu_file); return 0; } memset(&pkg, 0, sizeof(pkg)); strcpy(pkg.desc_short, "DreamShell Settings"); strcpy(pkg.desc_long, getenv("VERSION")); strcpy(pkg.app_id, "DreamShell"); pkg.icon_cnt = 1; pkg.icon_anim_speed = 0; memcpy(pkg.icon_pal, DS_pal, 32); pkg.icon_data = DS_data; pkg.eyecatch_type = VMUPKG_EC_16BIT; pkg.data_len = sizeof(current_set); pkg.data = (void *)&current_set; vmu_pkg_build(&pkg, &pkg_out, &pkg_size); if(!pkg_out || pkg_size <= 0) { dbglog(DBG_DEBUG, "%s: vmu_pkg_build failed\n", __func__); return 0; } fs_write(fd, pkg_out, pkg_size); fs_close(fd); free(pkg_out); return 1; } static int SaveSettingsFile(const char *filename) { file_t fd; ssize_t res; fd = fs_open(filename, O_WRONLY | O_TRUNC); if(fd == FILEHND_INVALID) { dbglog(DBG_DEBUG, "%s: Can't open for write %s\n", __func__, filename); return 0; } res = fs_write(fd, &current_set, sizeof(current_set)); fs_close(fd); return (res <= 0 ? 0 : 1); } int SaveSettings() { char fn[NAME_MAX]; if(current_set.version != GetVersion()) { current_set.version = GetVersion(); } snprintf(fn, NAME_MAX, "%s/%s", getenv("PATH"), raw_file); return SaveSettingsVMU() || SaveSettingsFile(fn); } <file_sep>/modules/mp3/libmp3/xingmp3/itype.h /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /*--------------------------------------------------------------- mpeg Layer II audio decoder, integer version variable type control -----------------------------------------------------------------*/ /*----------------------------------------------------------------- Variable types can have a large impact on performance. If the native type int is 32 bit or better, setting all variables to the native int is probably the best bet. Machines with fast floating point handware will probably run faster with the floating point version of this decoder. On 16 bit machines, use the native 16 bit int where possible with special consideration given to the multiplies used in the dct and window (see below). The code uses the type INT32 when 32 or more bits are required. Use the native int if possible. Signed types are required for all but DCTCOEF which may be unsigned. THe major parts of the decoder are: bit stream unpack (iup.c), dct (cidct.c), and window (iwinq.c). The compute time relationship is usually unpack < dct < window. -------------------------------------------------------------------*/ /*-------------- dct cidct.c ------------------------------------------- dct input is type SAMPLEINT, output is WININT DCTCOEF: dct coefs, 16 or more bits required DCTBITS: fractional bits in dct coefs. Coefs are unsigned in the range 0.50 to 10.2. DCTBITS=10 is a compromise between precision and the possibility of overflowing intermediate results. DCTSATURATE: If set, saturates dct output to 16 bit. Dct output may overflow if WININT is 16 bit, overflow is rare, but very noisy. Define to 1 for 16 bit WININT. Define to 0 otherwise. The multiply used in the dct (routine forward_bf in cidct.c) requires the multiplication of a 32 bit variable by a 16 bit unsigned coef to produce a signed 32 bit result. On 16 bit machines this could be faster than a full 32x32 multiply. ------------------------------------------------------------------*/ /*-------------- WINDOW iwinq.c --------------------------------------- window input is type WININT, output is short (16 bit pcm audio) window coefs WINBITS fractional bits, coefs are signed range in -1.15 to 0.96. WINBITS=14 is maximum for 16 bit signed representation. Some CPU's will multiply faster with fewer bits. WINBITS less that 8 may cause noticeable quality loss. WINMULT defines the multiply used in the window (iwinq.c) WINMULT must produce a 32 bit (or better) result, although both multipliers may be 16 bit. A 16x16-->32 multiply may offer a performance advantage if the compiler can be coerced into doing the right thing. ------------------------------------------------------------------*/ /*-- settings for MS C++ 4.0 flat 32 bit (long=int=32bit) --*/ /*-- asm replacement modules must use these settings ---*/ #ifndef ITYPES_H #define ITYPES_H #ifdef WIN32 #include <basetsd.h> #endif #ifndef WIN32 typedef long INT32; typedef unsigned long UINT32; #endif typedef int SAMPLEINT; typedef int DCTCOEF; #define DCTBITS 10 #define DCTSATURATE 0 typedef int WININT; typedef int WINCOEF; #define WINBITS 10 #define WINMULT(x,coef) ((x)*(coef)) #endif <file_sep>/modules/bflash/flash_if.h /** * \file flash_if.h * \brief Bios flash interface * \date 2009-2014 * \author SWAT * \copyright http://www.dc-swat.ru */ #ifndef __BIOS_FLASH_IF_H #define __BIOS_FLASH_IF_H #include <arch/types.h> #include "drivers/bflash.h" #define ADDR_MANUFACTURER 0x0000 #define ADDR_DEVICE_ID 0x0002 #define ADDR_SECTOR_LOCK 0x0004 #define ADDR_HANDSHAKE 0x0006 /* Byte mode */ #define ADDR_UNLOCK_1_BM 0x0AAA #define ADDR_UNLOCK_2_BM 0x0555 /* Word mode */ #define ADDR_UNLOCK_1_WM 0x0555 #define ADDR_UNLOCK_2_WM 0x02AA /* JEDEC */ /* words to put on A14-A0 without A-1 (Q15) ! -> The address need to be shifted. */ #define ADDR_UNLOCK_1_JEDEC (0x5555<<1) #define ADDR_UNLOCK_2_JEDEC (0x2AAA<<1) #define CMD_UNLOCK_DATA_1 0x00AA #define CMD_UNLOCK_DATA_2 0x0055 #define CMD_MANUFACTURER_UNLOCK_DATA 0x0090 #define CMD_UNLOCK_BYPASS_MODE 0x0020 #define CMD_PROGRAM_UNLOCK_DATA 0x00A0 #define CMD_SLEEP 0x00C0 #define CMD_ABORT 0x00E0 #define CMD_RESET_DATA 0x00F0 #define CMD_SECTOR_ERASE_UNLOCK_DATA 0x0080 #define CMD_SECTOR_ERASE_UNLOCK_DATA_2 0x0030 #define CMD_ERASE_ALL 0x0010 #define CMD_ERASE_SUSPEND 0x00B0 #define CMD_ERASE_RESUME 0x0030 #define CMD_UNLOCK_SECTOR 0x0060 #define CMD_CFI_QUERY 0x0062 #define D6_MASK 0x40 /* Ready bit */ #define D7_MASK 0x80 /* Data polling bit */ #define SEGA_FLASH_DEVICE_ID 0xFF28 /* The "SEGA ID" is just the data read back from the ROM at the address 0 and 2... */ #endif /* __BIOS_FLASH_IF_H */ <file_sep>/lib/SDL_gui/ToggleButton.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_ToggleButton::GUI_ToggleButton(const char *aname, int x, int y, int w, int h) : GUI_AbstractButton(aname, x, y, w, h) { SDL_Rect in; in.x = 4; in.y = 4; in.w = area.w-8; in.h = area.h-8; on_normal = new GUI_Surface("on0", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); on_highlight = new GUI_Surface("on1", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); off_normal = new GUI_Surface("off0", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); off_highlight = new GUI_Surface("off1", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); off_normal->Fill(NULL, 0xFF000000); off_normal->Fill(&in, 0x007F0000); off_highlight->Fill(NULL, 0x00FFFFFF); off_highlight->Fill(&in, 0x007F0000); on_normal->Fill(NULL, 0xFF000000); on_normal->Fill(&in, 0x00007F00); on_highlight->Fill(NULL, 0x00FFFFFF); on_highlight->Fill(&in, 0x00007F00); } GUI_ToggleButton::~GUI_ToggleButton() { off_normal->DecRef(); off_highlight->DecRef(); on_normal->DecRef(); on_highlight->DecRef(); } void GUI_ToggleButton::Clicked(int x, int y) { flags ^= WIDGET_TURNED_ON; MarkChanged(); GUI_AbstractButton::Clicked(x,y); } void GUI_ToggleButton::Highlighted(int x, int y) { GUI_AbstractButton::Highlighted(x,y); } void GUI_ToggleButton::unHighlighted(int x, int y) { GUI_AbstractButton::unHighlighted(x,y); } GUI_Surface *GUI_ToggleButton::GetCurrentImage() { if (flags & WIDGET_INSIDE) { if (flags & WIDGET_TURNED_ON) return on_highlight; return off_highlight; } if (flags & WIDGET_TURNED_ON) return on_normal; return off_normal; } void GUI_ToggleButton::SetOnNormalImage(GUI_Surface *surface) { if (GUI_ObjectKeep((GUI_Object **) &on_normal, surface)) MarkChanged(); } void GUI_ToggleButton::SetOffNormalImage(GUI_Surface *surface) { if (GUI_ObjectKeep((GUI_Object **) &off_normal, surface)) MarkChanged(); } void GUI_ToggleButton::SetOnHighlightImage(GUI_Surface *surface) { if (GUI_ObjectKeep((GUI_Object **) &on_highlight, surface)) MarkChanged(); } void GUI_ToggleButton::SetOffHighlightImage(GUI_Surface *surface) { if (GUI_ObjectKeep((GUI_Object **) &off_highlight, surface)) MarkChanged(); } extern "C" { GUI_Widget *GUI_ToggleButtonCreate(const char *name, int x, int y, int w, int h) { return new GUI_ToggleButton(name, x, y, w, h); } int GUI_ToggleButtonCheck(GUI_Widget *widget) { // FIXME not implemented return 0; } void GUI_ToggleButtonSetOnNormalImage(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_ToggleButton *) widget)->SetOnNormalImage(surface); } void GUI_ToggleButtonSetOnHighlightImage(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_ToggleButton *) widget)->SetOnHighlightImage(surface); } void GUI_ToggleButtonSetOffNormalImage(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_ToggleButton *) widget)->SetOffNormalImage(surface); } void GUI_ToggleButtonSetOffHighlightImage(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_ToggleButton *) widget)->SetOffHighlightImage(surface); } void GUI_ToggleButtonSetCaption(GUI_Widget *widget, GUI_Widget *caption) { ((GUI_ToggleButton *) widget)->SetCaption(caption); } GUI_Widget *GUI_ToggleButtonGetCaption(GUI_Widget *widget) { return ((GUI_ToggleButton *) widget)->GetCaption(); } void GUI_ToggleButtonSetClick(GUI_Widget *widget, GUI_Callback *callback) { ((GUI_ToggleButton *) widget)->SetClick(callback); } void GUI_ToggleButtonSetContextClick(GUI_Widget *widget, GUI_Callback *callback) { ((GUI_ToggleButton *) widget)->SetContextClick(callback); } void GUI_ToggleButtonSetMouseover(GUI_Widget *widget, GUI_Callback *callback) { ((GUI_ToggleButton *) widget)->SetMouseover(callback); } void GUI_ToggleButtonSetMouseout(GUI_Widget *widget, GUI_Callback *callback) { ((GUI_ToggleButton *) widget)->SetMouseout(callback); } } <file_sep>/lib/SDL_image/IMG_ImageIO.c /* * IMG_ImageIO.c * SDL_image * * Created by <NAME> on 1/1/09. * Copyright 2009 __MyCompanyName__. All rights reserved. * */ #if defined(__APPLE__) && !defined(SDL_IMAGE_USE_COMMON_BACKEND) #include "SDL_image.h" // Used because CGDataProviderCreate became deprecated in 10.5 #include <AvailabilityMacros.h> #include <TargetConditionals.h> #include <Foundation/Foundation.h> #if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1) #ifdef ALLOW_UIIMAGE_FALLBACK #define USE_UIIMAGE_BACKEND() ([UIImage instancesRespondToSelector:@selector(initWithCGImage:scale:orientation:)] == NO) #else #define USE_UIIMAGE_BACKEND() (Internal_checkImageIOisAvailable()) #endif #import <MobileCoreServices/MobileCoreServices.h> // for UTCoreTypes.h #import <ImageIO/ImageIO.h> #import <UIKit/UIImage.h> #else // For ImageIO framework and also LaunchServices framework (for UTIs) #include <ApplicationServices/ApplicationServices.h> #endif /************************************************************** ***** Begin Callback functions for block reading ************* **************************************************************/ // This callback reads some bytes from an SDL_rwops and copies it // to a Quartz buffer (supplied by Apple framework). static size_t MyProviderGetBytesCallback(void* rwops_userdata, void* quartz_buffer, size_t the_count) { return (size_t)SDL_RWread((struct SDL_RWops *)rwops_userdata, quartz_buffer, 1, the_count); } // This callback is triggered when the data provider is released // so you can clean up any resources. static void MyProviderReleaseInfoCallback(void* rwops_userdata) { // What should I put here? // I think the user and SDL_RWops controls closing, so I don't do anything. } static void MyProviderRewindCallback(void* rwops_userdata) { SDL_RWseek((struct SDL_RWops *)rwops_userdata, 0, RW_SEEK_SET); } #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 // CGDataProviderCreateSequential was introduced in 10.5; CGDataProviderCreate is deprecated off_t MyProviderSkipForwardBytesCallback(void* rwops_userdata, off_t the_count) { off_t start_position = SDL_RWtell((struct SDL_RWops *)rwops_userdata); SDL_RWseek((struct SDL_RWops *)rwops_userdata, the_count, RW_SEEK_CUR); off_t end_position = SDL_RWtell((struct SDL_RWops *)rwops_userdata); return (end_position - start_position); } #else // CGDataProviderCreate was deprecated in 10.5 static void MyProviderSkipBytesCallback(void* rwops_userdata, size_t the_count) { SDL_RWseek((struct SDL_RWops *)rwops_userdata, the_count, RW_SEEK_CUR); } #endif /************************************************************** ***** End Callback functions for block reading *************** **************************************************************/ // This creates a CGImageSourceRef which is a handle to an image that can be used to examine information // about the image or load the actual image data. static CGImageSourceRef CreateCGImageSourceFromRWops(SDL_RWops* rw_ops, CFDictionaryRef hints_and_options) { CGImageSourceRef source_ref; // Similar to SDL_RWops, Apple has their own callbacks for dealing with data streams. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 // CGDataProviderCreateSequential was introduced in 10.5; CGDataProviderCreate is deprecated CGDataProviderSequentialCallbacks provider_callbacks = { 0, MyProviderGetBytesCallback, MyProviderSkipForwardBytesCallback, MyProviderRewindCallback, MyProviderReleaseInfoCallback }; CGDataProviderRef data_provider = CGDataProviderCreateSequential(rw_ops, &provider_callbacks); #else // CGDataProviderCreate was deprecated in 10.5 CGDataProviderCallbacks provider_callbacks = { MyProviderGetBytesCallback, MyProviderSkipBytesCallback, MyProviderRewindCallback, MyProviderReleaseInfoCallback }; CGDataProviderRef data_provider = CGDataProviderCreate(rw_ops, &provider_callbacks); #endif // Get the CGImageSourceRef. // The dictionary can be NULL or contain hints to help ImageIO figure out the image type. source_ref = CGImageSourceCreateWithDataProvider(data_provider, hints_and_options); CGDataProviderRelease(data_provider); return source_ref; } /* Create a CGImageSourceRef from a file. */ /* Remember to CFRelease the created source when done. */ static CGImageSourceRef CreateCGImageSourceFromFile(const char* the_path) { CFURLRef the_url = NULL; CGImageSourceRef source_ref = NULL; CFStringRef cf_string = NULL; /* Create a CFString from a C string */ cf_string = CFStringCreateWithCString(NULL, the_path, kCFStringEncodingUTF8); if (!cf_string) { return NULL; } /* Create a CFURL from a CFString */ the_url = CFURLCreateWithFileSystemPath(NULL, cf_string, kCFURLPOSIXPathStyle, false); /* Don't need the CFString any more (error or not) */ CFRelease(cf_string); if(!the_url) { return NULL; } source_ref = CGImageSourceCreateWithURL(the_url, NULL); /* Don't need the URL any more (error or not) */ CFRelease(the_url); return source_ref; } static CGImageRef CreateCGImageFromCGImageSource(CGImageSourceRef image_source) { CGImageRef image_ref = NULL; if(NULL == image_source) { return NULL; } // Get the first item in the image source (some image formats may // contain multiple items). image_ref = CGImageSourceCreateImageAtIndex(image_source, 0, NULL); if(NULL == image_ref) { IMG_SetError("CGImageSourceCreateImageAtIndex() failed"); } return image_ref; } static CFDictionaryRef CreateHintDictionary(CFStringRef uti_string_hint) { CFDictionaryRef hint_dictionary = NULL; if(uti_string_hint != NULL) { // Do a bunch of work to setup a CFDictionary containing the jpeg compression properties. CFStringRef the_keys[1]; CFStringRef the_values[1]; the_keys[0] = kCGImageSourceTypeIdentifierHint; the_values[0] = uti_string_hint; // kCFTypeDictionaryKeyCallBacks or kCFCopyStringDictionaryKeyCallBacks? hint_dictionary = CFDictionaryCreate(NULL, (const void**)&the_keys, (const void**)&the_values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } return hint_dictionary; } // Once we have our image, we need to get it into an SDL_Surface static SDL_Surface* Create_SDL_Surface_From_CGImage_RGB(CGImageRef image_ref) { /* This code is adapted from Apple's Documentation found here: * http://developer.apple.com/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/index.html * Listing 9-4††Using a Quartz image as a texture source. * Unfortunately, this guide doesn't show what to do about * non-RGBA image formats so I'm making the rest up. * All this code should be scrutinized. */ size_t w = CGImageGetWidth(image_ref); size_t h = CGImageGetHeight(image_ref); CGRect rect = {{0, 0}, {w, h}}; CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image_ref); //size_t bits_per_pixel = CGImageGetBitsPerPixel(image_ref); size_t bits_per_component = 8; SDL_Surface* surface; Uint32 Amask; Uint32 Rmask; Uint32 Gmask; Uint32 Bmask; CGContextRef bitmap_context; CGBitmapInfo bitmap_info; /* This sets up a color space that results in identical values * as the image data itself, which is the same as the standalone * libpng loader. * Thanks to Allegro. :) */ CGFloat whitePoint[3] = { 1, 1, 1 }; CGFloat blackPoint[3] = { 0, 0, 0 }; CGFloat gamma[3] = { 2.2, 2.2, 2.2 }; CGFloat matrix[9] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 }; CGColorSpaceRef color_space = CGColorSpaceCreateCalibratedRGB( whitePoint, blackPoint, gamma, matrix ); if (alpha == kCGImageAlphaNone || alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast) { bitmap_info = kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host; /* XRGB */ Amask = 0x00000000; } else { /* kCGImageAlphaFirst isn't supported */ //bitmap_info = kCGImageAlphaFirst | kCGBitmapByteOrder32Host; /* ARGB */ bitmap_info = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host; /* ARGB */ Amask = 0xFF000000; } Rmask = 0x00FF0000; Gmask = 0x0000FF00; Bmask = 0x000000FF; surface = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32, Rmask, Gmask, Bmask, Amask); if (surface) { // Sets up a context to be drawn to with surface->pixels as the area to be drawn to bitmap_context = CGBitmapContextCreate( surface->pixels, surface->w, surface->h, bits_per_component, surface->pitch, color_space, bitmap_info ); // Draws the image into the context's image_data CGContextDrawImage(bitmap_context, rect, image_ref); CGContextRelease(bitmap_context); // FIXME: Reverse the premultiplied alpha if ((bitmap_info & kCGBitmapAlphaInfoMask) == kCGImageAlphaPremultipliedFirst) { int i, j; Uint8 *p = (Uint8 *)surface->pixels; for (i = surface->h * surface->pitch/4; i--; ) { #if __LITTLE_ENDIAN__ Uint8 A = p[3]; if (A) { for (j = 0; j < 3; ++j) { p[j] = (p[j] * 255) / A; } } #else Uint8 A = p[0]; if (A) { for (j = 1; j < 4; ++j) { p[j] = (p[j] * 255) / A; } } #endif /* ENDIAN */ p += 4; } } } if (color_space) { CGColorSpaceRelease(color_space); } return surface; } static SDL_Surface* Create_SDL_Surface_From_CGImage_Index(CGImageRef image_ref) { size_t w = CGImageGetWidth(image_ref); size_t h = CGImageGetHeight(image_ref); size_t bits_per_pixel = CGImageGetBitsPerPixel(image_ref); size_t bytes_per_row = CGImageGetBytesPerRow(image_ref); SDL_Surface* surface; SDL_Palette* palette; CGColorSpaceRef color_space = CGImageGetColorSpace(image_ref); CGColorSpaceRef base_color_space = CGColorSpaceGetBaseColorSpace(color_space); size_t num_components = CGColorSpaceGetNumberOfComponents(base_color_space); size_t num_entries = CGColorSpaceGetColorTableCount(color_space); uint8_t *entry, entries[num_components * num_entries]; /* What do we do if it's not RGB? */ if (num_components != 3) { SDL_SetError("Unknown colorspace components %lu", num_components); return NULL; } if (bits_per_pixel != 8) { SDL_SetError("Unknown bits_per_pixel %lu", bits_per_pixel); return NULL; } CGColorSpaceGetColorTable(color_space, entries); surface = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, bits_per_pixel, 0, 0, 0, 0); if (surface) { uint8_t* pixels = (uint8_t*)surface->pixels; CGDataProviderRef provider = CGImageGetDataProvider(image_ref); NSData* data = (id)CGDataProviderCopyData(provider); [data autorelease]; const uint8_t* bytes = [data bytes]; size_t i; palette = surface->format->palette; for (i = 0, entry = entries; i < num_entries; ++i) { palette->colors[i].r = entry[0]; palette->colors[i].g = entry[1]; palette->colors[i].b = entry[2]; entry += num_components; } for (i = 0; i < h; ++i) { SDL_memcpy(pixels, bytes, w); pixels += surface->pitch; bytes += bytes_per_row; } } return surface; } static SDL_Surface* Create_SDL_Surface_From_CGImage(CGImageRef image_ref) { CGColorSpaceRef color_space = CGImageGetColorSpace(image_ref); if (CGColorSpaceGetModel(color_space) == kCGColorSpaceModelIndexed) { return Create_SDL_Surface_From_CGImage_Index(image_ref); } else { return Create_SDL_Surface_From_CGImage_RGB(image_ref); } } #pragma mark - #pragma mark IMG_Init stubs #if !defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) static int Internal_checkImageIOisAvailable() { // just check if we are running on ios 4 or more, else throw exception if ([UIImage instancesRespondToSelector:@selector(initWithCGImage:scale:orientation:)]) return 0; [NSException raise:@"UIImage fallback not enabled at compile time" format:@"ImageIO is not available on your platform, please recompile SDL_Image with ALLOW_UIIMAGE_FALLBACK."]; return -1; } #endif int IMG_InitJPG() { return 0; } void IMG_QuitJPG() { } int IMG_InitPNG() { return 0; } void IMG_QuitPNG() { } int IMG_InitTIF() { return 0; } void IMG_QuitTIF() { } #pragma mark - #pragma mark Get type of image static int Internal_isType_UIImage (SDL_RWops *rw_ops, CFStringRef uti_string_to_test) { int is_type = 0; #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) int start = SDL_RWtell(rw_ops); if ((0 == CFStringCompare(uti_string_to_test, kUTTypeICO, 0)) || (0 == CFStringCompare(uti_string_to_test, CFSTR("com.microsoft.cur"), 0))) { // The Win32 ICO file header (14 bytes) Uint16 bfReserved; Uint16 bfType; Uint16 bfCount; int type = (0 == CFStringCompare(uti_string_to_test, kUTTypeICO, 0)) ? 1 : 2; bfReserved = SDL_ReadLE16(rw_ops); bfType = SDL_ReadLE16(rw_ops); bfCount = SDL_ReadLE16(rw_ops); if ((bfReserved == 0) && (bfType == type) && (bfCount != 0)) is_type = 1; } else if (0 == CFStringCompare(uti_string_to_test, kUTTypeBMP, 0)) { char magic[2]; if ( SDL_RWread(rw_ops, magic, sizeof(magic), 1) ) { if ( strncmp(magic, "BM", 2) == 0 ) { is_type = 1; } } } else if (0 == CFStringCompare(uti_string_to_test, kUTTypeGIF, 0)) { char magic[6]; if ( SDL_RWread(rw_ops, magic, sizeof(magic), 1) ) { if ( (strncmp(magic, "GIF", 3) == 0) && ((memcmp(magic + 3, "87a", 3) == 0) || (memcmp(magic + 3, "89a", 3) == 0)) ) { is_type = 1; } } } else if (0 == CFStringCompare(uti_string_to_test, kUTTypeJPEG, 0)) { int in_scan = 0; Uint8 magic[4]; // This detection code is by <NAME> <<EMAIL>> // Blame me, not Sam, if this doesn't work right. */ // And don't forget to report the problem to the the sdl list too! */ if ( SDL_RWread(rw_ops, magic, 2, 1) ) { if ( (magic[0] == 0xFF) && (magic[1] == 0xD8) ) { is_type = 1; while (is_type == 1) { if(SDL_RWread(rw_ops, magic, 1, 2) != 2) { is_type = 0; } else if( (magic[0] != 0xFF) && (in_scan == 0) ) { is_type = 0; } else if( (magic[0] != 0xFF) || (magic[1] == 0xFF) ) { /* Extra padding in JPEG (legal) */ /* or this is data and we are scanning */ SDL_RWseek(rw_ops, -1, SEEK_CUR); } else if(magic[1] == 0xD9) { /* Got to end of good JPEG */ break; } else if( (in_scan == 1) && (magic[1] == 0x00) ) { /* This is an encoded 0xFF within the data */ } else if( (magic[1] >= 0xD0) && (magic[1] < 0xD9) ) { /* These have nothing else */ } else if(SDL_RWread(rw_ops, magic+2, 1, 2) != 2) { is_type = 0; } else { /* Yes, it's big-endian */ Uint32 start; Uint32 size; Uint32 end; start = SDL_RWtell(rw_ops); size = (magic[2] << 8) + magic[3]; end = SDL_RWseek(rw_ops, size-2, SEEK_CUR); if ( end != start + size - 2 ) is_type = 0; if ( magic[1] == 0xDA ) { /* Now comes the actual JPEG meat */ #ifdef FAST_IS_JPEG /* Ok, I'm convinced. It is a JPEG. */ break; #else /* I'm not convinced. Prove it! */ in_scan = 1; #endif } } } } } } else if (0 == CFStringCompare(uti_string_to_test, kUTTypePNG, 0)) { Uint8 magic[4]; if ( SDL_RWread(rw_ops, magic, 1, sizeof(magic)) == sizeof(magic) ) { if ( magic[0] == 0x89 && magic[1] == 'P' && magic[2] == 'N' && magic[3] == 'G' ) { is_type = 1; } } } else if (0 == CFStringCompare(uti_string_to_test, CFSTR("com.truevision.tga-image"), 0)) { //TODO: fill me! } else if (0 == CFStringCompare(uti_string_to_test, kUTTypeTIFF, 0)) { Uint8 magic[4]; if ( SDL_RWread(rw_ops, magic, 1, sizeof(magic)) == sizeof(magic) ) { if ( (magic[0] == 'I' && magic[1] == 'I' && magic[2] == 0x2a && magic[3] == 0x00) || (magic[0] == 'M' && magic[1] == 'M' && magic[2] == 0x00 && magic[3] == 0x2a) ) { is_type = 1; } } } else if (0 == CFStringCompare(uti_string_to_test, kUTTypePVR, 0)) { Uint8 magic[4]; if ( SDL_RWread(rw_ops, magic, 1, sizeof(magic)) == sizeof(magic) ) { if ( (magic[0] == 'P' && magic[1] == 'V' && magic[2] == 'R' && magic[3] == 'T') || (magic[0] == 'G' && magic[1] == 'B' && magic[2] == 'I' && magic[3] == 'X') ) { is_type = 1; } } // reset the file descption pointer SDL_RWseek(rw_ops, start, SEEK_SET); #endif /* #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) */ return is_type; } static int Internal_isType_ImageIO (SDL_RWops *rw_ops, CFStringRef uti_string_to_test) { int is_type = 0; CFDictionaryRef hint_dictionary = CreateHintDictionary(uti_string_to_test); CGImageSourceRef image_source = CreateCGImageSourceFromRWops(rw_ops, hint_dictionary); if (hint_dictionary != NULL) { CFRelease(hint_dictionary); } if (NULL == image_source) { return 0; } // This will get the UTI of the container, not the image itself. // Under most cases, this won't be a problem. // But if a person passes an icon file which contains a bmp, // the format will be of the icon file. // But I think the main SDL_image codebase has this same problem so I'm not going to worry about it. CFStringRef uti_type = CGImageSourceGetType(image_source); // CFShow(uti_type); // Unsure if we really want conformance or equality is_type = (int)UTTypeConformsTo(uti_string_to_test, uti_type); CFRelease(image_source); return is_type; } static int Internal_isType (SDL_RWops *rw_ops, CFStringRef uti_string_to_test) { if (rw_ops == NULL) return 0; #if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1) if (USE_UIIMAGE_BACKEND()) return Internal_isType_UIImage(rw_ops, uti_string_to_test); else #endif return Internal_isType_ImageIO(rw_ops, uti_string_to_test); } int IMG_isCUR(SDL_RWops *src) { /* FIXME: Is this a supported type? */ return Internal_isType(src, CFSTR("com.microsoft.cur")); } int IMG_isICO(SDL_RWops *src) { return Internal_isType(src, kUTTypeICO); } int IMG_isBMP(SDL_RWops *src) { return Internal_isType(src, kUTTypeBMP); } int IMG_isGIF(SDL_RWops *src) { return Internal_isType(src, kUTTypeGIF); } // Note: JPEG 2000 is kUTTypeJPEG2000 int IMG_isJPG(SDL_RWops *src) { return Internal_isType(src, kUTTypeJPEG); } int IMG_isPNG(SDL_RWops *src) { return Internal_isType(src, kUTTypePNG); } // This isn't a public API function. Apple seems to be able to identify tga's. int IMG_isTGA(SDL_RWops *src) { return Internal_isType(src, CFSTR("com.truevision.tga-image")); } int IMG_isTIF(SDL_RWops *src) { return Internal_isType(src, kUTTypeTIFF); } int IMG_isPVR(SDL_RWops *src) { return Internal_isType(src, kUTTypePVR); } #pragma mark - #pragma mark Load image engine static SDL_Surface *LoadImageFromRWops_UIImage (SDL_RWops* rw_ops, CFStringRef uti_string_hint) { SDL_Surface *sdl_surface = NULL; #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) NSAutoreleasePool* autorelease_pool = [[NSAutoreleasePool alloc] init]; UIImage *ui_image; int bytes_read = 0; // I don't know what a good size is. // Max recommended texture size is 1024x1024 on iPhone so maybe base it on that? const int block_size = 1024*4; char temp_buffer[block_size]; NSMutableData* ns_data = [[NSMutableData alloc] initWithCapacity:1024*1024*4]; do { bytes_read = SDL_RWread(rw_ops, temp_buffer, 1, block_size); [ns_data appendBytes:temp_buffer length:bytes_read]; } while (bytes_read > 0); ui_image = [[UIImage alloc] initWithData:ns_data]; if (ui_image != nil) sdl_surface = Create_SDL_Surface_From_CGImage([ui_image CGImage]); [ui_image release]; [ns_data release]; [autorelease_pool drain]; #endif /* #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) */ return sdl_surface; } static SDL_Surface *LoadImageFromRWops_ImageIO (SDL_RWops *rw_ops, CFStringRef uti_string_hint) { CFDictionaryRef hint_dictionary = CreateHintDictionary(uti_string_hint); CGImageSourceRef image_source = CreateCGImageSourceFromRWops(rw_ops, hint_dictionary); if (hint_dictionary != NULL) CFRelease(hint_dictionary); if (NULL == image_source) return NULL; CGImageRef image_ref = CreateCGImageFromCGImageSource(image_source); CFRelease(image_source); if (NULL == image_ref) return NULL; SDL_Surface *sdl_surface = Create_SDL_Surface_From_CGImage(image_ref); CFRelease(image_ref); return sdl_surface; } static SDL_Surface *LoadImageFromRWops (SDL_RWops *rw_ops, CFStringRef uti_string_hint) { #if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1) if (USE_UIIMAGE_BACKEND()) return LoadImageFromRWops_UIImage(rw_ops, uti_string_hint); else #endif return LoadImageFromRWops_ImageIO(rw_ops, uti_string_hint); } static SDL_Surface* LoadImageFromFile_UIImage (const char *file) { SDL_Surface *sdl_surface = NULL; #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) NSAutoreleasePool* autorelease_pool = [[NSAutoreleasePool alloc] init]; NSString *ns_string = [[NSString alloc] initWithUTF8String:file]; UIImage *ui_image = [[UIImage alloc] initWithContentsOfFile:ns_string]; if (ui_image != nil) sdl_surface = Create_SDL_Surface_From_CGImage([ui_image CGImage]); [ui_image release]; [ns_string release]; [autorelease_pool drain]; #endif /* #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) */ return sdl_surface; } static SDL_Surface* LoadImageFromFile_ImageIO (const char *file) { CGImageSourceRef image_source = NULL; image_source = CreateCGImageSourceFromFile(file); if(NULL == image_source) return NULL; CGImageRef image_ref = CreateCGImageFromCGImageSource(image_source); CFRelease(image_source); if (NULL == image_ref) return NULL; SDL_Surface *sdl_surface = Create_SDL_Surface_From_CGImage(image_ref); CFRelease(image_ref); return sdl_surface; } static SDL_Surface* LoadImageFromFile (const char *file) { #if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1) if (USE_UIIMAGE_BACKEND()) return LoadImageFromFile_UIImage(file); else #endif return LoadImageFromFile_ImageIO(file); } SDL_Surface* IMG_LoadCUR_RW (SDL_RWops *src) { /* FIXME: Is this a supported type? */ return LoadImageFromRWops(src, CFSTR("com.microsoft.cur")); } SDL_Surface* IMG_LoadICO_RW (SDL_RWops *src) { return LoadImageFromRWops(src, kUTTypeICO); } SDL_Surface* IMG_LoadBMP_RW (SDL_RWops *src) { return LoadImageFromRWops(src, kUTTypeBMP); } SDL_Surface* IMG_LoadGIF_RW (SDL_RWops *src) { return LoadImageFromRWops (src, kUTTypeGIF); } SDL_Surface* IMG_LoadJPG_RW (SDL_RWops *src) { return LoadImageFromRWops (src, kUTTypeJPEG); } SDL_Surface* IMG_LoadPNG_RW (SDL_RWops *src) { return LoadImageFromRWops (src, kUTTypePNG); } SDL_Surface* IMG_LoadTGA_RW (SDL_RWops *src) { return LoadImageFromRWops(src, CFSTR("com.truevision.tga-image")); } SDL_Surface* IMG_LoadTIF_RW (SDL_RWops *src) { return LoadImageFromRWops(src, kUTTypeTIFF); } SDL_Surface* IMG_LoadPVR_RW (SDL_RWops *src) { return LoadImageFromRWops(src, kUTTypePVR); } // Since UIImage doesn't really support streams well, we should optimize for the file case. // Apple provides both stream and file loading functions in ImageIO. // Potentially, Apple can optimize for either case. SDL_Surface* IMG_Load (const char *file) { SDL_Surface* sdl_surface = NULL; sdl_surface = LoadImageFromFile(file); if(NULL == sdl_surface) { // Either the file doesn't exist or ImageIO doesn't understand the format. // For the latter case, fallback to the native SDL_image handlers. SDL_RWops *src = SDL_RWFromFile(file, "rb"); char *ext = strrchr(file, '.'); if (ext) { ext++; } if (!src) { /* The error message has been set in SDL_RWFromFile */ return NULL; } sdl_surface = IMG_LoadTyped_RW(src, 1, ext); } return sdl_surface; } #endif /* defined(__APPLE__) && !defined(SDL_IMAGE_USE_COMMON_BACKEND) */ <file_sep>/firmware/isoldr/loader/include/malloc.h /** * DreamShell ISO Loader * Memory allocation * (c)2022-2023 SWAT <http://www.dc-swat.ru> */ #ifndef __MALLOC_H #define __MALLOC_H #include <sys/cdefs.h> __BEGIN_DECLS #include <arch/types.h> int malloc_init(int first); void malloc_stat(uint32 *free_size, uint32 *max_free_size); uint32 malloc_heap_pos(); void *malloc(uint32 size); void free(void *data); void *realloc(void *data, uint32 size); __END_DECLS #endif /*__MALLOC_H */ <file_sep>/modules/mp3/libmp3/xingmp3/Makefile OBJS = cdct.o csbt.o cup.o cupl3.o OBJS += cwinm.o dec8.o hwin.o icdct.o isbt.o OBJS += iup.o iwinm.o l3dq.o l3init.o OBJS += mdct.o mhead.o msis.o uph.o upsf.o INCS += -I. -DLITTLE_ENDIAN=1 CFLAGS += -O2 all: libxingmp3.a libxingmp3.a: $(OBJS) $(KOS_AR) rcs libxingmp3.a $(OBJS) cp $(OBJS) ../build clean: -rm -f $(OBJS) libxingmp3.a include $(KOS_BASE)/Makefile.rules <file_sep>/firmware/aica/codec/dac.c /* Copyright (C) 2006 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <stdio.h> #include "dac.h" #include "AT91SAM7S64.h" #define debug_printf static int wp=0, rp=0, readable_buffers=0; short dac_buffer[MAX_BUFFERS][DAC_BUFFER_MAX_SIZE]; int dac_buffer_size[MAX_BUFFERS]; int stopped; unsigned long current_srate; unsigned int underruns; void dac_reset() { wp = rp = readable_buffers = 0; dac_disable_dma(); stopped = 1; underruns = 0; dac_set_srate(44100); } // return the index of the next writeable buffer or -1 on failure int dac_get_writeable_buffer() { if (dac_writeable_buffers() > 0) { int buffer; buffer = wp; wp = (wp + 1) % MAX_BUFFERS; readable_buffers ++; return buffer; } else { return -1; } } // return the index of the next readable buffer or -1 on failure int dac_get_readable_buffer() { if (dac_readable_buffers() > 0) { int buffer; buffer = rp; rp = (rp + 1) % MAX_BUFFERS; readable_buffers --; return buffer; } else { return -1; } } // return the number of buffers that are ready to be read int dac_readable_buffers() { return readable_buffers - adc_busy_buffers(); } // return the number of buffers that are ready to be written to int dac_writeable_buffers() { return MAX_BUFFERS - readable_buffers - dac_busy_buffers() - adc_busy_buffers(); } // return the number of buffers that are set up for DMA int dac_busy_buffers() { if (!dac_next_dma_empty()) { return 2; } else if (!dac_first_dma_empty()) { return 1; } else { return 0; } } int adc_first_dma_empty() { return *AT91C_SSC_RCR == 0; } int adc_next_dma_empty() { return *AT91C_SSC_RNCR == 0; } int adc_busy_buffers() { if (!adc_next_dma_empty()) { return 2; } else if (!adc_first_dma_empty()) { return 1; } else { return 0; } } // returns -1 if there is no free DMA buffer int dac_fill_dma() { int readable_buffer; if(*AT91C_SSC_TNCR == 0 && *AT91C_SSC_TCR == 0) { if (!stopped) { // underrun stopped = 1; underruns++; puts("both buffers empty, disabling DMA"); dac_disable_dma(); } if ( (readable_buffer = dac_get_readable_buffer()) == -1 ) { return -1; } debug_printf("rb %i, size %i\n", readable_buffer, dac_buffer_size[readable_buffer]); dac_set_first_dma(dac_buffer[readable_buffer], dac_buffer_size[readable_buffer]); //puts("ffb!"); return 0; } else if(*AT91C_SSC_TNCR == 0) { if ( (readable_buffer = dac_get_readable_buffer()) == -1 ) { return -1; } debug_printf("rb %i, size %i\n", readable_buffer, dac_buffer_size[readable_buffer]); dac_set_next_dma(dac_buffer[readable_buffer], dac_buffer_size[readable_buffer]); //puts("fnb"); return 0; } else { // both DMA buffers are full if (stopped && (dac_readable_buffers() == MAX_BUFFERS - dac_busy_buffers() - adc_busy_buffers())) { // all buffers are full stopped = 0; puts("all buffers full, re-enabling DMA"); dac_enable_dma(); } return -1; } } void dac_enable_dma() { // enable DMA *AT91C_SSC_PTCR = AT91C_PDC_TXTEN; } void dac_disable_dma() { // disable DMA *AT91C_SSC_PTCR = AT91C_PDC_TXTDIS; } int dac_first_dma_empty() { return *AT91C_SSC_TCR == 0; } int dac_next_dma_empty() { return *AT91C_SSC_TNCR == 0; } void dac_set_first_dma(short *buffer, int n) { *AT91C_SSC_TPR = buffer; *AT91C_SSC_TCR = n; } void dac_set_next_dma(short *buffer, int n) { *AT91C_SSC_TNPR = buffer; *AT91C_SSC_TNCR = n; } int dma_endtx(void) { return *AT91C_SSC_SR & AT91C_SSC_ENDTX; } void dac_write_reg(unsigned char reg, unsigned short value) { unsigned char b0, b1; b1 = (reg << 1) | ((value >> 8) & 0x01); b0 = value & 0xFF; //iprintf("reg: %x, value: %x\nb1: %x, b0: %x\n", reg, value, b1, b0); // load high byte *AT91C_TWI_THR = b1; // send start condition *AT91C_TWI_CR = AT91C_TWI_START; while(!(*AT91C_TWI_SR & AT91C_TWI_TXRDY)); // send low byte *AT91C_TWI_THR = b0; while(!(*AT91C_TWI_SR & AT91C_TWI_TXRDY)); //iprintf("%lu\n", *AT91C_TWI_SR); *AT91C_TWI_CR = AT91C_TWI_STOP; while(!(*AT91C_TWI_SR & AT91C_TWI_TXCOMP)); } int dac_set_srate(unsigned long srate) { if (current_srate == srate) return 0; iprintf("setting rate %lu\n", srate); switch(srate) { case 8000: dac_write_reg(AIC_REG_SRATE, AIC_SR1|AIC_SR0|AIC_USB); break; case 8021: dac_write_reg(AIC_REG_SRATE, AIC_SR3|AIC_SR1|AIC_SR0|AIC_BOSR|AIC_USB); break; case 32000: dac_write_reg(AIC_REG_SRATE, AIC_SR2|AIC_SR1|AIC_USB); break; case 44100: dac_write_reg(AIC_REG_SRATE, AIC_SR3|AIC_BOSR|AIC_USB); break; case 48000: dac_write_reg(AIC_REG_SRATE, AIC_USB); break; case 88200: dac_write_reg(AIC_REG_SRATE, AIC_SR3|AIC_SR2|AIC_SR1|AIC_SR0|AIC_BOSR|AIC_USB); break; case 96000: dac_write_reg(AIC_REG_SRATE, AIC_SR2|AIC_SR1|AIC_SR0|AIC_USB); break; default: return -1; } current_srate = srate; return 0; } void dac_init(void) { AT91PS_PMC pPMC = AT91C_BASE_PMC; /************ PWM ***********/ /* PWM0 = MAINCK/4 */ /* *AT91C_PMC_PCER = (1 << AT91C_ID_PWMC); // Enable Clock for PWM controller *AT91C_PWMC_CH0_CPRDR = 2; // channel period = 2 *AT91C_PWMC_CH0_CMR = 1; // prescaler = 2 *AT91C_PIOA_PDR = AT91C_PA0_PWM0; // enable pin *AT91C_PWMC_CH0_CUPDR = 1; *AT91C_PWMC_ENA = AT91C_PWMC_CHID0; // enable channel 0 output */ /************ Programmable Clock Output PCK2 ***********/ // select source (MAIN CLK = external clock) // select prescaler (1) // => 12 MHz pPMC->PMC_PCKR[2] = (AT91C_PMC_PRES_CLK | AT91C_PMC_CSS_MAIN_CLK); // uncomment the following to use PLLCK/8 (if you are using a different XTAL and a PLL clock of 96 MHz): //pPMC->PMC_PCKR[2] = (AT91C_PMC_PRES_CLK_8 | AT91C_PMC_CSS_PLL_CLK); // enable PCK2 *AT91C_PMC_SCER = AT91C_PMC_PCK2; // wait while( !(*AT91C_PMC_SR & AT91C_PMC_PCK2RDY) ); // select peripheral b *AT91C_PIOA_BSR = AT91C_PA31_PCK2; // disable PIO 31 *AT91C_PIOA_PDR = AT91C_PA31_PCK2; /************* TWI ************/ // internal pull ups enabled by default // enable clock for TWI *AT91C_PMC_PCER = (1 << AT91C_ID_TWI); // disable pio *AT91C_PIOA_PDR = AT91C_PA3_TWD | AT91C_PA4_TWCK; // reset *AT91C_TWI_CR = AT91C_TWI_SWRST; // set TWI clock to ( MCK / ((CxDIV) * 2^CKDIV) + 3) ) / 2 *AT91C_TWI_CWGR = (5 << 16) | // CKDIV (255 << 8) | // CHDIV (255 << 0); // CLDIV // enable master transfer *AT91C_TWI_CR = AT91C_TWI_MSEN; // master mode *AT91C_TWI_MMR = AT91C_TWI_IADRSZ_NO | (0x1A << 16); // codec address = 0b0011010 = 0x1A dac_write_reg(AIC_REG_RESET, 0x00); dac_write_reg(AIC_REG_POWER, 0 << 1); // Line in powered down dac_write_reg(AIC_REG_SRATE, AIC_SR3|AIC_BOSR|AIC_USB); // mic bypass test //dac_write_reg(AIC_REG_AN_PATH, AIC_STE|AIC_STA2|AIC_INSEL|AIC_MICB); // enable DAC,input select=MIC, mic boost dac_write_reg(AIC_REG_AN_PATH, AIC_DAC|AIC_INSEL|AIC_MICB); // enable DAC,input select=MIC, mic boost dac_write_reg(AIC_REG_DIG_PATH, 0 << 3); // disable soft mute dac_write_reg(AIC_REG_DIG_FORMAT, (1 << 6) | 2); // master, I2S left aligned dac_write_reg(AIC_REG_DIG_ACT, 1 << 0); // activate digital interface /************ SSC ***********/ *AT91C_PMC_PCER = (1 << AT91C_ID_SSC); // Enable Clock for SSC controller *AT91C_SSC_CR = AT91C_SSC_SWRST; // reset *AT91C_SSC_CMR = 0; // no divider //*AT91C_SSC_CMR = 18; // slow for testing *AT91C_SSC_TCMR = AT91C_SSC_CKS_RK | // external clock on TK AT91C_SSC_START_EDGE_RF | // any edge (0 << 16); // STTDLY = 0! *AT91C_SSC_TFMR = (15) | // 16 bit word length (0 << 8) | // DATNB = 0 => 1 words per frame AT91C_SSC_MSBF; // MSB first *AT91C_PIOA_PDR = AT91C_PA16_TK | AT91C_PA15_TF | AT91C_PA17_TD | AT91C_PA18_RD; // enable pins *AT91C_SSC_CR = AT91C_SSC_TXEN; // enable TX /*********** SSC RX ************/ *AT91C_SSC_RCMR = AT91C_SSC_CKS_TK | AT91C_SSC_START_TX | AT91C_SSC_CKI | // sample on rising clock edge (1 << 16); // STTDLY = 0 *AT91C_SSC_RFMR = (15) | // 16 bit word length (0 << 8) | // DATNB = 0 => 1 words per frame AT91C_SSC_MSBF; // MSB first *AT91C_SSC_CR = AT91C_SSC_RXEN; // enable RX dac_reset(); } <file_sep>/modules/aicaos/arm/spinlock.h #ifndef _SPINLOCK_H #define _SPINLOCK_H #include "interrupt.h" #include "task.h" typedef volatile int spinlock_t; #define SPINLOCK_INITIALIZER 0 #define spinlock_init(A) *(A) = SPINLOCK_INITIALIZER static inline int spinlock_trylock(spinlock_t *lock) { int res = 0, context = int_disable(); if (!*lock) res = *lock = 1; int_restore(context); return res; } #define spinlock_lock(A) while (!spinlock_trylock(A)) task_reschedule() #define spinlock_unlock(A) *(A) = 0 #define spinlock_is_locked(A) ( *(A) != 0 ) #endif <file_sep>/modules/ffmpeg/sdl_player.c /* DreamShell ##version## sdl_player.c - SDL_ffmpeg player Copyright (C)2011-2014 SWAT */ #include "ds.h" #include "SDL.h" #include "SDL_ffmpeg.h" #include <string.h> /* as an example we create an audio buffer consisting of BUF_SIZE frames */ #define BUF_SIZE 3 /* pointer to file we will be opening */ static SDL_ffmpegFile *file = 0; /* create a buffer for audio frames */ static SDL_ffmpegAudioFrame *audioFrame[BUF_SIZE]; /* simple way of syncing, just for example purposes */ static uint64_t sync = 0, offset = 0; /* returns the current position the file should be at */ static uint64_t getSync() { if ( file ) { if ( SDL_ffmpegValidAudio( file ) ) { return sync; } if ( SDL_ffmpegValidVideo( file ) ) { return ( SDL_GetTicks() % SDL_ffmpegDuration( file ) ) + offset; } } return 0; } /* use a mutex to prevent errors due to multithreading */ static SDL_mutex *mutex = 0; static void audioCallback( void *data, Uint8 *stream, int length ) { /* lock mutex, so audioFrame[0] will not be changed from another thread */ SDL_LockMutex( mutex ); if ( audioFrame[0]->size == length ) { /* update sync */ sync = audioFrame[0]->pts; /* copy the data to the output */ memcpy( stream, audioFrame[0]->buffer, audioFrame[0]->size ); /* mark data as used */ audioFrame[0]->size = 0; /* move frames in buffer */ SDL_ffmpegAudioFrame *f = audioFrame[0]; int i; for ( i = 1; i < BUF_SIZE; i++ ) audioFrame[i-1] = audioFrame[i]; audioFrame[BUF_SIZE-1] = f; } else { /* no data available, just set output to zero */ memset( stream, 0, length ); } /* were done with the audio frame, release lock */ SDL_UnlockMutex( mutex ); return; } int sdl_ffplay(const char *filename) { char fn[NAME_MAX]; sprintf(fn, "ds:%s", filename); /* open file from arg[1] */ file = SDL_ffmpegOpen(fn); if ( !file ) { ds_printf("DS_ERROR: Could not open %s: %s\n", fn, SDL_ffmpegGetError() ); return -1; } /* initialize the mutex */ mutex = SDL_CreateMutex(); /* select the stream you want to decode (example just uses 0 as a default) */ SDL_ffmpegSelectVideoStream( file, 0 ); /* print frame rate of video stream */ SDL_ffmpegStream *stream = SDL_ffmpegGetVideoStream( file, 0 ); if ( stream ) { ds_printf("DS_ERROR: Selected video stream 0, frame rate: %.2f\n", SDL_ffmpegGetFrameRate( stream, 0, 0 ) ); } /* if no audio can be selected, audio will not be used in this example */ SDL_ffmpegSelectAudioStream( file, 0 ); /* print frame rate of audio stream */ stream = SDL_ffmpegGetAudioStream( file, 0 ); if ( stream ) { ds_printf("DS_ERROR: Selected audio stream 0, frame rate: %.2f\n", SDL_ffmpegGetFrameRate( stream, 0, 0 ) ); } /* get the audiospec which fits the selected audiostream, if no audiostream is selected, default values are used (2 channel, 48Khz) */ SDL_AudioSpec specs = SDL_ffmpegGetAudioSpec( file, 512, audioCallback ); /* we get the size from our active video stream, if no active video stream exists, width and height are set to zero */ int w, h; SDL_ffmpegGetVideoSize( file, &w, &h ); /* Open the Video device */ SDL_Surface *screen = GetScreen(); /* create a video frame which will be used to receive the video data. */ SDL_ffmpegVideoFrame *videoFrame = SDL_ffmpegCreateVideoFrame(); /* depending on which type of surface you want to use, you either create an RGB or an YUV buffer */ /* RGB */ videoFrame->surface = SDL_CreateRGBSurface( 0, screen->w, screen->h, 24, 0x0000FF, 0x00FF00, 0xFF0000, 0 ); /* YUV */ /* videoFrame->overlay = SDL_CreateYUVOverlay( screen->w, screen->h, SDL_YUY2_OVERLAY, screen ); */ /* create a SDL_Rect for blitting of image data */ SDL_Rect rect; rect.x = 0; rect.y = 0; rect.w = w; rect.h = h; /* check if a valid audio stream was selected */ if ( SDL_ffmpegValidAudio( file ) ) { /* Open the Audio device */ if ( SDL_OpenAudio( &specs, 0 ) < 0 ) { fprintf( stderr, "Couldn't open audio: %s\n", SDL_GetError() ); SDL_Quit(); return -1; } /* calculate frame size ( 2 bytes per sample ) */ int frameSize = specs.channels * specs.samples * 2; /* prepare audio buffer */ int i; for ( i = 0; i < BUF_SIZE; i++ ) { /* create frame */ audioFrame[i] = SDL_ffmpegCreateAudioFrame( file, frameSize ); /* check if we got a frame */ if ( !audioFrame[i] ) { /* no frame could be created, this is fatal */ goto CLEANUP_DATA; } /* fill frame with data */ SDL_ffmpegGetAudioFrame( file, audioFrame[i] ); } /* we unpause the audio so our audiobuffer gets read */ SDL_PauseAudio( 0 ); } int done = 0, mouseState = 0; while ( !done ) { /* just some standard SDL event stuff */ SDL_Event event; while ( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_QUIT: done = 1; break; case SDL_MOUSEBUTTONUP: mouseState = 0; break; case SDL_MOUSEBUTTONDOWN: mouseState = 1; break; case SDL_KEYDOWN: if ( event.key.keysym.sym == SDLK_ESCAPE ) { done = 1; } } } if ( mouseState ) { int x, y; SDL_GetMouseState( &x, &y ); /* by clicking you turn on the stream, seeking to the percentage in time, based on the x-position you clicked on */ uint64_t time = ( uint64_t )((( double )x / ( double )w ) * SDL_ffmpegDuration( file ) ); /* lock mutex when working on data which is shared with the audiocallback */ SDL_LockMutex( mutex ); /* invalidate current video frame */ if ( videoFrame ) videoFrame->ready = 0; /* invalidate buffered audio frames */ if ( SDL_ffmpegValidAudio( file ) ) { int i; for ( i = 0; i < BUF_SIZE; i++ ) { audioFrame[i]->size = 0; } } /* we seek to time (milliseconds) */ SDL_ffmpegSeek( file, time ); /* store new offset */ offset = time - ( getSync() - offset ); /* we release the mutex so the new data can be handled */ SDL_UnlockMutex( mutex ); } /* check if we need to decode audio data */ if ( SDL_ffmpegValidAudio( file ) ) { /* lock mutex when working on data which is shared with the audiocallback */ SDL_LockMutex( mutex ); /* fill empty spaces in audio buffer */ int i; for ( i = 0; i < BUF_SIZE; i++ ) { /* check if frame is empty */ if ( !audioFrame[i]->size ) { /* fill frame with new data */ SDL_ffmpegGetAudioFrame( file, audioFrame[i] ); } } SDL_UnlockMutex( mutex ); } if ( videoFrame ) { /* check if video frame is ready */ if ( !videoFrame->ready ) { /* not ready, try to get a new frame */ SDL_ffmpegGetVideoFrame( file, videoFrame ); } else if ( videoFrame->pts <= getSync() ) { /* video frame ready and in sync */ if ( videoFrame->overlay ) { /* blit overlay */ //SDL_DisplayYUVOverlay( videoFrame->overlay, &rect ); } else if ( videoFrame->surface ) { /* blit RGB surface */ LockVideo(); SDL_BlitSurface( videoFrame->surface, 0, screen, 0 ); UnlockVideo(); /* flip screen */ //SDL_Flip( screen ); } /* video frame is displayed, make sure we don't show it again */ videoFrame->ready = 0; } } } CLEANUP_DATA: /* cleanup audio related data */ if ( SDL_ffmpegValidAudio( file ) ) { /* stop audio callback */ SDL_PauseAudio( 1 ); /* clean up frames */ int i; for ( i = 0; i < BUF_SIZE; i++ ) { SDL_ffmpegFreeAudioFrame( audioFrame[i] ); } } /* cleanup video data */ if ( videoFrame ) { SDL_ffmpegFreeVideoFrame( videoFrame ); } /* after all is said and done, we should call this */ SDL_ffmpegFree( file ); return 0; } <file_sep>/firmware/isoldr/loader/kos/src/asm.h #ifdef __STDC__ # define _C_LABEL(x) _ ## x #else # define _C_LABEL(x) _/**/x #endif #define _ASM_LABEL(x) x #if __SH5__ # if __SH5__ == 32 && __SHMEDIA__ # define TEXT .section .text..SHmedia32, "ax" # else # define TEXT .text # endif # define _ENTRY(name) \ TEXT; .balign 8; .globl name; name: #else #define _ENTRY(name) \ .text; .align 2; .globl name; name: #endif /* __SH5__ */ #define ENTRY(name) \ _ENTRY(_C_LABEL(name)) #if (defined (__sh2__) || defined (__SH2E__) || defined (__sh3__) || defined (__SH3E__) \ || defined (__SH4_SINGLE__) || defined (__SH4__)) \ || defined (__SH4_SINGLE_ONLY__) || defined (__SH5__) || defined (__SH2A__) #define DELAYED_BRANCHES #define SL(branch, dest, in_slot, in_slot_arg2) \ branch##.s dest; in_slot, in_slot_arg2 #else #define SL(branch, dest, in_slot, in_slot_arg2) \ in_slot, in_slot_arg2; branch dest #endif #ifdef __LITTLE_ENDIAN__ #define SHHI shlld #define SHLO shlrd #else #define SHHI shlrd #define SHLO shlld #endif #define __ALIGN .balign 4 #define __ALIGN_STR ".balign 4" //#ifndef __SH_FPU_ANY__ //#define __SH_FPU_ANY__ //#endif <file_sep>/modules/ppp/module.c /* DreamShell ##version## module.c - PPP module Copyright (C)2014-2019 SWAT */ #include "ds.h" #include <ppp/ppp.h> DEFAULT_MODULE_EXPORTS_CMD(ppp, "PPP connection manager"); int builtin_ppp_cmd(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s options args\n" "Options: \n" " -i, --init -Initialize PPP connection\n" " -s, --shut -Shutdown PPP connection\n" " -B, --blind -Blind dial (don't wait for a dial tone)\n\n", argv[0]); ds_printf("Arguments: \n" " -b, --bps -Baudrate for scif\n" " -n, --number -Number to dial\n" " -u, --username -Username (dream by default)\n" " -p, --password -Password (<PASSWORD> by default)\n" " -d, --device -Device, scif or modem (default)\n\n"); return CMD_NO_ARG; } int rc, isSerial = 0, init_ppp = 0, shut_ppp = 0; int conn_rate = 0, blind = 0, bps = 115200; char *number = "1111111", *username = "dream", *password = "<PASSWORD>"; char *device = "modem"; struct cfg_option options[] = { {"init", 'i', NULL, CFG_BOOL, (void *) &init_ppp, 0}, {"shut", 's', NULL, CFG_BOOL, (void *) &shut_ppp, 0}, {"bps", 'b', NULL, CFG_INT, (void *) &bps, 0}, {"blind", 'B', NULL, CFG_BOOL, (void *) &blind, 0}, {"number", 'n', NULL, CFG_STR, (void *) &number, 0}, {"username", 'u', NULL, CFG_STR, (void *) &username, 0}, {"password", 'p', NULL, CFG_STR, (void *) &password, 0}, {"device", 'd', NULL, CFG_STR, (void *) &device, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(init_ppp) { ppp_init(); if(!strncasecmp(device, "scif", 4)) { isSerial = 1; rc = ppp_scif_init(bps); } else { rc = ppp_modem_init(number, blind, &conn_rate); } if(rc < 0) { ds_printf("DS_ERROR: Modem PPP initialization failed!\n"); if (isSerial) { scif_shutdown(); } else { modem_shutdown(); } return CMD_ERROR; } ppp_set_login(username, password); rc = ppp_connect(); if(rc < 0) { ds_printf("DS_ERROR: Link establishment failed!\n"); return CMD_ERROR; } ds_printf("DS_OK: Link established, rate is %d bps\n", conn_rate); char ip_str[64]; memset(ip_str, 0, sizeof(ip_str)); snprintf(ip_str, sizeof(ip_str), "%d.%d.%d.%d", net_default_dev->ip_addr[0], net_default_dev->ip_addr[1], net_default_dev->ip_addr[2], net_default_dev->ip_addr[3]); setenv("NET_IPV4", ip_str, 1); ds_printf("Network IPv4 address: %s\n", ip_str); return CMD_OK; } if(shut_ppp) { ppp_shutdown(); if(modem_is_connected() || modem_is_connecting()) { modem_shutdown(); setenv("NET_IPV4", "0.0.0.0", 1); } ds_printf("DS_OK: Complete!\n"); return CMD_OK; } return CMD_NO_ARG; } <file_sep>/modules/mp3/libmp3/xingmp3/xinglmc.h /*____________________________________________________________________________ FreeAmp - The Free MP3 Player Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ #ifndef INCLUDED_XINGLMC_H_ #define INCLUDED_XINGLMC_H_ /* system headers */ #include <stdlib.h> #include <time.h> /* project headers */ #include "config.h" #include "pmi.h" #include "pmo.h" #include "mutex.h" #include "event.h" #include "lmc.h" #include "thread.h" #include "mutex.h" #include "queue.h" #include "semaphore.h" extern "C" { #include "mhead.h" #include "port.h" } #define BS_BUFBYTES 60000U #define PCM_BUFBYTES 60000U #define FRAMES_FLAG 0x0001 #define BYTES_FLAG 0x0002 #define TOC_FLAG 0x0004 #define VBR_SCALE_FLAG 0x0008 #define FRAMES_AND_BYTES (FRAMES_FLAG | BYTES_FLAG) // structure to receive extracted header // toc may be NULL typedef struct { int h_id; // from MPEG header, 0=MPEG2, 1=MPEG1 int samprate; // determined from MPEG header int flags; // from Xing header data int frames; // total bit stream frames from Xing header data int bytes; // total bit stream bytes from Xing header data int vbr_scale; // encoded vbr scale from Xing header data unsigned char *toc; // pointer to unsigned char toc_buffer[100] // may be NULL if toc not desired } XHEADDATA; enum { lmcError_MinimumError = 1000, lmcError_DecodeFailed, lmcError_AudioDecodeInitFailed, lmcError_DecoderThreadFailed, lmcError_PMIError, lmcError_PMOError, lmcError_MaximumError }; class XingLMC:public LogicalMediaConverter { public: XingLMC(FAContext *context); virtual ~XingLMC(); virtual uint32 CalculateSongLength(const char *url); virtual Error ChangePosition(int32 position); virtual Error CanDecode(); virtual void Clear(); virtual Error ExtractMediaInfo(); virtual void SetPMI(PhysicalMediaInput *pmi) { m_pPmi = pmi; }; virtual void SetPMO(PhysicalMediaOutput *pmo) { m_pPmo = pmo; }; virtual Error Prepare(PullBuffer *pInputBuffer, PullBuffer *&pOutBuffer); virtual Error InitDecoder(); virtual Error SetEQData(float *, float); virtual Error SetEQData(bool); virtual Error SetDecodeInfo(DecodeInfo &info); virtual vector<string> *GetExtensions(void); private: static void DecodeWorkerThreadFunc(void *); void DecodeWork(); Error BeginRead(void *&pBuffer, unsigned int iBytesNeeded); Error EndRead(size_t iBytesUsed); Error AdvanceBufferToNextFrame(); Error GetHeadInfo(); Error GetBitstreamStats(float &fTotalSeconds, float &fMsPerFrame, int32 &iTotalFrames, int32 &iSampleRate, int32 &iLayer); int GetXingHeader(XHEADDATA *X, unsigned char *buf); int SeekPoint(unsigned char TOC[100], int file_bytes, float percent); int ExtractI4(unsigned char *buf); PhysicalMediaInput *m_pPmi; PhysicalMediaOutput *m_pPmo; int m_iMaxWriteSize; int32 m_frameBytes, m_iBufferUpInterval, m_iBufferSize; size_t m_lFileSize; MPEG_HEAD m_sMpegHead; int32 m_iBitRate, m_iTotalFrames; bool m_bBufferingUp; Thread *m_decoderThread; int32 m_frameCounter; time_t m_iBufferUpdate; char *m_szUrl; const char *m_szError; XHEADDATA *m_pXingHeader; // These vars are used for a nasty hack. FILE *m_fpFile; char *m_pLocalReadBuffer; MPEG m_sMPEG; }; #endif /* _XINGLMC_H */ <file_sep>/lib/SDL_Console/Makefile # by SWAT SUBDIRS = src include $(KOS_BASE)/addons/Makefile.prefab <file_sep>/firmware/isoldr/loader/kos/unistd.h /* KallistiOS ##version## unistd.h (c)2000-2001 <NAME> $Id: unistd.h,v 1.1 2002/02/09 06:15:42 bardtx Exp $ */ #ifndef __UNISTD_H #define __UNISTD_H #include <sys/cdefs.h> __BEGIN_DECLS #include <stddef.h> #include <arch/types.h> #define true (1) #define false (0) void usleep(unsigned long usec); __END_DECLS #endif /* __UNISTD_H */ <file_sep>/modules/adx/LibADX/snddrv.c /* ** ** (C) Josh 'PH3NOM' Pearson 2011 ** */ /* ** To anyone looking at this code: ** ** This driver runs in its own thread on the sh4. ** ** When the AICA driver requests more samples, ** it will signal sndbuf_status=SNDDRV_STATUS_NEEDBUF ** and assign the number of requested samples to snddrv.pcm_needed. ** ** The decoders need to check sndbuf_status, ** when more samples are requested by the driver ** the decoders will loop ** decoding into pcm_buffer untill pcm_bytes==snddrv.pcm_needed ** at that point the decoder signals sndbuf_status=SNDDRV_STATUS_HAVEBUF ** */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <kos/thread.h> #include <dc/sound/stream.h> #include "audio/snddrv.h" snd_stream_hnd_t shnd; kthread_t * snddrv_thd; static int snddrv_vol = 255; /* Increase the Sound Driver volume */ int snddrv_volume_up() { if( snddrv_vol <= 245 ) { snddrv_vol += 10; snd_stream_volume(shnd, snddrv_vol); } return snddrv_vol; } /* Decrease the Sound Driver volume */ int snddrv_volume_down() { if( snddrv_vol >= 10 ) { snddrv_vol -= 10; snd_stream_volume(shnd, snddrv_vol); } return snddrv_vol; } /* Exit the Sound Driver */ int snddrv_exit() { if( snddrv.drv_status != SNDDRV_STATUS_NULL ) { snddrv.drv_status = SNDDRV_STATUS_DONE; snddrv.buf_status = SNDDRV_STATUS_BUFEND; while( snddrv.drv_status != SNDDRV_STATUS_NULL ) thd_pass(); printf("SNDDRV: Exited\n"); } memset( snddrv.pcm_buffer, 0, 65536+16384); snddrv.pcm_bytes = 0; snddrv.pcm_needed = 0; SNDDRV_FREE_STRUCT(); return snddrv.drv_status; } /* Signal how many samples the AICA needs, then wait for the deocder to produce them */ static void *snddrv_callback(snd_stream_hnd_t hnd, int len, int * actual) { /* Signal the Decoder thread how many more samples are needed */ snddrv.pcm_needed = len; snddrv.buf_status = SNDDRV_STATUS_NEEDBUF; /* Wait for the samples to be ready */ while( snddrv.buf_status != SNDDRV_STATUS_HAVEBUF && snddrv.buf_status != SNDDRV_STATUS_BUFEND ) thd_pass(); snddrv.pcm_ptr = snddrv.pcm_buffer; snddrv.pcm_bytes = 0; *actual = len; return snddrv.pcm_ptr; } static void *snddrv_thread() { printf("SNDDRV: Rate - %i, Channels - %i\n", snddrv.rate, snddrv.channels); shnd = snd_stream_alloc(snddrv_callback, SND_STREAM_BUFFER_MAX/4); snd_stream_start(shnd, snddrv.rate, snddrv.channels-1); snddrv.drv_status = SNDDRV_STATUS_STREAMING; while( snddrv.drv_status != SNDDRV_STATUS_DONE && snddrv.drv_status != SNDDRV_STATUS_ERROR ) { snd_stream_poll(shnd); thd_sleep(20); } snddrv.drv_status = SNDDRV_STATUS_NULL; snd_stream_destroy(shnd); snd_stream_shutdown(); printf("SNDDRV: Finished\n"); return NULL; } /* Start the AICA Sound Stream Thread */ int snddrv_start( int rate, int chans ) { snddrv.rate = rate; snddrv.channels = chans; if( snddrv.channels > 2) { printf("SNDDRV: ERROR - Exceeds maximum channels\n"); return -1; } printf("SNDDRV: Creating Driver Thread\n"); snddrv.drv_status = SNDDRV_STATUS_INITIALIZING; snd_stream_init(); snddrv_thd = thd_create(0, snddrv_thread, NULL ); return snddrv.drv_status; } <file_sep>/modules/ftpd/Makefile # # FTP server module for DreamShell # Copyright (C)2023 SWAT # http://www.dc-swat.ru # TARGET_NAME = ftpd LIBRARY_NAME = lftpd OBJS = module.o \ $(LIBRARY_NAME)/lftpd.o \ $(LIBRARY_NAME)/lftpd_inet.o \ $(LIBRARY_NAME)/lftpd_string.o \ $(LIBRARY_NAME)/lftpd_log.o \ $(LIBRARY_NAME)/lftpd_io.o DBG_LIBS = -lds EXPORTS_FILE = exports.txt VER_MAJOR = 0 VER_MINOR = 1 VER_MICRO = 0 all: rm-elf #$(LIBRARY_NAME)/Makefile include ../../sdk/Makefile.loadable KOS_CFLAGS += -I$(DS_SDK)/include/network $(LIBRARY_NAME)/Makefile: git clone https://github.com/vonnieda/$(LIBRARY_NAME).git cd ./$(LIBRARY_NAME) && git checkout 7c54d2676ba7a2bcf9f72fd21557d5b97729771f rm-elf: -rm -f $(TARGET) || true -rm -f $(TARGET_LIB) || true install: $(TARGET) $(TARGET_LIB) -rm -f $(DS_BUILD)/modules/$(TARGET) || true -rm -f $(DS_SDK)/lib/$(TARGET_LIB) || true cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/lib/SDL_gui/ScrollBar.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_ScrollBar::GUI_ScrollBar(const char *aname, int x, int y, int w, int h) : GUI_Widget(aname, x, y, w, h) { SDL_Rect in; in.x = 4; in.y = 4; in.w = w-8; in.h = w-8; SetTransparent(1); background = new GUI_Surface("bg", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); knob = new GUI_Surface("knob", SDL_HWSURFACE, w, w, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); position_x = 0; position_y = 0; tracking_on = 0; tracking_start_x = 0; tracking_start_y = 0; tracking_pos_x = 0; tracking_pos_y = 0; knob->Fill(NULL, 0x00FFFFFF); knob->Fill(&in, 0x004040FF); background->Fill(NULL, 0x00FFFFFF); in.h = h-8; background->Fill(&in, 0xFF000000); moved_callback = 0; wtype = WIDGET_TYPE_SCROLLBAR; } GUI_ScrollBar::~GUI_ScrollBar(void) { knob->DecRef(); background->DecRef(); if (moved_callback) moved_callback->DecRef(); } void GUI_ScrollBar::Update(int force) { if (parent == 0) return; if (force) { if (flags & WIDGET_TRANSPARENT) parent->Erase(&area); if (background) parent->Draw(background, NULL, &area); if (knob) { SDL_Rect sr, dr; sr.w = dr.w = knob->GetWidth(); sr.h = dr.h = knob->GetHeight(); dr.x = area.x + position_x; dr.y = area.y + position_y; sr.x = 0; sr.y = 0; parent->Draw(knob, &sr, &dr); } } } void GUI_ScrollBar::Erase(const SDL_Rect *rp) { SDL_Rect dest; //assert(parent != NULL); //assert(rp != NULL); if(parent != NULL && rp != NULL) { dest = Adjust(rp); if (flags & WIDGET_TRANSPARENT) parent->Erase(&dest); if (background) parent->TileImage(background, &dest, 0, 0); } } int GUI_ScrollBar::Event(const SDL_Event *event, int xoffset, int yoffset) { switch (event->type) { case SDL_MOUSEMOTION: { //SDL_GetMouseState(&event->motion.x, &event->motion.y); int x = event->motion.x - area.x - xoffset; int y = event->motion.y - area.y - yoffset; if (tracking_on) { position_x = tracking_pos_x + x - tracking_start_x; position_y = tracking_pos_y + y - tracking_start_y; if (position_x < 0) position_x = 0; if (position_x > area.w - knob->GetWidth()) position_x = area.w - knob->GetWidth(); if (position_y < 0) position_y = 0; if (position_y > area.h - knob->GetHeight()) position_y = area.h - knob->GetHeight(); MarkChanged(); if (moved_callback) { moved_callback->Call(this); } return 1; } break; } case SDL_MOUSEBUTTONDOWN: { if (flags & WIDGET_INSIDE) { int x = event->button.x - area.x - xoffset; int y = event->button.y - area.y - yoffset; /* if the cursor is inside the knob, start tracking */ if (y >= position_y && y < position_y + knob->GetHeight() && x >= position_x && x < position_x + knob->GetWidth()) { tracking_on = 1; tracking_start_x = x; tracking_pos_x = position_x; tracking_start_y = y; tracking_pos_y = position_y; } return 1; } break; } case SDL_MOUSEBUTTONUP: { if (tracking_on) { tracking_on = 0; } break; } } return GUI_Drawable::Event(event, xoffset, yoffset); } void GUI_ScrollBar::SetKnobImage(GUI_Surface *image) { if (GUI_ObjectKeep((GUI_Object **) &knob, image)) MarkChanged(); } GUI_Surface *GUI_ScrollBar::GetKnobImage() { return knob; } void GUI_ScrollBar::SetBackgroundImage(GUI_Surface *image) { if (GUI_ObjectKeep((GUI_Object **) &background, image)) MarkChanged(); } int GUI_ScrollBar::GetHorizontalPosition(void) { return position_x; } int GUI_ScrollBar::GetVerticalPosition(void) { return position_y; } void GUI_ScrollBar::SetHorizontalPosition(int value) { position_x = value; MarkChanged(); } void GUI_ScrollBar::SetVerticalPosition(int value) { position_y = value; MarkChanged(); } void GUI_ScrollBar::SetMovedCallback(GUI_Callback *callback) { GUI_ObjectKeep((GUI_Object **) &moved_callback, callback); } extern "C" { GUI_Widget *GUI_ScrollBarCreate(const char *name, int x, int y, int w, int h) { return new GUI_ScrollBar(name, x, y, w, h); } int GUI_ScrollBarCheck(GUI_Widget *widget) { // FIXME not implemented return 0; } void GUI_ScrollBarSetKnobImage(GUI_Widget *widget, GUI_Surface *image) { ((GUI_ScrollBar *) widget)->SetKnobImage(image); } GUI_Surface *GUI_ScrollBarGetKnobImage(GUI_Widget *widget) { return ((GUI_ScrollBar *) widget)->GetKnobImage(); } void GUI_ScrollBarSetBackgroundImage(GUI_Widget *widget, GUI_Surface *image) { ((GUI_ScrollBar *) widget)->SetBackgroundImage(image); } void GUI_ScrollBarSetPosition(GUI_Widget *widget, int value) { ((GUI_ScrollBar *) widget)->SetVerticalPosition(value); } void GUI_ScrollBarSetMovedCallback(GUI_Widget *widget, GUI_Callback *callback) { ((GUI_ScrollBar *) widget)->SetMovedCallback(callback); } int GUI_ScrollBarGetPosition(GUI_Widget *widget) { return ((GUI_ScrollBar *) widget)->GetVerticalPosition(); } int GUI_ScrollBarGetHorizontalPosition(GUI_Widget *widget) { return ((GUI_ScrollBar *) widget)->GetHorizontalPosition(); } int GUI_ScrollBarGetVerticalPosition(GUI_Widget *widget) { return ((GUI_ScrollBar *) widget)->GetVerticalPosition(); } void GUI_ScrollBarSetHorizontalPosition(GUI_Widget *widget, int value) { ((GUI_ScrollBar *) widget)->SetHorizontalPosition(value); } void GUI_ScrollBarSetVerticalPosition(GUI_Widget *widget, int value) { ((GUI_ScrollBar *) widget)->SetVerticalPosition(value); } }<file_sep>/modules/gumbo/gumbo/README.md Gumbo - A pure-C HTML5 parser. ============ Gumbo is an implementation of the [HTML5 parsing algorithm](http://www.whatwg.org/specs/web-apps/current-work/multipage/#auto-toc-12) implemented as a pure C99 library with no outside dependencies. It's designed to serve as a building block for other tools and libraries such as linters, validators, templating languages, and refactoring and analysis tools. Goals & features: * Fully conformant with the [HTML5 spec](http://www.whatwg.org/specs/web-apps/current-work/multipage/). * Robust and resilient to bad input. * Simple API that can be easily wrapped by other languages. * Support for source locations and pointers back to the original text. * Relatively lightweight, with no outside dependencies. * Passes all [html5lib-0.95 tests](https://github.com/html5lib/html5lib-tests). * Tested on over 2.5 billion pages from Google's index. Non-goals: * Execution speed. Gumbo gains some of this by virtue of being written in C, but it is not an important consideration for the intended use-case, and was not a major design factor. * Support for encodings other than UTF-8. For the most part, client code can convert the input stream to UTF-8 text using another library before processing. * C89 support. Most major compilers support C99 by now; the major exception (Microsoft Visual Studio) should be able to compile this in C++ mode with relatively few changes. (Bug reports welcome.) Wishlist (aka "We couldn't get these into the original release, but are hoping to add them soon"): * Support for recent HTML5 spec changes to support the template tag. * Support for fragment parsing. * Full-featured error reporting. * Bindings in other languages. Installation ============ To build and install the library, issue the standard UNIX incantation from the root of the distribution: $ ./configure $ make $ sudo make install Gumbo comes with full pkg-config support, so you can use the pkg-config to print the flags needed to link your program against it: $ pkg-config --cflags gumbo # print compiler flags $ pkg-config --libs gumbo # print linker flags $ pkg-config --cflags --libs gumbo # print both For example: $ gcc my_program.c `pkg-config --cflags --libs gumbo` See the pkg-config man page for more info. There are a number of sample programs in the examples/ directory. They're built automatically by 'make', but can also be made individually with 'make <programname>' (eg. 'make clean_text'). To run the unit tests, you'll need to have [googletest](https://code.google.com/p/googletest/) downloaded and unzipped. The googletest maintainers recommend against using 'make install'; instead, symlink the root googletest directory to 'gtest' inside gumbo's root directory, and then 'make check': $ unzip gtest-1.6.0.zip $ cd gumbo-* $ ln -s ../gtest-1.6.0 gtest $ make check Gumbo's 'make check' has code to automatically configure & build gtest and then link in the library. Basic Usage =========== Within your program, you need to include "gumbo.h" and then issue a call to gumbo_parse: ```C++ #include "gumbo.h" int main(int argc, char** argv) { GumboOutput* output = gumbo_parse(argv[1]); // Do stuff with output->root gumbo_destroy_output(&kGumboDefaultOptions, output); } ``` See the API documentation and sample programs for more details. A note on API/ABI compatibility =============================== We'll make a best effort to preserve API compatibility between releases. The initial release is a 0.9 (beta) release to solicit comments from early adopters, but if no major problems are found with the API, a 1.0 release will follow shortly, and the API of that should be considered stable. If changes are necessary, we follow [semantic versioning](http://semver.org). We make no such guarantees about the ABI, and it's very likely that subsequent versions may require a recompile of client code. For this reason, we recommend NOT using Gumbo data structures throughout a program, and instead limiting them to a translation layer that picks out whatever data is needed from the parse tree and then converts that to persistent data structures more appropriate for the application. The API is structured to encourage this use, with a single delete function for the whole parse tree, and is not designed with mutation in mind. Python usage ============ To install the python bindings, make sure that the C library is installed first, and then "sudo python setup.py install" from the root of the distro. This installs a 'gumbo' module; 'pydoc gumbo' should tell you about it. Recommended best-practice for Python usage is to use one of the adapters to an existing API (personally, I prefer BeautifulSoup) and write your program in terms of those. The raw CTypes bindings should be considered building blocks for higher-level libraries and rarely referenced directly. <file_sep>/include/network/net.h /** * \file net.h * \brief Network utils * \date 2007-2023 * \author SWAT www.dc-swat.ru */ #ifndef _DS_NET_H #define _DS_NET_H #include <sys/cdefs.h> #include <arch/types.h> /** * Initialize and shutdown DreamShell network */ int InitNet(uint32 ipl); void ShutdownNet(); /** * Utils */ #define READIP(dst, src) \ dst = ((src[0]) << 24) | \ ((src[1]) << 16) | \ ((src[2]) << 8) | \ ((src[3]) << 0) #define SETIP(target, src) \ IP4_ADDR(target, \ (src >> 24) & 0xff, \ (src >> 16) & 0xff, \ (src >> 8) & 0xff, \ (src >> 0) & 0xff) #endif /* _DS_NET_H */ <file_sep>/modules/bzip2/module.c /* DreamShell ##version## module.c - bzip2 module Copyright (C)2009-2014 SWAT */ #include "ds.h" #include "bzlib.h" DEFAULT_MODULE_EXPORTS_CMD(bzip2, "bzip2 archiver"); int builtin_bzip2_cmd(int argc, char *argv[]) { if(argc < 3) { ds_printf("Usage: %s option infile outfile\n" "Options: \n" " -9 -Compress with mode from 0 to 9\n" " -d -Decompress\n\n" "Examples: %s -9 /cd/file.dat /ram/file.dat.bz2\n" " %s -d /ram/file.dat.bz2 /ram/file.dat\n", argv[0], argv[0], argv[0]); return CMD_NO_ARG; } char dst[NAME_MAX]; char buff[512]; int len = 0; file_t fd; BZFILE *zfd; if(argc < 4) { char tmp[NAME_MAX]; relativeFilePath_wb(tmp, argv[2], strrchr(argv[2], '/')); sprintf(dst, "%s.bz2", tmp); } else { strcpy(dst, argv[3]); } if(!strcmp("-d", argv[1])) { ds_printf("DS_PROCESS: Decompressing '%s' ...\n", argv[2]); zfd = BZ2_bzopen(argv[2], "rb"); if(zfd == NULL) { ds_printf("DS_ERROR: Can't create file: %s\n", argv[2]); return CMD_ERROR; } fd = fs_open(dst, O_WRONLY | O_CREAT); if(fd < 0) { ds_printf("DS_ERROR: Can't open file: %s\n", dst); BZ2_bzclose(zfd); return CMD_ERROR; } while((len = BZ2_bzread(zfd, buff, sizeof(buff))) > 0) { fs_write(fd, buff, len); } BZ2_bzclose(zfd); fs_close(fd); ds_printf("DS_OK: File decompressed."); } else if(argv[1][1] >= '0' && argv[1][1] <= '9') { char mode[3]; sprintf(mode, "wb%c", argv[1][1]); ds_printf("DS_PROCESS: Compressing '%s' with mode '%c' ...\n", argv[2], argv[1][1]); zfd = BZ2_bzopen(dst, mode); if(zfd == NULL) { ds_printf("DS_ERROR: Can't create file: %s\n", dst); return CMD_ERROR; } fd = fs_open(argv[2], O_RDONLY); if(fd < 0) { ds_printf("DS_ERROR: Can't open file: %s\n", argv[2]); BZ2_bzclose(zfd); return CMD_ERROR; } while((len = fs_read(fd, buff, sizeof(buff))) > 0) { if(!BZ2_bzwrite(zfd, buff, len)) { ds_printf("DS_ERROR: Error writing to file: %s\n", dst); BZ2_bzclose(zfd); fs_close(fd); return CMD_ERROR; } } BZ2_bzclose(zfd); fs_close(fd); ds_printf("DS_OK: File compressed."); } else { return CMD_NO_ARG; } return CMD_OK; } <file_sep>/modules/zip/module.c /* DreamShell ##version## module.c - zip module Copyright (C)2009-2014 SWAT */ #include "ds.h" DEFAULT_MODULE_HEADER(zip); int builtin_zip_cmd(int argc, char *argv[]); int builtin_unzip_cmd(int argc, char *argv[]); int lib_open(klibrary_t *lib) { AddCmd(lib_get_name(), "zip archiver", (CmdHandler *) builtin_zip_cmd); AddCmd("unzip", "unzip archives", (CmdHandler *) builtin_unzip_cmd); return nmmgr_handler_add(&ds_zip_hnd.nmmgr); } int lib_close(klibrary_t *lib) { RemoveCmd(GetCmdByName(lib_get_name())); RemoveCmd(GetCmdByName("unzip")); return nmmgr_handler_remove(&ds_zip_hnd.nmmgr); } <file_sep>/modules/luaTask/src/syncos.c /* ** $Id: syncos.c 10 2007-09-15 19:37:27Z danielq $ ** Os Abstraction: Implementation ** SoongSoft, Argentina ** http://www.soongsoft.com mailto:<EMAIL> ** Copyright (C) 2003-2006 <NAME>. All rights reserved. */ #ifdef _WIN32 #include <winsock2.h> #include <process.h> #else #define TRUE 1 #define FALSE 0 #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #ifndef _WIN32 #include <sys/types.h> #include <unistd.h> #endif #ifdef _WIN32 #include <io.h> #include <direct.h> #ifndef NATV_WIN32 #include <pthread.h> #endif #else #include <errno.h> #include <pthread.h> #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <signal.h> //#include <sys/un.h> #include <netinet/in.h> #endif #include "syncos.h" #include <fcntl.h> long OsCreateThread( OS_THREAD_T *th, OS_THREAD threadfunc, void *param) { #ifdef NATV_WIN32 unsigned tid; *th = _beginthreadex( NULL, 0, threadfunc, param, 0, &tid); return( th == NULL ? -1 : 0); #else pthread_attr_t attr; int status; pthread_attr_init( &attr); pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED); #ifdef LUATASK_PTHREAD_STACK_SIZE pthread_attr_setstacksize( &attr, LUATASK_PTHREAD_STACK_SIZE ); #endif status = pthread_create( th, &attr, threadfunc, param); pthread_attr_destroy( &attr); return( status); #endif } long OsCancelThread( OS_THREAD_T th) { #ifdef NATV_WIN32 /* Not supported */ return( -1); #else return( pthread_cancel( th)); #endif } //long OsCreateEvent( char *name ) { //#ifdef _WIN32 // HANDLE eh; // // eh = CreateEvent( NULL, TRUE, FALSE, name); // // return( ( long) eh); //#else // int *pfd; // pfd = calloc( sizeof( int), 2); // if( pfd != NULL) { // if( pipe( pfd)) { // free( pfd); // pfd = NULL; // } // } // return( ( long) pfd); //#endif //} // //long OsSetEvent( long evt) { //#ifdef _WIN32 // return( SetEvent( ( HANDLE) evt) ? 0 : -1); //#else // return( write( ( ( int *) evt)[1], "", 1)); //#endif //} // //void OsCloseEvent( long evt) { //#ifdef _WIN32 // CloseHandle( ( HANDLE) evt); //#else // close( ( ( int *) evt)[0]); // close( ( ( int *) evt)[1]); // free( ( ( int *) evt)); //#endif //} void * OsCreateMutex( char *name) { #ifdef _WIN32 HANDLE mh; mh = CreateMutex( NULL, FALSE, name); return( ( void *) mh); #else pthread_mutex_t * mtx = malloc( sizeof( pthread_mutex_t)); if( mtx == NULL) { return( NULL); } pthread_mutex_init( mtx, NULL); return( mtx); #endif } long OsLockMutex( void *mtx, long timeout) { #ifdef _WIN32 return( WaitForSingleObject( ( HANDLE) mtx, timeout) == WAIT_OBJECT_0 ? 0 : -1); #else int status; pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, NULL); status = pthread_mutex_lock( ( pthread_mutex_t *) mtx); return( status == 0 ? 0 : -1); #endif } long OsUnlockMutex( void * mtx) { #ifdef _WIN32 return( ReleaseMutex( ( HANDLE) mtx) ? 0 : -1); #else int status; status = pthread_mutex_unlock( ( pthread_mutex_t *) mtx); pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, NULL); return( status == 0 ? 0 : -1); #endif } void OsCloseMutex( void * mtx) { #ifdef _WIN32 CloseHandle( ( HANDLE) mtx); #else int status; status = pthread_mutex_destroy( ( pthread_mutex_t *) mtx); if ( status != 0) { return; } free( mtx); #endif } long OsCreateThreadDataKey() { #ifdef _WIN32 long tdk = ( long) TlsAlloc(); return( tdk == TLS_OUT_OF_INDEXES ? -1 : tdk); #else pthread_key_t tdk; return( pthread_key_create( &tdk, NULL) ? -1 : ( long) tdk); #endif } void OsSetThreadData( long key, const void *tdata) { #ifdef _WIN32 TlsSetValue( ( DWORD) key, ( void *) tdata); #else pthread_setspecific( ( pthread_key_t) key, tdata); #endif } void *OsGetThreadData( long key) { #ifdef _WIN32 return( TlsGetValue( ( DWORD) key)); #else return( pthread_getspecific( ( pthread_key_t) key)); #endif } void OsSleep( long ms) { thd_sleep(ms); /* #ifdef _WIN32 Sleep( ms); #else struct timespec req, rem; req.tv_sec = ms / 1000L; req.tv_nsec = ms % 1000L; req.tv_nsec *= 1000000L; nanosleep( &req, &rem); #endif */ } <file_sep>/firmware/isoldr/loader/kos/dc/scif.h /* KallistiOS ##version## dc/scif.h Copyright (C)2000,2001,2004 <NAME> */ #ifndef __DC_SCIF_H #define __DC_SCIF_H #include <sys/cdefs.h> __BEGIN_DECLS #include <arch/types.h> /* Set serial parameters; this is not platform independent like I want it to be, but it should be generic enough to be useful. */ void scif_set_parameters(int baud, int fifo); // The rest of these are the standard dbgio interface. int scif_set_irq_usage(int on); int scif_detected(); int scif_init(); int scif_shutdown(); int scif_read(); int scif_write(int c); int scif_flush(); int scif_write_buffer(const uint8 *data, int len, int xlat); int scif_read_buffer(uint8 *data, int len); __END_DECLS #endif /* __DC_SCIF_H */ <file_sep>/modules/ogg/liboggvorbis/liboggvorbis/libogg/src/Makefile # KallistiOS Ogg/Vorbis Decoder Library # # Library Makefile # (c)2001 <NAME> # Based on KOS Makefiles by <NAME> OBJS = framing.o bitwise.o KOS_INCS += -I. -I../include -DLITTLE_ENDIAN=1 CFLAGS += -O2 all: libogg-local.a libogg-local.a: $(OBJS) $(KOS_AR) rcs libogg-local.a $(OBJS) cp $(OBJS) ../build cp libogg-local.a ../build clean: -rm -f $(OBJS) *.a -rm -f ../build/*.o *.a include $(KOS_BASE)/Makefile.rules <file_sep>/lib/SDL_gui/Window.cc // Modified by SWAT // http://www.dc-swat.net.ru #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_Window::GUI_Window(const char *aname, GUI_Window *p, int x, int y, int w, int h) : GUI_Object(aname), area(x,y,w,h), parent(p) { // parent is a borrowed reference. do not incref or decref } GUI_Window::~GUI_Window(void) { } void GUI_Window::UpdateAll(void) { if (parent) parent->Update(area); } void GUI_Window::Update(const GUI_Rect &r) { if (parent) parent->Update(r.Adjust(area.x, area.y)); } GUI_Window *GUI_Window::CreateWindow(const char *aname, int x, int y, int w, int h) { return new GUI_Window(aname, this, x, y, w, h); } void GUI_Window::DrawImage(const GUI_Surface *image, const GUI_Rect &src_r, const GUI_Rect &dst_r) { if (parent) parent->DrawImage(image, src_r, dst_r.Adjust(area.x, area.y)); } void GUI_Window::DrawRect(const GUI_Rect &r, const GUI_Color &c) { if (parent) parent->DrawRect(r.Adjust(area.x, area.y), c); } void GUI_Window::DrawLine(int x1, int y1, int x2, int y2, const GUI_Color &c) { if (parent) parent->DrawLine(x1+area.x, y1+area.y, x2+area.x, y2+area.y, c); } void GUI_Window::DrawPixel(int x, int y, const GUI_Color &c) { if (parent) parent->DrawPixel(x+area.x, y+area.y, c); } void GUI_Window::FillRect(const GUI_Rect &r, const GUI_Color &c) { if (parent) parent->FillRect(r.Adjust(area.x, area.y), c); } extern "C" { GUI_Window *CreateWindow(const char *aname, int x, int y, int w, int h) { GUI_Window *win = NULL; return new GUI_Window(aname, win, x, y, w, h); } void GUI_WindowUpdateAll(GUI_Window *win) { win->UpdateAll(); } void GUI_WindowUpdate(GUI_Window *win, const GUI_Rect *r) { win->Update(*r); } void GUI_WindowDrawImage(GUI_Window *win, const GUI_Surface *image, const GUI_Rect *src_r, const GUI_Rect *dst_r) { win->DrawImage(image, *src_r, *dst_r); } void GUI_WindowDrawRect(GUI_Window *win, const GUI_Rect *r, const GUI_Color *c) { win->DrawRect(*r, *c); } void GUI_WindowDrawLine(GUI_Window *win, int x1, int y1, int x2, int y2, const GUI_Color *c) { win->DrawLine(x1, y1, x2, y2, *c); } void GUI_WindowDrawPixel(GUI_Window *win, int x, int y, const GUI_Color *c) { win->DrawPixel(x, y, *c); } void GUI_WindowFillRect(GUI_Window *win, const GUI_Rect *r, const GUI_Color *c) { win->FillRect(*r, *c); } } <file_sep>/modules/minilzo/module.c /* DreamShell ##version## module.c - minilzo module Copyright (C)2011-2015 SWAT */ #include "ds.h" #include "minilzo.h" DEFAULT_MODULE_EXPORTS(minilzo); <file_sep>/sdk/bin/src/ciso/ciso.c /* This file is part of Ciso. Ciso is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Ciso is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Copyright 2005 BOOSTER Copyright 2011-2013 SWAT */ /**************************************************************************** Dependencies ****************************************************************************/ #include <stdio.h> #include <stdlib.h> // abort #include <string.h> // printf #include <assert.h> #include <memory.h> #include <zlib.h> #include <zconf.h> #include <lzo/lzo1x.h> #include "ciso.h" /**************************************************************************** Macros ****************************************************************************/ #define END(...) { \ fprintf(stderr, "" __VA_ARGS__); \ fprintf(stderr, " \n"); \ abort(); \ } /**************************************************************************** Utilities ****************************************************************************/ /* This function is necessarily successful if it returns */ static FILE* fopen_orDie(const char* fname, const char* mode) { FILE* const f = fopen(fname, mode); if (f==NULL) END("can't open '%s' with mode '%s'", fname, mode); return f; } /* This function is necessarily successful if it returns */ static size_t fread_orDie(void* buf, size_t eltSize, size_t nbElts, FILE* f) { size_t const nbEltsRead = fread(buf, eltSize, nbElts, f); if (nbEltsRead != nbElts) END("error reading data"); return nbEltsRead; } /* This function is necessarily successful if it returns */ static size_t fwrite_orDie(const void* buf, size_t eltSize, size_t nbElts, FILE* f) { size_t const nbEltsWritten = fwrite(buf, eltSize, nbElts, f); if (nbEltsWritten != nbElts) END("error writing data"); return nbEltsWritten; } /* This function is necessarily successful if it returns */ static void fseek_orDie(FILE* f, long int offset, int whence) { int const res = fseek(f, offset, whence); if (res != 0) END("error seeking into file"); } /**************************************************************************** decompress CSO to ISO ****************************************************************************/ static void decomp_ciso(const char* fname_out, const char* fname_in) { FILE* const fin = fopen_orDie(fname_in, "rb"); FILE* const fout = fopen_orDie(fname_out, "wb"); CISO_H ciso; z_stream z; int ciso_total_block; uint32_t *index_buf; unsigned char *block_buf1; unsigned char *block_buf2; /* read header */ fread_orDie(&ciso, 1, sizeof(ciso), fin); /* check header */ if ( (ciso.magic[0] != 'Z' && ciso.magic[0] != 'C') || ciso.magic[1] != 'I' || ciso.magic[2] != 'S' || ciso.magic[3] != 'O' || ciso.block_size == 0 || ciso.total_bytes == 0 ) { END("ciso file format error"); } { uint64_t const ctb64 = ciso.total_bytes / ciso.block_size; assert(ctb64 < INT_MAX); ciso_total_block = (int)ctb64; } /* allocate index block */ { size_t const index_size = (size_t)(ciso_total_block + 1 ) * sizeof(uint32_t); index_buf = malloc(index_size); block_buf1 = malloc(ciso.block_size*2); block_buf2 = malloc(ciso.block_size*2); if( !index_buf || !block_buf1 || !block_buf2 ) END("Can't allocate memory %d and %d x2", (int)index_size, (int)ciso.block_size*2); /* read index block */ fread_orDie(index_buf, 1, index_size, fin); } /* show info */ printf("Decompress '%s' to '%s' \n", fname_in, fname_out); printf("Total File Size %ld bytes\n", (long)ciso.total_bytes); printf("block size %d bytes\n", (int)ciso.block_size); printf("total blocks %d blocks\n", ciso_total_block); printf("index align %d\n", 1<<ciso.align); printf("type %s\n", ciso.magic[0] == 'Z' ? "ZISO" : "CISO"); if(ciso.magic[0] == 'Z') { if(lzo_init() != LZO_E_OK) END("lzo_init() failed"); } else { /* init zlib */ z.zalloc = Z_NULL; z.zfree = Z_NULL; z.opaque = Z_NULL; } /* decompress data */ { int percent_period = ciso_total_block / 100; int percent_cnt = 0; unsigned index, plain; long int read_pos; int block; for(block = 0;block < ciso_total_block ; block++) { size_t read_size; size_t cmp_size; if(--percent_cnt<=0) { percent_cnt = percent_period; printf("decompress %d%%\r",block / percent_period); } if(ciso.magic[0] == 'C') { if (inflateInit2(&z,-15) != Z_OK) END("deflateInit : %s\n", (z.msg) ? z.msg : "???"); } /* check index */ index = index_buf[block]; plain = index & 0x80000000; index &= 0x7fffffff; assert((LONG_MAX >> ciso.align) > index); // check overflow read_pos = index << (ciso.align); if(plain) { read_size = ciso.block_size; } else { unsigned int const index2 = index_buf[block+1] & 0x7fffffff; read_size = (index2-index) << (ciso.align); } fseek_orDie(fin, read_pos, SEEK_SET); z.avail_in = (uInt)fread_orDie(block_buf2, 1, read_size , fin); if(z.avail_in != read_size) END("block=%d : read error", block); if(plain) { memcpy(block_buf1,block_buf2,read_size); cmp_size = read_size; } else { if(ciso.magic[0] == 'Z') { unsigned long lzolen; int const status = lzo1x_decompress(block_buf2, z.avail_in, block_buf1, &lzolen, NULL); cmp_size = lzolen; z.avail_out = ciso.block_size; if(status != LZO_E_OK) END("block %d:lzo1x_decompress: %d", block, status); } else { int status; z.next_out = block_buf1; z.avail_out = ciso.block_size; z.next_in = block_buf2; status = inflate(&z, Z_FULL_FLUSH); if (status != Z_STREAM_END) END("block %d:inflate : %s[%d]", block,(z.msg) ? z.msg : "error", status); cmp_size = ciso.block_size - z.avail_out; } if (cmp_size != ciso.block_size) END("block %d : block size error %d != %d", block, (int)cmp_size, (int)ciso.block_size); } /* write decompressed block */ fwrite_orDie(block_buf1, 1,cmp_size , fout); if(ciso.magic[0] == 'C') { /* term zlib */ if (inflateEnd(&z) != Z_OK) END("inflateEnd : %s\n", (z.msg) ? z.msg : "error"); } } } printf("ciso decompress completed\n"); /* clean out */ free(index_buf); free(block_buf1); free(block_buf2); fclose(fin); fclose(fout); } /**************************************************************************** compress ISO ****************************************************************************/ /* if this function returns, it's necessary successful */ static CISO_H init_ciso_header(FILE* fp, int is_ziso) { CISO_H ciso; long int pos; fseek_orDie(fp, 0, SEEK_END); pos = ftell(fp); if (pos==-1L) END("Cannot determine file size; terminating ... \n"); /* init ciso header */ memset(&ciso, 0, sizeof(ciso)); if(is_ziso) { ciso.magic[0] = 'Z'; } else { ciso.magic[0] = 'C'; } ciso.magic[1] = 'I'; ciso.magic[2] = 'S'; ciso.magic[3] = 'O'; ciso.ver = 0x01; ciso.block_size = 0x800; /* ISO9660 one of sector */ assert(pos > 0); ciso.total_bytes = (uint64_t)pos; #if 0 /* align >0 has bug */ for(ciso.align = 0 ; (ciso.total_bytes >> ciso.align) >0x80000000LL ; ciso.align++); #endif fseek_orDie(fp,0,SEEK_SET); return ciso; } static void comp_ciso(int level, int is_ziso, int no_comp_diff, const char* fname_out, const char* fname_in) { FILE* const fin = fopen_orDie(fname_in, "rb"); FILE* const fout = fopen_orDie(fname_out, "wb"); unsigned long long write_pos; int block; unsigned char buf4[64] = {0}; int cmp_size; int percent_period; int percent_cnt; int align_b, align_m; z_stream z; lzo_voidp wrkmem = NULL; CISO_H ciso = init_ciso_header(fin, is_ziso); int const ciso_total_block = (int)(ciso.total_bytes / ciso.block_size); /* allocate index block */ size_t const index_size = (size_t)(ciso_total_block + 1 ) * sizeof(uint32_t); uint32_t* const index_buf = calloc(1, index_size); unsigned char* const block_buf1 = malloc(ciso.block_size*2); unsigned char* const block_buf2 = malloc(ciso.block_size*2); if( !index_buf || !block_buf1 || !block_buf2 ) END("Can't allocate memory\n"); if(is_ziso) { if(lzo_init() != LZO_E_OK) END("lzo_init() failed\n"); //wrkmem = (lzo_voidp) malloc(LZO1X_1_MEM_COMPRESS); wrkmem = (lzo_voidp) malloc(LZO1X_999_MEM_COMPRESS); if (wrkmem==NULL) END("memory allocation error"); } else { /* init zlib */ z.zalloc = Z_NULL; z.zfree = Z_NULL; z.opaque = Z_NULL; } /* show info */ printf("Compress '%s' to '%s' \n", fname_in, fname_out); printf("Total File Size %ld bytes\n", (long)ciso.total_bytes); printf("block size %d bytes\n", (int)ciso.block_size); printf("index align %d\n", 1<<ciso.align); printf("compress level %d\n", level); printf("type %s\n", is_ziso ? "ZISO" : "CISO"); /* write header block */ fwrite_orDie(&ciso, 1, sizeof(ciso), fout); /* skip index block */ assert(index_size < LONG_MAX); fseek_orDie(fout, (long int)index_size, SEEK_CUR); write_pos = sizeof(ciso) + index_size; /* compress data */ percent_period = ciso_total_block/100; percent_cnt = ciso_total_block/100; align_b = 1 << ciso.align; align_m = align_b - 1; for(block = 0;block < ciso_total_block ; block++) { if(--percent_cnt<=0) { percent_cnt = percent_period; printf("compress %3d%% avarage rate %3d%%\r", block / percent_period, (block==0) ? 0 : (int)(100*write_pos/((unsigned long long)block*0x800)) ); } if(!is_ziso) { if (deflateInit2(&z, level , Z_DEFLATED, -15,8,Z_DEFAULT_STRATEGY) != Z_OK) END("deflateInit : %s\n", (z.msg) ? z.msg : "???"); } /* write align */ { int align = (int)write_pos & align_m; if (align) { align = align_b - align; assert(align >= 0); fwrite_orDie(buf4, 1, (size_t)align, fout); write_pos = write_pos + (unsigned long long)align; } } /* mark offset index */ index_buf[block] = (uint32_t)(write_pos >> ciso.align); /* read buffer */ z.next_out = block_buf2; z.avail_out = ciso.block_size*2; z.next_in = block_buf1; z.avail_in = (uInt)fread_orDie(block_buf1, 1, ciso.block_size , fin); if(is_ziso) { unsigned long lzolen; //status = lzo1x_1_compress(block_buf1, z.avail_in, block_buf2, &lzolen, wrkmem); int const status = lzo1x_999_compress(block_buf1, z.avail_in, block_buf2, &lzolen, wrkmem); //printf("in: %d out: %d\n", z.avail_in, lzolen); if (status != LZO_E_OK) END("compression failed: lzo1x_1_compress: %d\n", status); assert(lzolen < INT_MAX); cmp_size = (int)lzolen; } else { /* compress block */ int const status = deflate(&z, Z_FINISH); if (status != Z_STREAM_END) END("block %d:deflate : %s[%d]\n", block,(z.msg) ? z.msg : "error", status); cmp_size = (int)(ciso.block_size*2 - z.avail_out); } /* choise plain / compress */ if (cmp_size >= ((int)ciso.block_size - no_comp_diff)) { cmp_size = (int)ciso.block_size; memcpy(block_buf2, block_buf1, (size_t)cmp_size); /* plain block mark */ index_buf[block] |= 0x80000000; } /* write compressed block */ fwrite_orDie(block_buf2, 1, (size_t)cmp_size, fout); /* mark next index */ write_pos = write_pos + (unsigned long long)cmp_size; if(!is_ziso) { /* term zlib */ if (deflateEnd(&z) != Z_OK) END("deflateEnd : %s\n", (z.msg) ? z.msg : "error"); } } /* last position (total size)*/ index_buf[block] = (uint32_t)(write_pos >> ciso.align); /* write index block */ fseek_orDie(fout, sizeof(ciso), SEEK_SET); fwrite_orDie(index_buf, 1, index_size, fout); printf("ciso compression completed ; total size = %8d bytes , rate %d%% \n", (int)write_pos, (int)(write_pos*100/ciso.total_bytes)); /* clean out */ free(index_buf); free(block_buf1); free(block_buf2); fclose(fin); fclose(fout); } /**************************************************************************** command line ****************************************************************************/ int main(int argc, char *argv[]) { int level; int no_comp_diff = 48; /* minimym gain required per block */ printf("ISO9660 comp/dec to/from CISO/ZISO v1.1 by SWAT \n"); if (argc < 5) { printf("Usage: %s library level infile outfile [no_comp_diff_bytes]\n", argv[0]); printf(" level: 1-9 for compress (1=fast/large - 9=small/slow), 0 for decompress\n"); printf(" library: zlib or lzo\n\n"); return 0; } level = argv[2][0] - '0'; if(level < 0 || level > 9) { printf("Unknown mode: %c\n", argv[2][0]); return 1; } if(argc > 5) { no_comp_diff = atoi(argv[5]); } { const char* const fname_in = argv[3]; const char* const fname_out = argv[4]; int const is_ziso = !strcmp("lzo", argv[1]); if(level==0) decomp_ciso(fname_out, fname_in); else comp_ciso(level, is_ziso, no_comp_diff, fname_out, fname_in); } return 0; } <file_sep>/src/fs/fat/utils.c // $$$ : utils.c -- #include "ff_utils.h" #include <drivers/rtc.h> #define S_P_MIN 60L #define S_P_HOUR (60L * S_P_MIN) #define S_P_DAY (24L * S_P_HOUR) #define S_P_YEAR (365L * S_P_DAY) #define JAPAN_ADJ (-9L * S_P_HOUR) struct _time_block *conv_gmtime(uint32 t) { static int day_p_m[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int day, mon, yr, cumday; static struct _time_block tm; tm.sec = t % 60L; t /= 60L; tm.min = t % 60L; t /= 60L; tm.hour = t % 24L; day = t / 24L; yr = 1950; cumday = 0; while ((cumday += (yr % 4 ? 365 : 366)) <= day) yr++; tm.year = yr; cumday -= yr % 4 ? 365 : 366; day -= cumday; cumday = 0; mon = 0; day_p_m[1] = (yr % 4) == 0 ? 29 : 28; while ((cumday += day_p_m[mon]) <= day) mon++; cumday -= day_p_m[mon]; day -= cumday; tm.day = day + 1; tm.mon = mon + 1; return &tm; } DWORD get_fattime() { struct timeval tv; struct _time_block *tm; DWORD tmr; rtc_gettimeofday(&tv); tm = conv_gmtime(tv.tv_sec); tmr = (((DWORD)tm->year - 60) << 25) | ((DWORD)tm->mon << 21) | ((DWORD)tm->day << 16) | (WORD)(tm->hour << 11) | (WORD)(tm->min << 5) | (WORD)(tm->sec >> 1); return tmr; } <file_sep>/firmware/isoldr/loader/kos/arch/types.h /* KallistiOS ##version## arch/dreamcast/include/types.h (c)2000-2001 <NAME> $Id: types.h,v 1.2 2002/01/05 07:33:50 bardtx Exp $ */ #ifndef __ARCH_TYPES_H #define __ARCH_TYPES_H #include <sys/cdefs.h> __BEGIN_DECLS #include <stddef.h> /* Generic types */ typedef unsigned long long uint64; typedef unsigned long uint32; typedef unsigned short uint16; typedef unsigned char uint8; typedef long long int64; typedef long int32; typedef short int16; typedef char int8; /* Volatile types */ typedef volatile uint64 vuint64; typedef volatile uint32 vuint32; typedef volatile uint16 vuint16; typedef volatile uint8 vuint8; typedef volatile int64 vint64; typedef volatile int32 vint32; typedef volatile int16 vint16; typedef volatile int8 vint8; /* Pointer arithmetic types */ typedef uint32 ptr_t; /* another format for type names */ #define __u_char_defined #define __u_short_defined #define __u_int_defined #define __u_long_defined #define __ushort_defined #define __uint_defined typedef unsigned char u_char; typedef unsigned short u_short; typedef unsigned int u_int; typedef unsigned long u_long; typedef unsigned short ushort; typedef unsigned int uint; /* File-specific types */ //typedef size_t ssize_t; //typedef size_t off_t; /* This type may be used for any generic handle type that is allowed to be negative (for errors) and has no specific bit count restraints. */ typedef int handle_t; typedef handle_t file_t; /* Thread and priority types */ typedef handle_t tid_t; typedef handle_t prio_t; __END_DECLS #endif /* __ARCH_TYPES_H */ <file_sep>/modules/aicaos/aica_registers.h #ifndef AICA_REGISTERS_H #define AICA_REGISTERS_H #define REG_BUS_REQUEST 0x00802808 #define REG_ARM_INT_ENABLE 0x0080289c #define REG_ARM_INT_SEND 0x008028a0 #define REG_ARM_INT_RESET 0x008028a4 #define REG_ARM_FIQ_BIT_0 0x008028a8 #define REG_ARM_FIQ_BIT_1 0x008028ac #define REG_ARM_FIQ_BIT_2 0x008028b0 #define REG_SH4_INT_ENABLE 0x008028b4 #define REG_SH4_INT_SEND 0x008028b8 #define REG_SH4_INT_RESET 0x008028bc #define REG_ARM_FIQ_CODE 0x00802d00 #define REG_ARM_FIQ_ACK 0x00802d04 /* That value is required on several registers */ #define MAGIC_CODE 0x20 /* Interruption codes */ #define TIMER_INTERRUPT_INT_CODE 2 #define BUS_REQUEST_INT_CODE 5 #define SH4_INTERRUPT_INT_CODE 6 #define AICA_FROM_SH4(x) ((x) + 0x9ff00000) #endif <file_sep>/commands/scramble/main.c #include "ds.h" void scramble(char *src, char *dst); void descramble(char *src, char *dst); int main(int argc, char *argv[]) { if(argc < 3) { ds_printf("Usage: %s -flag infile outfile\n"); ds_printf("Flags: \n" "-s -Scramble bin file\n" "-d -Descramble bin file\n\n", argv[0]); ds_printf("Example: %s -d /cd/1ST_READ.BIN /ram/unscramble.bin\n", argv[0]); return CMD_NO_ARG; } if(!strncasecmp(argv[1], "-s", 2)) { ds_printf("DS_PROCESS: Scrambling...\n"); scramble(argv[2], argv[3]); ds_printf("DS_OK: Complete.\n"); } else if(!strncasecmp(argv[1], "-d", 2)) { ds_printf("DS_PROCESS: Descrambling...\n"); descramble(argv[2], argv[3]); ds_printf("DS_OK: Complete.\n"); } else { ds_printf("DS_ERROR: Uknown flag - '%s'\n", argv[1]); } return CMD_OK; } <file_sep>/modules/ffmpeg/oggvorbis.c /** * @file oggvorbis.c * Ogg Vorbis codec support via libvorbisenc. * @author <NAME> and SWAT */ #include "libavcodec/avcodec.h" #include "libavformat/avformat.h" #include <ogg/ogg.h> #include <vorbis/codec.h> #define OGGVORBIS_FRAME_SIZE 1024 typedef struct OggVorbisContext { vorbis_info vi; vorbis_dsp_state vd; vorbis_block vb; /* decoder */ vorbis_comment vc; } OggVorbisContext; static int oggvorbis_decode_init(AVCodecContext *avccontext) { OggVorbisContext *context = avccontext->priv_data; vorbis_info_init(&context->vi); vorbis_comment_init(&context->vc); return 0; } static inline int conv(int samples, float **pcm, char *buf, int channels) { int i, j, val; ogg_int16_t *ptr, *data = (ogg_int16_t*)buf; float *mono; for(i = 0 ; i < channels ; i++){ ptr = &data[i]; mono = pcm[i]; for(j = 0 ; j < samples ; j++) { val = mono[j] * 32767.f; if(val > 32767) val = 32767; if(val < -32768) val = -32768; *ptr = val; ptr += channels; } } return 0; } static int oggvorbis_decode_frame(AVCodecContext * avccontext, void *data, int *data_size, AVPacket *avpkt) { OggVorbisContext *context = avccontext->priv_data; ogg_packet *op = (ogg_packet*)avpkt->data; float **pcm; int samples, total_samples, total_bytes; op->packet = (uint8*)op + sizeof(ogg_packet) ; /* correct data pointer */ if(op->packetno < 3) { vorbis_synthesis_headerin(&context->vi, &context->vc, op); return avpkt->size; } if(op->packetno == 3) { // printf("vorbis_decode: %d channel, %ldHz, encoder `%s'\n", // context->vi.channels, context->vi.rate, context->vc.vendor); avccontext->channels = context->vi.channels; avccontext->sample_rate = context->vi.rate; vorbis_synthesis_init(&context->vd, &context->vi); vorbis_block_init(&context->vd, &context->vb); } if(vorbis_synthesis(&context->vb, op) == 0) vorbis_synthesis_blockin(&context->vd, &context->vb); total_samples = 0; total_bytes = 0; while((samples = vorbis_synthesis_pcmout(&context->vd, &pcm)) > 0) { conv(samples, pcm, (char*)data + total_bytes, context->vi.channels); total_bytes += samples * 2 * context->vi.channels; total_samples += samples; vorbis_synthesis_read(&context->vd, samples); } *data_size = total_bytes; return avpkt->size; } static int oggvorbis_decode_close(AVCodecContext *avccontext) { OggVorbisContext *context = avccontext->priv_data; vorbis_info_clear(&context->vi); vorbis_comment_clear(&context->vc); return 0; } AVCodec vorbis_decoder = { "vorbis", AVMEDIA_TYPE_AUDIO, CODEC_ID_VORBIS, sizeof(OggVorbisContext), oggvorbis_decode_init, NULL, oggvorbis_decode_close, oggvorbis_decode_frame, CODEC_CAP_PARSE_ONLY, NULL, NULL, NULL, NULL, "Vorbis", }; <file_sep>/modules/aicaos/sh4/aica_syscalls.c #include <alloca.h> #include <kos.h> #include "../aica_syscalls.h" static AICA_SHARED(sh4_open) { char *fn; struct open_param *p = (struct open_param *) in; fn = alloca(p->namelen+1); aica_download(fn, p->name, p->namelen); fn[p->namelen] = '\0'; return open(fn, p->flags, p->mode); } static AICA_SHARED(sh4_close) { return close(*(int *) in); } static AICA_SHARED(sh4_fstat) { int result; struct stat st; struct fstat_param *p = (struct fstat_param *) in; result = fstat(p->file, &st); if (!result) aica_upload(p->st, &st, sizeof(st)); return result; } static AICA_SHARED(sh4_stat) { int result; struct stat st; char *fn; struct stat_param *p = (struct stat_param *) in; fn = alloca(p->namelen+1); aica_download(fn, p->name, p->namelen); fn[p->namelen] = '\0'; result = stat(fn, &st); if (!result) aica_upload(p->st, &st, sizeof(st)); return result; } static AICA_SHARED(sh4_isatty) { return isatty(*(int *) in); } static AICA_SHARED(sh4_link) { struct link_param *p = (struct link_param *) in; char *fn_old, *fn_new; fn_old = alloca(p->namelen_old+1); fn_new = alloca(p->namelen_new+1); aica_download(fn_old, p->old, p->namelen_old); aica_download(fn_new, p->new, p->namelen_new); fn_old[p->namelen_old] = '\0'; fn_new[p->namelen_new] = '\0'; return link(fn_old, fn_new); } static AICA_SHARED(sh4_lseek) { struct lseek_param *p = (struct lseek_param *) in; return lseek(p->file, p->ptr, p->dir); } /* TODO: optimize... */ static AICA_SHARED(sh4_read) { _READ_WRITE_RETURN_TYPE result; struct read_param *p = (struct read_param *) in; void *buf = alloca(p->len); result = read(p->file, buf, p->len); if (result != -1) aica_upload(p->ptr, buf, p->len); return (int) result; } /* TODO: optimize... */ static AICA_SHARED(sh4_write) { _READ_WRITE_RETURN_TYPE result; struct write_param *p = (struct write_param *) in; void *buf = alloca(p->len); aica_download(buf, p->ptr, p->len); result = write(p->file, buf, p->len); return (int) result; } void aica_init_syscalls(void) { AICA_SHARE(sh4_open, sizeof(struct open_param), 0); AICA_SHARE(sh4_close, sizeof(int), 0); AICA_SHARE(sh4_fstat, sizeof(struct fstat_param), 0); AICA_SHARE(sh4_stat, sizeof(struct stat_param), 0); AICA_SHARE(sh4_isatty, sizeof(int), 0); AICA_SHARE(sh4_link, sizeof(struct link_param), 0); AICA_SHARE(sh4_lseek, sizeof(struct lseek_param), 0); AICA_SHARE(sh4_read, sizeof(struct read_param), 0); AICA_SHARE(sh4_write, sizeof(struct write_param), 0); } <file_sep>/firmware/isoldr/loader/main.c /** * DreamShell ISO Loader * (c)2009-2022 SWAT <http://www.dc-swat.ru> */ #include <main.h> #include <arch/timer.h> #include <arch/cache.h> #include <ubc.h> #include <exception.h> #include <maple.h> isoldr_info_t *IsoInfo; uint32 loader_addr = 0; uint32 loader_end = 0; int main(int argc, char *argv[]) { (void)argc; (void)argv; if(is_custom_bios() && is_no_syscalls()) { bfont_saved_addr = 0xa0001000; } IsoInfo = (isoldr_info_t *)LOADER_ADDR; loader_addr = (uint32)IsoInfo; loader_end = loader_addr + loader_size + ISOLDR_PARAMS_SIZE + 32; OpenLog(); printf(NULL); printf("DreamShell ISO from "DEV_NAME" loader v"VERSION"\n"); malloc_init(1); /* Setup BIOS timer */ timer_init(); timer_prime_bios(TMU0); timer_start(TMU0); int emu_all_sc = 0; if (IsoInfo->syscalls == 0) { if(loader_addr < ISOLDR_DEFAULT_ADDR_LOW || (malloc_heap_pos() < ISOLDR_DEFAULT_ADDR_LOW) || (is_custom_bios() && is_no_syscalls())) { emu_all_sc = 1; } enable_syscalls(emu_all_sc); } if(IsoInfo->magic[0] != 'D' || IsoInfo->magic[1] != 'S' || IsoInfo->magic[2] != 'I') { LOGF("Magic is incorrect!\n"); goto error; } #ifndef HAVE_LIMIT if(IsoInfo->gdtex > 0) { draw_gdtex((uint8 *)IsoInfo->gdtex); } #endif LOGF("Magic: %s\n" "LBA: %d (%d)\n" "Sector size: %d\n" "Image type: %d\n", IsoInfo->magic, IsoInfo->track_lba[0], IsoInfo->track_lba[1], IsoInfo->sector_size, IsoInfo->image_type ); LOGF("Boot: %s at %d size %d addr %08lx type %d mode %d\n", IsoInfo->exec.file, IsoInfo->exec.lba, IsoInfo->exec.size, IsoInfo->exec.addr, IsoInfo->exec.type, IsoInfo->boot_mode ); LOGF("Loader: %08lx - %08lx size %d, heap %08lx\n", loader_addr, loader_addr + loader_size, loader_size + ISOLDR_PARAMS_SIZE, malloc_heap_pos() ); printf("Initializing "DEV_NAME"...\n"); if(!InitReader()) { goto error; } if (!IsoInfo->use_dma) { fs_enable_dma(FS_DMA_DISABLED); } printf("Loading executable...\n"); if(!Load_BootBin()) { goto error; } if(IsoInfo->exec.type == BIN_TYPE_KOS) { uint8 *src = (uint8 *)NONCACHED_ADDR(IsoInfo->exec.addr); if(src[1] != 0xD0) { LOGF("Descrambling...\n"); uint32 exec_addr = NONCACHED_ADDR(IsoInfo->exec.addr); uint8 *dest = (uint8 *)(exec_addr + (IsoInfo->exec.size * 3)); descramble(src, dest, IsoInfo->exec.size); memcpy(src, dest, IsoInfo->exec.size); } } #ifndef HAVE_LIMIT if(IsoInfo->boot_mode != BOOT_MODE_DIRECT || (loader_end < IPBIN_ADDR && (IsoInfo->emu_cdda == 0 || IsoInfo->use_irq)) || (loader_addr > APP_ADDR) ) { printf("Loading IP.BIN...\n"); if(!Load_IPBin(IsoInfo->boot_mode == BOOT_MODE_DIRECT)) { goto error; } } #endif if(IsoInfo->exec.type != BIN_TYPE_KOS) { /* Patch GDC driver entry */ gdc_syscall_patch(); } #ifdef HAVE_EXPT if(IsoInfo->exec.type == BIN_TYPE_WINCE && IsoInfo->use_irq) { uint32 exec_addr = CACHED_ADDR(IsoInfo->exec.addr); uint8 wince_version = *((uint8 *)NONCACHED_ADDR(IsoInfo->exec.addr + 0x0c)); /* Check WinCE version and hack VBR before executing */ if(wince_version == 0xe0) { exception_init(exec_addr + 0x2110); } else { exception_init(exec_addr + 0x20f0); } } #endif #ifdef HAVE_EXT_SYSCALLS if(IsoInfo->syscalls) { printf("Loading syscalls...\n"); Load_Syscalls(); } #endif #ifdef HAVE_CDDA if(IsoInfo->emu_cdda) { CDDA_Init(); } #endif #ifdef HAVE_MAPLE if(IsoInfo->emu_vmu) { maple_init_vmu(IsoInfo->emu_vmu); } #endif setup_machine(); #ifndef HAVE_LIMIT if(IsoInfo->boot_mode == BOOT_MODE_DIRECT) { printf("Executing...\n"); launch(NONCACHED_ADDR(IsoInfo->exec.addr)); } else { printf("Executing from IP.BIN...\n"); launch(0xac00e000); } error: printf("Failed!\n"); timer_spin_sleep_bios(3000); Load_DS(); launch(NONCACHED_ADDR(IsoInfo->exec.addr)); *(vuint32 *)0xA05F6890 = 0x7611; #else printf("Executing...\n"); launch(NONCACHED_ADDR(IsoInfo->exec.addr)); error: printf("Failed!\n"); *(vuint32 *)0xA05F6890 = 0x7611; do {} while (1); #endif /* HAVE_LIMIT */ return -1; } <file_sep>/applications/bios_flasher/modules/app_module.h /* DreamShell ##version## app_module.h - Bios flasher app module header Copyright (C)2013 Yev Copyright (C)2013-2023 SWAT */ #include "ds.h" void BiosFlasher_OnLeftScrollPressed(GUI_Widget *widget); void BiosFlasher_OnRightScrollPressed(GUI_Widget *widget); void BiosFlasher_ItemClick(dirent_fm_t *fm_ent); void BiosFlasher_OnWritePressed(GUI_Widget *widget); void BiosFlasher_OnReadPressed(GUI_Widget *widget); void BiosFlasher_OnComparePressed(GUI_Widget *widget); void BiosFlasher_OnDetectPressed(GUI_Widget *widget); void BiosFlasher_OnBackPressed(GUI_Widget *widget); void BiosFlasher_OnSettingsPressed(GUI_Widget *widget); void BiosFlasher_OnConfirmPressed(GUI_Widget *widget); void BiosFlasher_OnSaveSettingsPressed(GUI_Widget *widget); void BiosFlasher_OnSupportedPressed(GUI_Widget *widget); void BiosFlasher_OnExitPressed(GUI_Widget *widget); void BiosFlasher_Init(App_t* app); <file_sep>/resources/lua/lib/bit/hex.lua --[[--------------- Hex v0.4 ------------------- Hex conversion lib for lua. How to use: hex.to_hex(n) -- convert a number to a hex string hex.to_dec(hex) -- convert a hex string(prefix with '0x' or '0X') to number Part of LuaBit(http://luaforge.net/projects/bit/). Under the MIT license. copyright(c) 2006~2007 hanzhao (<EMAIL>) --]]--------------- require '/cd/lua/lib/bit/bit.lua'; do local function to_hex(n) if(type(n) ~= "number") then error("non-number type passed in.") end -- checking not float if(n - math.floor(n) > 0) then error("trying to apply bitwise operation on non-integer!") end if(n < 0) then -- negative n = bit.tobits(bit.bnot(math.abs(n)) + 1) n = bit.tonumb(n) end hex_tbl = {'A', 'B', 'C', 'D', 'E', 'F'} hex_str = "" while(n ~= 0) do last = math.mod(n, 16) if(last < 10) then hex_str = tostring(last) .. hex_str else hex_str = hex_tbl[last-10+1] .. hex_str end n = math.floor(n/16) end if(hex_str == "") then hex_str = "0" end return "0x" .. hex_str end local function to_dec(hex) if(type(hex) ~= "string") then error("non-string type passed in.") end head = string.sub(hex, 1, 2) if( head ~= "0x" and head ~= "0X") then error("wrong hex format, should lead by 0x or 0X.") end v = tonumber(string.sub(hex, 3), 16) return v; end -------------------- -- hex lib interface hex = { to_dec = to_dec, to_hex = to_hex, } end --[[ -- test d = 4341688 h = to_hex(d) print(h) print(to_dec(h)) for i = 1, 100000 do h = hex.to_hex(i) d = hex.to_dec(h) if(d ~= i) then error("failed " .. i .. ", " .. h) end end --]]<file_sep>/commands/Makefile # # DreamShell commands Makefile # Copyright (C) 2009-2016 SWAT # http://www.dc-swat.ru # _SUBDIRS = bin2iso flashrom netstat ping scramble \ untgz vmu vmode mke2fs gdiopt ciso sip all: $(patsubst %, _dir_%, $(_SUBDIRS)) $(patsubst %, _dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _dir_%, %, $@) clean: $(patsubst %, _clean_dir_%, $(_SUBDIRS)) $(patsubst %, _clean_dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _clean_dir_%, %, $@) clean install: $(patsubst %, _install_dir_%, $(_SUBDIRS)) $(patsubst %, _install_dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _install_dir_%, %, $@) install <file_sep>/commands/netstat/main.c /* DreamShell ##version## netstat.c Copyright (C) 2011-2013 SWAT */ #include "ds.h" int main(int argc, char *argv[]) { net_ipv4_stats_t ip; net_udp_stats_t udp; /* Print out some statistics about the connection. */ ip = net_ipv4_get_stats(); udp = net_udp_get_stats(); ds_printf("IPv4 Stats:\n" "Packets sent successfully: %6d\n" "Packets that failed to send: %6d\n" "Packets received successfully: %6d\n" "Packets rejected (bad size): %6d\n" " (bad checksum): %6d\n" " (bad protocol): %6d\n\n", ip.pkt_sent, ip.pkt_send_failed, ip.pkt_recv, ip.pkt_recv_bad_size, ip.pkt_recv_bad_chksum, ip.pkt_recv_bad_proto); ds_printf("UDP Stats:\n" "Packets sent successfully: %6d\n" "Packets that failed to send: %6d\n" "Packets received successfully: %6d\n" "Packets rejected (bad size): %6d\n" " (bad checksum): %6d\n" " (no socket): %6d\n\n", udp.pkt_sent, udp.pkt_send_failed, udp.pkt_recv, udp.pkt_recv_bad_size, udp.pkt_recv_bad_chksum, udp.pkt_recv_no_sock); return CMD_OK; } <file_sep>/modules/ogg/liboggvorbis/liboggvorbisplay/sndoggvorbis.c /* KallistiOS Ogg/Vorbis Decoder Library * for KOS ##version## * * sndoggvorbis.c * Copyright (C)2001,2002 <NAME> * Copyright (C)2002,2003,2004 <NAME> * * An Ogg/Vorbis player library using sndstream and functions provided by * ivorbisfile (Tremor). */ #include <kos.h> /* #include <sndserver.h> */ #include <assert.h> #include <vorbis/vorbisfile.h> #include "misc.h" /* Enable this #define to do timing testing */ /* #define TIMING_TESTS */ #define BUF_SIZE 65536 /* Size of buffer */ static uint8 pcm_buffer[BUF_SIZE+16384]; /* complete buffer + 16KB safety */ static uint8 *pcm_ptr=pcm_buffer; /* place we write to */ static int32 pcm_count=0; /* bytes in buffer */ static int32 last_read=0; /* number of bytes the sndstream driver grabbed at last callback */ static int tempcounter =0; static snd_stream_hnd_t stream_hnd = SND_STREAM_INVALID; /* liboggvorbis Related Variables */ static OggVorbis_File vf; /* Since we're only providing this library for single-file playback it should * make no difference if we define an info-storage here where the user can * get essential information about his file. */ static VorbisFile_info_t sndoggvorbis_info; /* Thread-state related defines */ #define STATUS_INIT 0 #define STATUS_READY 1 #define STATUS_STARTING 2 #define STATUS_PLAYING 3 #define STATUS_STOPPING 4 #define STATUS_QUIT 5 #define STATUS_ZOMBIE 6 #define STATUS_REINIT 7 #define STATUS_RESTART 8 #define STATUS_LOADING 9 #define STATUS_QUEUEING 10 #define STATUS_QUEUED 11 #define BITRATE_MANUAL -1 /* Library status related variables */ static int sndoggvorbis_queue_enabled; /* wait in STATUS_QUEUED? */ static volatile int sndoggvorbis_loop; /* current looping mode */ static volatile int sndoggvorbis_status; /* current status of thread */ static volatile int sndoggvorbis_bitrateint; /* bitrateinterval in calls */ static semaphore_t *sndoggvorbis_halt_sem; /* semaphore to pause thread */ static char sndoggvorbis_lastfilename[256]; /* filename of last played file */ static int current_section; static int sndoggvorbis_vol = 240; /* Enable/disable queued waiting */ void sndoggvorbis_queue_enable() { sndoggvorbis_queue_enabled = 1; } void sndoggvorbis_queue_disable() { sndoggvorbis_queue_enabled = 0; } /* Wait for the song to be queued */ void sndoggvorbis_queue_wait() { assert(sndoggvorbis_queue_wait); /* Make sure we've loaded ok */ while (sndoggvorbis_status != STATUS_QUEUED) thd_pass(); } /* Queue the song to start if it's in QUEUED */ void sndoggvorbis_queue_go() { /* Make sure we're ready */ sndoggvorbis_queue_wait(); /* Tell it to go */ sndoggvorbis_status = STATUS_STARTING; sem_signal(sndoggvorbis_halt_sem); } /* getter and setter functions for information access */ int sndoggvorbis_isplaying() { if((sndoggvorbis_status == STATUS_PLAYING) || (sndoggvorbis_status == STATUS_STARTING) || (sndoggvorbis_status == STATUS_QUEUEING) || (sndoggvorbis_status == STATUS_QUEUED)) { return(1); } return(0); } void sndoggvorbis_setbitrateinterval(int interval) { sndoggvorbis_bitrateint=interval; /* Just in case we're already counting above interval * reset the counter */ tempcounter = 0; } /* sndoggvorbis_getbitrate() * * returns the actual bitrate of the playing stream. * * NOTE: * The value returned is only actualized every once in a while ! */ long sndoggvorbis_getbitrate() { return(sndoggvorbis_info.actualbitrate); // return(VorbisFile_getBitrateInstant()); } long sndoggvorbis_getposition() { return(sndoggvorbis_info.actualposition); } /* The following getters only return the contents of specific comment * fields. It is thinkable that these return something like "NOT SET" * in case the specified field has not been set ! */ char *sndoggvorbis_getartist() { return(sndoggvorbis_info.artist); } char *sndoggvorbis_gettitle() { return(sndoggvorbis_info.title); } char *sndoggvorbis_getgenre() { return(sndoggvorbis_info.genre); } char *sndoggvorbis_getcommentbyname(const char *commentfield) { dbglog(DBG_ERROR, "sndoggvorbis: getcommentbyname not implemented for tremor yet\n"); return NULL; } static void sndoggvorbis_clear_comments() { sndoggvorbis_info.artist=NULL; sndoggvorbis_info.title=NULL; sndoggvorbis_info.album=NULL; sndoggvorbis_info.tracknumber=NULL; sndoggvorbis_info.organization=NULL; sndoggvorbis_info.description=NULL; sndoggvorbis_info.genre=NULL; sndoggvorbis_info.date=NULL; sndoggvorbis_info.location=NULL; sndoggvorbis_info.copyright=NULL; sndoggvorbis_info.isrc=NULL; sndoggvorbis_info.filename=NULL; sndoggvorbis_info.nominalbitrate=0; sndoggvorbis_info.actualbitrate=0; sndoggvorbis_info.actualposition=0; } /* main functions controlling the thread */ /* sndoggvorbis_wait_start() * * let's the caller wait until the vorbis thread is signalling that it is ready * to decode data */ void sndoggvorbis_wait_start() { while(sndoggvorbis_status != STATUS_READY) thd_pass(); } /* *callback(...) * * this procedure is called by the streaming server when it needs more PCM data * for internal buffering */ static void *callback(snd_stream_hnd_t hnd, int size, int * size_out) { #ifdef TIMING_TESTS int decoded_bytes = 0; uint32 s_s, s_ms, e_s, e_ms; #endif // printf("sndoggvorbis: callback requested %d bytes\n",size); /* Check if the callback requests more data than our buffer can hold */ if (size > BUF_SIZE) size = BUF_SIZE; #ifdef TIMING_TESTS timer_ms_gettime(&s_s, &s_ms); #endif /* Shift the last data the AICA driver took out of the PCM Buffer */ if (last_read > 0) { pcm_count -= last_read; if (pcm_count < 0) pcm_count=0; /* Don't underrun */ /* printf("memcpy(%08x, %08x, %d (%d - %d))\n", pcm_buffer, pcm_buffer+last_read, pcm_count-last_read, pcm_count, last_read); */ memcpy(pcm_buffer, pcm_buffer+last_read, pcm_count); pcm_ptr = pcm_buffer + pcm_count; } /* If our buffer has not enough data to fulfill the callback decode 4 KB * chunks until we have enough PCM samples buffered */ // printf("sndoggvorbis: fill buffer if not enough data\n"); long pcm_decoded = 0; while(pcm_count < size) { //int pcm_decoded = VorbisFile_decodePCMint8(v_headers, pcm_ptr, 4096); pcm_decoded = ov_read(&vf, pcm_ptr, 4096, 0, 2, 1, &current_section); /* Are we at the end of the stream? If so and looping is enabled, then go ahead and seek back to the first. */ if (pcm_decoded == 0 && sndoggvorbis_loop) { /* Seek back */ if (ov_raw_seek(&vf, 0) < 0) { dbglog(DBG_ERROR, "sndoggvorbis: can't ov_raw_seek to the beginning!\n"); } else { /* Try again */ pcm_decoded = ov_read(&vf, pcm_ptr, 4096, 0, 2, 1, &current_section); } } #ifdef TIMING_TESTS decoded_bytes += pcm_decoded; #endif // printf("pcm_decoded is %d\n", pcm_decoded); pcm_count += pcm_decoded; pcm_ptr += pcm_decoded; //if (pcm_decoded == 0 && check_for_reopen() < 0) // break; if (pcm_decoded == 0) break; } if (pcm_count > size) *size_out = size; else *size_out = pcm_count; /* Let the next callback know how many bytes the last callback grabbed */ last_read = *size_out; #ifdef TIMING_TESTS if (decoded_bytes != 0) { int t; timer_ms_gettime(&e_s, &e_ms); t = ((int)e_ms - (int)s_ms) + ((int)e_s - (int)s_s) * 1000; printf("%dms for %d bytes (%.2fms / byte)\n", t, decoded_bytes, t*1.0f/decoded_bytes); } #endif // printf("sndoggvorbis: callback: returning\n"); if (pcm_decoded == 0) return NULL; else return pcm_buffer; } /* sndoggvorbis_thread() * * this function is called by sndoggvorbis_mainloop and handles all the threads * status handling and playing functionality. */ void sndoggvorbis_thread() { int stat; stream_hnd = snd_stream_alloc(NULL, SND_STREAM_BUFFER_MAX); assert( stream_hnd != SND_STREAM_INVALID ); while(sndoggvorbis_status != STATUS_QUIT) { switch(sndoggvorbis_status) { case STATUS_INIT: sndoggvorbis_status= STATUS_READY; break; case STATUS_READY: printf("oggthread: waiting on semaphore\n"); sem_wait(sndoggvorbis_halt_sem); printf("oggthread: released from semaphore (status=%d)\n", sndoggvorbis_status); break; case STATUS_QUEUEING: { vorbis_info * vi = ov_info(&vf, -1); snd_stream_reinit(stream_hnd, callback); snd_stream_queue_enable(stream_hnd); printf("oggthread: stream_init called\n"); snd_stream_start(stream_hnd, vi->rate, vi->channels - 1); snd_stream_volume(stream_hnd, sndoggvorbis_vol); printf("oggthread: stream_start called\n"); if (sndoggvorbis_status != STATUS_STOPPING) sndoggvorbis_status = STATUS_QUEUED; break; } case STATUS_QUEUED: printf("oggthread: queue waiting on semaphore\n"); sem_wait(sndoggvorbis_halt_sem); printf("oggthread: queue released from semaphore\n"); break; case STATUS_STARTING: { vorbis_info * vi = ov_info(&vf, -1); if (sndoggvorbis_queue_enabled) { snd_stream_queue_go(stream_hnd); } else { snd_stream_reinit(stream_hnd, callback); printf("oggthread: stream_init called\n"); snd_stream_start(stream_hnd, vi->rate, vi->channels - 1); printf("oggthread: stream_start called\n"); } snd_stream_volume(stream_hnd, sndoggvorbis_vol); sndoggvorbis_status=STATUS_PLAYING; break; } case STATUS_PLAYING: /* Preliminary Bitrate Code * For our tests the bitrate is being set in the struct once in a * while so that the user can just read out this value from the struct * and use it for whatever purpose */ /* if (tempcounter==sndoggvorbis_bitrateint) { long test; if((test=VorbisFile_getBitrateInstant()) != -1) { sndoggvorbis_info.actualbitrate=test; } tempcounter = 0; } tempcounter++; */ /* Stream Polling and end-of-stream detection */ if ( (stat = snd_stream_poll(stream_hnd)) < 0) { printf("oggthread: stream ended (status %d)\n", stat); printf("oggthread: not restarting\n"); snd_stream_stop(stream_hnd); /* Reset our PCM buffer */ pcm_count = 0; last_read = 0; pcm_ptr = pcm_buffer; /* This can also happen sometimes when you stop the stream manually, so we'll call this here to make sure */ ov_clear(&vf); sndoggvorbis_lastfilename[0] = 0; sndoggvorbis_status = STATUS_READY; sndoggvorbis_clear_comments(); } else { /* Sleep some until the next buffer is needed */ thd_sleep(50); } break; case STATUS_STOPPING: snd_stream_stop(stream_hnd); ov_clear(&vf); /* Reset our PCM buffer */ pcm_count = 0; last_read = 0; pcm_ptr = pcm_buffer; sndoggvorbis_lastfilename[0] = 0; sndoggvorbis_status = STATUS_READY; sndoggvorbis_clear_comments(); break; } } snd_stream_stop(stream_hnd); snd_stream_destroy(stream_hnd); sndoggvorbis_status=STATUS_ZOMBIE; printf("oggthread: thread released\n"); } /* sndoggvorbis_stop() * * function to stop the current playback and set the thread back to * STATUS_READY mode. */ void sndoggvorbis_stop() { if (sndoggvorbis_status != STATUS_PLAYING && sndoggvorbis_status != STATUS_STARTING && sndoggvorbis_status != STATUS_QUEUEING && sndoggvorbis_status != STATUS_QUEUED) { return; } /* Wait for the thread to finish starting */ while (sndoggvorbis_status == STATUS_STARTING) thd_pass(); sndoggvorbis_status = STATUS_STOPPING; /* Wait until thread is at STATUS_READY before giving control * back to the MAIN */ while(sndoggvorbis_status != STATUS_READY) { thd_pass(); } } static char *vc_get_comment(vorbis_comment * vc, const char *commentfield) { int i; int commentlength = strlen(commentfield); for (i=0; i<vc->comments; i++) { if (!(strncmp(commentfield, vc->user_comments[i], commentlength))) { /* Return adress of comment content but leave out the * commentname= part ! */ return vc->user_comments[i] + commentlength + 1; } } return NULL; } /* Same as sndoggvorbis_start, but takes an already-opened file. Once a file is passed into this function, we assume that _we_ own it. */ int sndoggvorbis_start_fd(FILE * fd, int loop) { vorbis_comment *vc; /* If we are already playing or just loading a new file * we can't start another one ! */ if (sndoggvorbis_status != STATUS_READY) { fclose(fd); return -1; } /* Initialize liboggvorbis. Try to open file and grab the headers * from the bitstream */ printf("oggthread: initializing and parsing ogg\n"); if(ov_open(fd, &vf, NULL, 0) < 0) { printf("sndoggvorbis: input does not appear to be an Ogg bitstream\n"); fclose(fd); return -1; } sndoggvorbis_loop = loop; strcpy(sndoggvorbis_lastfilename, "<stream>"); if (sndoggvorbis_queue_enabled) sndoggvorbis_status = STATUS_QUEUEING; else sndoggvorbis_status = STATUS_STARTING; sem_signal(sndoggvorbis_halt_sem); /* Grab all standard comments from the file * (based on v-comment.html found in OggVorbis source packages */ vc = ov_comment(&vf, -1); if (vc == NULL) { dbglog(DBG_WARNING, "sndoggvorbis: can't obtain bitstream comments\n"); sndoggvorbis_clear_comments(); } else { sndoggvorbis_info.artist = vc_get_comment(vc, "artist"); sndoggvorbis_info.title = vc_get_comment(vc, "title"); sndoggvorbis_info.version = vc_get_comment(vc, "version"); sndoggvorbis_info.album = vc_get_comment(vc, "album"); sndoggvorbis_info.tracknumber = vc_get_comment(vc, "tracknumber"); sndoggvorbis_info.organization = vc_get_comment(vc, "organization"); sndoggvorbis_info.description = vc_get_comment(vc, "description"); sndoggvorbis_info.genre = vc_get_comment(vc, "genre"); sndoggvorbis_info.date = vc_get_comment(vc, "date"); sndoggvorbis_info.filename = sndoggvorbis_lastfilename; } return 0; } /* sndoggvorbis_start(...) * * function to start playback of a Ogg/Vorbis file. Expects a filename to * a file in the KOS filesystem. */ int sndoggvorbis_start(const char *filename,int loop) { FILE *f; f = fopen(filename, "rb"); if (!f) { dbglog(DBG_ERROR, "sndoggvorbis: couldn't open source file!\n"); return -1; } return sndoggvorbis_start_fd(f, loop); } /* sndoggvorbis_shutdown() * * function that stops playing and shuts down the player thread. */ void sndoggvorbis_thd_quit() { sndoggvorbis_status = STATUS_QUIT; /* In case player is READY -> tell it to continue */ sem_signal(sndoggvorbis_halt_sem); while (sndoggvorbis_status != STATUS_ZOMBIE) thd_pass(); // snd_stream_stop(); } /* sndoggvorbis_volume(...) * * function to set the volume of the streaming channel */ void sndoggvorbis_volume(int vol) { sndoggvorbis_vol = vol; snd_stream_volume(stream_hnd, vol); } /* sndoggvorbis_mainloop() * * code that runs in our decoding thread. sets up the semaphore. initializes the stream * driver and calls our *real* thread code */ void sndoggvorbis_mainloop() { /* create a semaphore for thread to halt on */ sndoggvorbis_halt_sem = sem_create(0); sndoggvorbis_status = STATUS_INIT; sndoggvorbis_queue_enabled = 0; /* initialize comment field */ sndoggvorbis_clear_comments(); /* sndoggvorbis_setbitrateinterval(1000);*/ /* call the thread code */ sndoggvorbis_thread(); /* destroy the semaphore we first created */ sem_destroy(sndoggvorbis_halt_sem); } <file_sep>/modules/aicaos/aica_common.h #ifndef _AICA_H #define _AICA_H #include <sys/types.h> #include <errno.h> #define SH_TO_ARM 0 #define ARM_TO_SH 1 #define NB_MAX_FUNCTIONS 0x40 #define FUNCNAME_MAX_LENGTH 0x20 #define PRIORITY_MAX 15 /* Default priority for a function call */ #define PRIORITY_DEFAULT 10 /* EAICA error for 'errno'. * It means that the function call did not success. */ #define EAICA 101 #define FUNCTION_CALL_AVAIL 1 #define FUNCTION_CALL_PENDING 2 #define FUNCTION_CALL_DONE 3 typedef int (*aica_funcp_t)(void *, void *); struct function_flow_params { /* Length in bytes of the buffer. */ size_t size; /* Pointer to the buffer. * /!\ Can be inaccessible from the ARM! */ void *ptr; }; struct function_params { /* Input and output buffers of the function. */ struct function_flow_params in; struct function_flow_params out; /* Indicates whether the previous call of that function * is still pending or has been completed. */ int call_status; /* Integer value returned by the function */ int return_value; /* Contains the error code (if error there is) */ int err_no; }; /* Contains the parameters relative to one * function call. */ struct call_params { /* ID of the function to call */ unsigned int id; /* Priority of the call */ unsigned short prio; /* Flag value: set when the io_channel is * free again. */ unsigned char sync; /* local addresses where to load/store results */ void *in; void *out; }; /* That structure defines one channel of communication. * Two of them will be instancied: one for the * sh4->arm channel, and one for the arm->sh4 channel. */ struct io_channel { /* Params of the call. */ struct call_params cparams; /* Array of function params. * fparams[i] contains the params for the * function with the ID=i. */ struct function_params fparams[NB_MAX_FUNCTIONS]; }; /* Make a function available to the remote processor. * /!\ Never use that function directly! * Use the macro AICA_SHARE instead. */ void __aica_share(aica_funcp_t func, const char *funcname, size_t sz_in, size_t sz_out); /* Call a function shared by the remote processor. * /!\ Never use that function directly! * Use the AICA_ADD_REMOTE macro instead; it will * define locally the remote function. */ int __aica_call(unsigned int id, void *in, void *out, unsigned short prio); /* Unregister the handler at the given ID. */ int aica_clear_handler(unsigned int id); /* Clear the whole table. */ void aica_clear_handler_table(void); /* Update the function params table. */ void aica_update_fparams_table(unsigned int id, struct function_params *fparams); /* Return the ID associated to a function name. */ int aica_find_id(unsigned int *id, char *funcname); /* Return the function associated to an ID. */ aica_funcp_t aica_get_func_from_id(unsigned int id); /* Return the name of the function associated to an ID. */ const char * aica_get_funcname_from_id(unsigned int id); /* Send data to the remote processor. */ void aica_upload(void *dest, const void *from, size_t size); /* Receive data from the remote processor. */ void aica_download(void *dest, const void *from, size_t size); /* Initialize the interrupt system. */ void aica_interrupt_init(void); /* Send a notification to the remote processor. */ void aica_interrupt(void); /* Stop all communication with the AICA subsystem. */ void aica_exit(void); struct __aica_shared_function { aica_funcp_t func; const char *name; size_t sz_in, sz_out; }; #define AICA_SHARED_LIST struct __aica_shared_function __aica_shared_list[] extern AICA_SHARED_LIST __attribute__((weak)); #define AICA_SHARED_LIST_ELEMENT(func, sz_in, sz_out) \ { func, #func, sz_in, sz_out, } #define AICA_SHARED_LIST_END \ { NULL, NULL, 0, 0, } #define AICA_SHARE(func, sz_in, sz_out) \ __aica_share(func, #func, sz_in, sz_out) #define AICA_SHARED(func) \ int func(void *out, void *in) #define AICA_ADD_REMOTE(func, prio) \ static int _##func##_id = -1; \ int func(void *out, void *in) \ { \ if (_##func##_id < 0) { \ int res = __aica_call(0, #func, &_##func##_id, 0); \ if (res < 0) \ return res; \ } \ return __aica_call(_##func##_id, in, out, prio); \ } #endif <file_sep>/sdk/bin/src/raw2wav/Makefile # Makefile for the raw2wav program. ifeq ($(LBITS),64) INCS = -I/usr/include/x86_64-linux-gnu -I/usr/include/$(gcc -print-multiarch) LIBS = -L/usr/lib32 CC = gcc -m32 $(INCS) LD = gcc -m32 $(LIBS) else CC = gcc LD = gcc endif CFLAGS = -O2 INSTALL = install DESTDIR = ../.. all: raw2wav install : raw2wav $(INSTALL) -m 755 raw2wav $(DESTDIR)/raw2wav run : raw2wav @./raw2wav test.raw test.wav clean: rm -rf *.o rm -rf raw2wav <file_sep>/include/drivers/sh7750_regs.h /** * SH-7750 memory-mapped registers * This file based on information provided in the following document: * "Hitachi SuperH (tm) RISC engine. SH7750 Series (SH7750, SH7750S) * Hardware Manual" * Document Number ADE-602-124C, Rev. 4.0, 4/21/00, Hitachi Ltd. * * Copyright (C) 2001 OKTET Ltd., St.-Petersburg, Russia * Author: <NAME> <<EMAIL>> * <NAME> <<EMAIL>> * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.com/license/LICENSE. * * @(#) $Id: sh7750_regs.h,v 1.5 2006/09/13 11:22:13 ralf Exp $ * * 2011-2014 Modified by SWAT */ #ifndef __SH7750_REGS_H__ #define __SH7750_REGS_H__ #include <arch/types.h> /* * All register has 2 addresses: in 0xff000000 - 0xffffffff (P4 address) and * in 0x1f000000 - 0x1fffffff (area 7 address) */ #define P4_BASE 0xff000000 /* Accessable only in priveleged mode */ #define A7_BASE 0x1f000000 /* Accessable only using TLB */ #define P4_REG32(ofs) (P4_BASE + (ofs)) #define A7_REG32(ofs) (A7_BASE + (ofs)) /** * Macros for r/w registers */ #define reg_read_8(a) (*(vuint8 *)(a)) #define reg_read_16(a) (*(vuint16 *)(a)) #define reg_read_32(a) (*(vuint32 *)(a)) #define reg_write_8(a, v) (*(vuint8 *)(a) = (v)) #define reg_write_16(a, v) (*(vuint16 *)(a) = (v)) #define reg_write_32(a, v) (*(vuint32 *)(a) = (v)) /* * MMU Registers */ /* Page Table Entry High register - PTEH */ #define PTEH_REGOFS 0x000000 /* offset */ #define PTEH P4_REG32(PTEH_REGOFS) #define PTEH_A7 A7_REG32(PTEH_REGOFS) #define PTEH_VPN 0xfffffd00 /* Virtual page number */ #define PTEH_VPN_S 10 #define PTEH_ASID 0x000000ff /* Address space identifier */ #define PTEH_ASID_S 0 /* Page Table Entry Low register - PTEL */ #define PTEL_REGOFS 0x000004 /* offset */ #define PTEL P4_REG32(PTEL_REGOFS) #define PTEL_A7 A7_REG32(PTEL_REGOFS) #define PTEL_PPN 0x1ffffc00 /* Physical page number */ #define PTEL_PPN_S 10 #define PTEL_V 0x00000100 /* Validity (0-entry is invalid) */ #define PTEL_SZ1 0x00000080 /* Page size bit 1 */ #define PTEL_SZ0 0x00000010 /* Page size bit 0 */ #define PTEL_SZ_1KB 0x00000000 /* 1-kbyte page */ #define PTEL_SZ_4KB 0x00000010 /* 4-kbyte page */ #define PTEL_SZ_64KB 0x00000080 /* 64-kbyte page */ #define PTEL_SZ_1MB 0x00000090 /* 1-Mbyte page */ #define PTEL_PR 0x00000060 /* Protection Key Data */ #define PTEL_PR_ROPO 0x00000000 /* read-only in priv mode */ #define PTEL_PR_RWPO 0x00000020 /* read-write in priv mode */ #define PTEL_PR_ROPU 0x00000040 /* read-only in priv or user mode*/ #define PTEL_PR_RWPU 0x00000060 /* read-write in priv or user mode*/ #define PTEL_C 0x00000008 /* Cacheability (0 - page not cacheable) */ #define PTEL_D 0x00000004 /* Dirty bit (1 - write has been performed to a page) */ #define PTEL_SH 0x00000002 /* Share Status bit (1 - page are shared by processes) */ #define PTEL_WT 0x00000001 /* Write-through bit, specifies the cache write mode: 0 - Copy-back mode 1 - Write-through mode */ /* Page Table Entry Assistance register - PTEA */ #define PTEA_REGOFS 0x000034 /* offset */ #define PTEA P4_REG32(PTEA_REGOFS) #define PTEA_A7 A7_REG32(PTEA_REGOFS) #define PTEA_TC 0x00000008 /* Timing Control bit 0 - use area 5 wait states 1 - use area 6 wait states */ #define PTEA_SA 0x00000007 /* Space Attribute bits: */ #define PTEA_SA_UNDEF 0x00000000 /* 0 - undefined */ #define PTEA_SA_IOVAR 0x00000001 /* 1 - variable-size I/O space */ #define PTEA_SA_IO8 0x00000002 /* 2 - 8-bit I/O space */ #define PTEA_SA_IO16 0x00000003 /* 3 - 16-bit I/O space */ #define PTEA_SA_CMEM8 0x00000004 /* 4 - 8-bit common memory space*/ #define PTEA_SA_CMEM16 0x00000005 /* 5 - 16-bit common memory space*/ #define PTEA_SA_AMEM8 0x00000006 /* 6 - 8-bit attr memory space */ #define PTEA_SA_AMEM16 0x00000007 /* 7 - 16-bit attr memory space */ /* Translation table base register */ #define TTB_REGOFS 0x000008 /* offset */ #define TTB P4_REG32(TTB_REGOFS) #define TTB_A7 A7_REG32(TTB_REGOFS) /* TLB exeption address register - TEA */ #define TEA_REGOFS 0x00000c /* offset */ #define TEA P4_REG32(TEA_REGOFS) #define TEA_A7 A7_REG32(TEA_REGOFS) /* MMU control register - MMUCR */ #define MMUCR_REGOFS 0x000010 /* offset */ #define MMUCR P4_REG32(MMUCR_REGOFS) #define MMUCR_A7 A7_REG32(MMUCR_REGOFS) #define MMUCR_AT 0x00000001 /* Address translation bit */ #define MMUCR_TI 0x00000004 /* TLB invalidate */ #define MMUCR_SV 0x00000100 /* Single Virtual Mode bit */ #define MMUCR_SQMD 0x00000200 /* Store Queue Mode bit */ #define MMUCR_URC 0x0000FC00 /* UTLB Replace Counter */ #define MMUCR_URC_S 10 #define MMUCR_URB 0x00FC0000 /* UTLB Replace Boundary */ #define MMUCR_URB_S 18 #define MMUCR_LRUI 0xFC000000 /* Least Recently Used ITLB */ #define MMUCR_LRUI_S 26 /* * Cache registers * IC -- instructions cache * OC -- operand cache */ /* Cache Control Register - CCR */ #define CCR_REGOFS 0x00001c /* offset */ #define CCR P4_REG32(CCR_REGOFS) #define CCR_A7 A7_REG32(CCR_REGOFS) #define CCR_IIX 0x00008000 /* IC index enable bit */ #define CCR_ICI 0x00000800 /* IC invalidation bit: set it to clear IC */ #define CCR_ICE 0x00000100 /* IC enable bit */ #define CCR_OIX 0x00000080 /* OC index enable bit */ #define CCR_ORA 0x00000020 /* OC RAM enable bit if you set OCE = 0, you should set ORA = 0 */ #define CCR_OCI 0x00000008 /* OC invalidation bit */ #define CCR_CB 0x00000004 /* Copy-back bit for P1 area */ #define CCR_WT 0x00000002 /* Write-through bit for P0,U0,P3 area */ #define CCR_OCE 0x00000001 /* OC enable bit */ /* Queue address control register 0 - QACR0 */ #ifndef QACR0 #define QACR0_REGOFS 0x000038 /* offset */ #define QACR0 P4_REG32(QACR0_REGOFS) #define QACR0_A7 A7_REG32(QACR0_REGOFS) /* Queue address control register 1 - QACR1 */ #define QACR1_REGOFS 0x00003c /* offset */ #define QACR1 P4_REG32(QACR1_REGOFS) #define QACR1_A7 A7_REG32(QACR1_REGOFS) #endif /* * Exeption-related registers */ /* Immediate data for TRAPA instuction - TRA */ #define TRA_REGOFS 0x000020 /* offset */ #define TRA P4_REG32(TRA_REGOFS) #define TRA_A7 A7_REG32(TRA_REGOFS) #define TRA_IMM 0x000003fd /* Immediate data operand */ #define TRA_IMM_S 2 /* Exeption event register - EXPEVT */ #define EXPEVT_REGOFS 0x000024 #define EXPEVT P4_REG32(EXPEVT_REGOFS) #define EXPEVT_A7 A7_REG32(EXPEVT_REGOFS) #define EXPEVT_EX 0x00000fff /* Exeption code */ #define EXPEVT_EX_S 0 /* Interrupt event register */ #define INTEVT_REGOFS 0x000028 #define INTEVT P4_REG32(INTEVT_REGOFS) #define INTEVT_A7 A7_REG32(INTEVT_REGOFS) #define INTEVT_EX 0x00000fff /* Exeption code */ #define INTEVT_EX_S 0 /* * Exception/interrupt codes */ #define EVT_TO_NUM(evt) ((evt) >> 5) /* Reset exception category */ #define EVT_POWER_ON_RST 0x000 /* Power-on reset */ #define EVT_MANUAL_RST 0x020 /* Manual reset */ #define EVT_TLB_MULT_HIT 0x140 /* TLB multiple-hit exception */ /* General exception category */ #define EVT_USER_BREAK 0x1E0 /* User break */ #define EVT_IADDR_ERR 0x0E0 /* Instruction address error */ #define EVT_TLB_READ_MISS 0x040 /* ITLB miss exception / DTLB miss exception (read) */ #define EVT_TLB_READ_PROTV 0x0A0 /* ITLB protection violation / DTLB protection violation (read)*/ #define EVT_ILLEGAL_INSTR 0x180 /* General Illegal Instruction exception */ #define EVT_SLOT_ILLEGAL_INSTR 0x1A0 /* Slot Illegal Instruction exception */ #define EVT_FPU_DISABLE 0x800 /* General FPU disable exception*/ #define EVT_SLOT_FPU_DISABLE 0x820 /* Slot FPU disable exception */ #define EVT_DATA_READ_ERR 0x0E0 /* Data address error (read) */ #define EVT_DATA_WRITE_ERR 0x100 /* Data address error (write) */ #define EVT_DTLB_WRITE_MISS 0x060 /* DTLB miss exception (write) */ #define EVT_DTLB_WRITE_PROTV 0x0C0 /* DTLB protection violation exception (write) */ #define EVT_FPU_EXCEPTION 0x120 /* FPU exception */ #define EVT_INITIAL_PGWRITE 0x080 /* Initial Page Write exception */ #define EVT_TRAPA 0x160 /* Unconditional trap (TRAPA) */ /* Interrupt exception category */ #define EVT_NMI 0x1C0 /* Non-maskable interrupt */ #define EVT_IRQ0 0x200 /* External Interrupt 0 */ #define EVT_IRQ1 0x220 /* External Interrupt 1 */ #define EVT_IRQ2 0x240 /* External Interrupt 2 */ #define EVT_IRQ3 0x260 /* External Interrupt 3 */ #define EVT_IRQ4 0x280 /* External Interrupt 4 */ #define EVT_IRQ5 0x2A0 /* External Interrupt 5 */ #define EVT_IRQ6 0x2C0 /* External Interrupt 6 */ #define EVT_IRQ7 0x2E0 /* External Interrupt 7 */ #define EVT_IRQ8 0x300 /* External Interrupt 8 */ #define EVT_IRQ9 0x320 /* External Interrupt 9 */ #define EVT_IRQA 0x340 /* External Interrupt A */ #define EVT_IRQB 0x360 /* External Interrupt B */ #define EVT_IRQC 0x380 /* External Interrupt C */ #define EVT_IRQD 0x3A0 /* External Interrupt D */ #define EVT_IRQE 0x3C0 /* External Interrupt E */ /* Peripheral Module Interrupts - Timer Unit (TMU) */ #define EVT_TUNI0 0x400 /* TMU Underflow Interrupt 0 */ #define EVT_TUNI1 0x420 /* TMU Underflow Interrupt 1 */ #define EVT_TUNI2 0x440 /* TMU Underflow Interrupt 2 */ #define EVT_TICPI2 0x460 /* TMU Input Capture Interrupt 2*/ /* Peripheral Module Interrupts - Real-Time Clock (RTC) */ #define EVT_RTC_ATI 0x480 /* Alarm Interrupt Request */ #define EVT_RTC_PRI 0x4A0 /* Periodic Interrupt Request */ #define EVT_RTC_CUI 0x4C0 /* Carry Interrupt Request */ /* Peripheral Module Interrupts - Serial Communication Interface (SCI) */ #define EVT_SCI_ERI 0x4E0 /* Receive Error */ #define EVT_SCI_RXI 0x500 /* Receive Data Register Full */ #define EVT_SCI_TXI 0x520 /* Transmit Data Register Empty */ #define EVT_SCI_TEI 0x540 /* Transmit End */ /* Peripheral Module Interrupts - Watchdog Timer (WDT) */ #define EVT_WDT_ITI 0x560 /* Interval Timer Interrupt (used when WDT operates in interval timer mode) */ /* Peripheral Module Interrupts - Memory Refresh Unit (REF) */ #define EVT_REF_RCMI 0x580 /* Compare-match Interrupt */ #define EVT_REF_ROVI 0x5A0 /* Refresh Counter Overflow interrupt */ /* Peripheral Module Interrupts - Hitachi User Debug Interface (H-UDI) */ #define EVT_HUDI 0x600 /* UDI interrupt */ /* Peripheral Module Interrupts - General-Purpose I/O (GPIO) */ #define EVT_GPIO 0x620 /* GPIO Interrupt */ /* Peripheral Module Interrupts - DMA Controller (DMAC) */ #define EVT_DMAC_DMTE0 0x640 /* DMAC 0 Transfer End Interrupt*/ #define EVT_DMAC_DMTE1 0x660 /* DMAC 1 Transfer End Interrupt*/ #define EVT_DMAC_DMTE2 0x680 /* DMAC 2 Transfer End Interrupt*/ #define EVT_DMAC_DMTE3 0x6A0 /* DMAC 3 Transfer End Interrupt*/ #define EVT_DMAC_DMAE 0x6C0 /* DMAC Address Error Interrupt */ /* Peripheral Module Interrupts - Serial Communication Interface with FIFO */ /* (SCIF) */ #define EVT_SCIF_ERI 0x700 /* Receive Error */ #define EVT_SCIF_RXI 0x720 /* Receive FIFO Data Full or Receive Data ready interrupt */ #define EVT_SCIF_BRI 0x740 /* Break or overrun error */ #define EVT_SCIF_TXI 0x760 /* Transmit FIFO Data Empty */ /* * Power Management */ #define STBCR_REGOFS 0xC00004 /* offset */ #define STBCR P4_REG32(STBCR_REGOFS) #define STBCR_A7 A7_REG32(STBCR_REGOFS) #define STBCR_STBY 0x80 /* Specifies a transition to standby mode: 0 - Transition to SLEEP mode on SLEEP 1 - Transition to STANDBY mode on SLEEP*/ #define STBCR_PHZ 0x40 /* State of peripheral module pins in standby mode: 0 - normal state 1 - high-impendance state */ #define STBCR_PPU 0x20 /* Peripheral module pins pull-up controls*/ #define STBCR_MSTP4 0x10 /* Stopping the clock supply to DMAC */ #define STBCR_DMAC_STP STBCR_MSTP4 #define STBCR_MSTP3 0x08 /* Stopping the clock supply to SCIF */ #define STBCR_SCIF_STP STBCR_MSTP3 #define STBCR_MSTP2 0x04 /* Stopping the clock supply to TMU */ #define STBCR_TMU_STP STBCR_MSTP2 #define STBCR_MSTP1 0x02 /* Stopping the clock supply to RTC */ #define STBCR_RTC_STP STBCR_MSTP1 #define STBCR_MSPT0 0x01 /* Stopping the clock supply to SCI */ #define STBCR_SCI_STP STBCR_MSTP0 #define STBCR_STBY 0x80 #define STBCR2_REGOFS 0xC00010 /* offset */ #define STBCR2 P4_REG32(STBCR2_REGOFS) #define STBCR2_A7 A7_REG32(STBCR2_REGOFS) #define STBCR2_DSLP 0x80 /* Specifies transition to deep sleep mode: 0 - transition to sleep or standby mode as it is specified in STBY bit 1 - transition to deep sleep mode on execution of SLEEP instruction */ #define STBCR2_MSTP6 0x02 /* Stopping the clock supply to Store Queue in the cache controller */ #define STBCR2_SQ_STP STBCR2_MSTP6 #define STBCR2_MSTP5 0x01 /* Stopping the clock supply to the User Break Controller (UBC) */ #define STBCR2_UBC_STP STBCR2_MSTP5 /* * Clock Pulse Generator (CPG) */ #define FRQCR_REGOFS 0xC00000 /* offset */ #define FRQCR P4_REG32(FRQCR_REGOFS) #define FRQCR_A7 A7_REG32(FRQCR_REGOFS) #define FRQCR_CKOEN 0x0800 /* Clock Output Enable 0 - CKIO pin goes to HiZ/pullup 1 - Clock is output from CKIO */ #define FRQCR_PLL1EN 0x0400 /* PLL circuit 1 enable */ #define FRQCR_PLL2EN 0x0200 /* PLL circuit 2 enable */ #define FRQCR_IFC 0x01C0 /* CPU clock frequency division ratio: */ #define FRQCR_IFCDIV1 0x0000 /* 0 - * 1 */ #define FRQCR_IFCDIV2 0x0040 /* 1 - * 1/2 */ #define FRQCR_IFCDIV3 0x0080 /* 2 - * 1/3 */ #define FRQCR_IFCDIV4 0x00C0 /* 3 - * 1/4 */ #define FRQCR_IFCDIV6 0x0100 /* 4 - * 1/6 */ #define FRQCR_IFCDIV8 0x0140 /* 5 - * 1/8 */ #define FRQCR_BFC 0x0038 /* Bus clock frequency division ratio: */ #define FRQCR_BFCDIV1 0x0000 /* 0 - * 1 */ #define FRQCR_BFCDIV2 0x0008 /* 1 - * 1/2 */ #define FRQCR_BFCDIV3 0x0010 /* 2 - * 1/3 */ #define FRQCR_BFCDIV4 0x0018 /* 3 - * 1/4 */ #define FRQCR_BFCDIV6 0x0020 /* 4 - * 1/6 */ #define FRQCR_BFCDIV8 0x0028 /* 5 - * 1/8 */ #define FRQCR_PFC 0x0007 /* Peripheral module clock frequency division ratio: */ #define FRQCR_PFCDIV2 0x0000 /* 0 - * 1/2 */ #define FRQCR_PFCDIV3 0x0001 /* 1 - * 1/3 */ #define FRQCR_PFCDIV4 0x0002 /* 2 - * 1/4 */ #define FRQCR_PFCDIV6 0x0003 /* 3 - * 1/6 */ #define FRQCR_PFCDIV8 0x0004 /* 4 - * 1/8 */ /* * Watchdog Timer (WDT) */ /* Watchdog Timer Counter register - WTCNT */ #define WTCNT_REGOFS 0xC00008 /* offset */ #define WTCNT P4_REG32(WTCNT_REGOFS) #define WTCNT_A7 A7_REG32(WTCNT_REGOFS) #define WTCNT_KEY 0x5A00 /* When WTCNT byte register written, you have to set the upper byte to 0x5A */ /* Watchdog Timer Control/Status register - WTCSR */ #define WTCSR_REGOFS 0xC0000C /* offset */ #define WTCSR P4_REG32(WTCSR_REGOFS) #define WTCSR_A7 A7_REG32(WTCSR_REGOFS) #define WTCSR_KEY 0xA500 /* When WTCSR byte register written, you have to set the upper byte to 0xA5 */ #define WTCSR_TME 0x80 /* Timer enable (1-upcount start) */ #define WTCSR_MODE 0x40 /* Timer Mode Select: */ #define WTCSR_MODE_WT 0x40 /* Watchdog Timer Mode */ #define WTCSR_MODE_IT 0x00 /* Interval Timer Mode */ #define WTCSR_RSTS 0x20 /* Reset Select: */ #define WTCSR_RST_MAN 0x20 /* Manual Reset */ #define WTCSR_RST_PWR 0x00 /* Power-on Reset */ #define WTCSR_WOVF 0x10 /* Watchdog Timer Overflow Flag */ #define WTCSR_IOVF 0x08 /* Interval Timer Overflow Flag */ #define WTCSR_CKS 0x07 /* Clock Select: */ #define WTCSR_CKS_DIV32 0x00 /* 1/32 of frequency divider 2 input */ #define WTCSR_CKS_DIV64 0x01 /* 1/64 */ #define WTCSR_CKS_DIV128 0x02 /* 1/128 */ #define WTCSR_CKS_DIV256 0x03 /* 1/256 */ #define WTCSR_CKS_DIV512 0x04 /* 1/512 */ #define WTCSR_CKS_DIV1024 0x05 /* 1/1024 */ #define WTCSR_CKS_DIV2048 0x06 /* 1/2048 */ #define WTCSR_CKS_DIV4096 0x07 /* 1/4096 */ /* * Real-Time Clock (RTC) */ /* 64-Hz Counter Register (byte, read-only) - R64CNT */ #define R64CNT_REGOFS 0xC80000 /* offset */ #define R64CNT P4_REG32(R64CNT_REGOFS) #define R64CNT_A7 A7_REG32(R64CNT_REGOFS) /* Second Counter Register (byte, BCD-coded) - RSECCNT */ #define RSECCNT_REGOFS 0xC80004 /* offset */ #define RSECCNT P4_REG32(RSECCNT_REGOFS) #define RSECCNT_A7 A7_REG32(RSECCNT_REGOFS) /* Minute Counter Register (byte, BCD-coded) - RMINCNT */ #define RMINCNT_REGOFS 0xC80008 /* offset */ #define RMINCNT P4_REG32(RMINCNT_REGOFS) #define RMINCNT_A7 A7_REG32(RMINCNT_REGOFS) /* Hour Counter Register (byte, BCD-coded) - RHRCNT */ #define RHRCNT_REGOFS 0xC8000C /* offset */ #define RHRCNT P4_REG32(RHRCNT_REGOFS) #define RHRCNT_A7 A7_REG32(RHRCNT_REGOFS) /* Day-of-Week Counter Register (byte) - RWKCNT */ #define RWKCNT_REGOFS 0xC80010 /* offset */ #define RWKCNT P4_REG32(RWKCNT_REGOFS) #define RWKCNT_A7 A7_REG32(RWKCNT_REGOFS) #define RWKCNT_SUN 0 /* Sunday */ #define RWKCNT_MON 1 /* Monday */ #define RWKCNT_TUE 2 /* Tuesday */ #define RWKCNT_WED 3 /* Wednesday */ #define RWKCNT_THU 4 /* Thursday */ #define RWKCNT_FRI 5 /* Friday */ #define RWKCNT_SAT 6 /* Saturday */ /* Day Counter Register (byte, BCD-coded) - RDAYCNT */ #define RDAYCNT_REGOFS 0xC80014 /* offset */ #define RDAYCNT P4_REG32(RDAYCNT_REGOFS) #define RDAYCNT_A7 A7_REG32(RDAYCNT_REGOFS) /* Month Counter Register (byte, BCD-coded) - RMONCNT */ #define RMONCNT_REGOFS 0xC80018 /* offset */ #define RMONCNT P4_REG32(RMONCNT_REGOFS) #define RMONCNT_A7 A7_REG32(RMONCNT_REGOFS) /* Year Counter Register (half, BCD-coded) - RYRCNT */ #define RYRCNT_REGOFS 0xC8001C /* offset */ #define RYRCNT P4_REG32(RYRCNT_REGOFS) #define RYRCNT_A7 A7_REG32(RYRCNT_REGOFS) /* Second Alarm Register (byte, BCD-coded) - RSECAR */ #define RSECAR_REGOFS 0xC80020 /* offset */ #define RSECAR P4_REG32(RSECAR_REGOFS) #define RSECAR_A7 A7_REG32(RSECAR_REGOFS) #define RSECAR_ENB 0x80 /* Second Alarm Enable */ /* Minute Alarm Register (byte, BCD-coded) - RMINAR */ #define RMINAR_REGOFS 0xC80024 /* offset */ #define RMINAR P4_REG32(RMINAR_REGOFS) #define RMINAR_A7 A7_REG32(RMINAR_REGOFS) #define RMINAR_ENB 0x80 /* Minute Alarm Enable */ /* Hour Alarm Register (byte, BCD-coded) - RHRAR */ #define RHRAR_REGOFS 0xC80028 /* offset */ #define RHRAR P4_REG32(RHRAR_REGOFS) #define RHRAR_A7 A7_REG32(RHRAR_REGOFS) #define RHRAR_ENB 0x80 /* Hour Alarm Enable */ /* Day-of-Week Alarm Register (byte) - RWKAR */ #define RWKAR_REGOFS 0xC8002C /* offset */ #define RWKAR P4_REG32(RWKAR_REGOFS) #define RWKAR_A7 A7_REG32(RWKAR_REGOFS) #define RWKAR_ENB 0x80 /* Day-of-week Alarm Enable */ #define RWKAR_SUN 0 /* Sunday */ #define RWKAR_MON 1 /* Monday */ #define RWKAR_TUE 2 /* Tuesday */ #define RWKAR_WED 3 /* Wednesday */ #define RWKAR_THU 4 /* Thursday */ #define RWKAR_FRI 5 /* Friday */ #define RWKAR_SAT 6 /* Saturday */ /* Day Alarm Register (byte, BCD-coded) - RDAYAR */ #define RDAYAR_REGOFS 0xC80030 /* offset */ #define RDAYAR P4_REG32(RDAYAR_REGOFS) #define RDAYAR_A7 A7_REG32(RDAYAR_REGOFS) #define RDAYAR_ENB 0x80 /* Day Alarm Enable */ /* Month Counter Register (byte, BCD-coded) - RMONAR */ #define RMONAR_REGOFS 0xC80034 /* offset */ #define RMONAR P4_REG32(RMONAR_REGOFS) #define RMONAR_A7 A7_REG32(RMONAR_REGOFS) #define RMONAR_ENB 0x80 /* Month Alarm Enable */ /* RTC Control Register 1 (byte) - RCR1 */ #define RCR1_REGOFS 0xC80038 /* offset */ #define RCR1 P4_REG32(RCR1_REGOFS) #define RCR1_A7 A7_REG32(RCR1_REGOFS) #define RCR1_CF 0x80 /* Carry Flag */ #define RCR1_CIE 0x10 /* Carry Interrupt Enable */ #define RCR1_AIE 0x08 /* Alarm Interrupt Enable */ #define RCR1_AF 0x01 /* Alarm Flag */ /* RTC Control Register 2 (byte) - RCR2 */ #define RCR2_REGOFS 0xC8003C /* offset */ #define RCR2 P4_REG32(RCR2_REGOFS) #define RCR2_A7 A7_REG32(RCR2_REGOFS) #define RCR2_PEF 0x80 /* Periodic Interrupt Flag */ #define RCR2_PES 0x70 /* Periodic Interrupt Enable: */ #define RCR2_PES_DIS 0x00 /* Periodic Interrupt Disabled */ #define RCR2_PES_DIV256 0x10 /* Generated at 1/256 sec interval */ #define RCR2_PES_DIV64 0x20 /* Generated at 1/64 sec interval */ #define RCR2_PES_DIV16 0x30 /* Generated at 1/16 sec interval */ #define RCR2_PES_DIV4 0x40 /* Generated at 1/4 sec interval */ #define RCR2_PES_DIV2 0x50 /* Generated at 1/2 sec interval */ #define RCR2_PES_x1 0x60 /* Generated at 1 sec interval */ #define RCR2_PES_x2 0x70 /* Generated at 2 sec interval */ #define RCR2_RTCEN 0x08 /* RTC Crystal Oscillator is Operated */ #define RCR2_ADJ 0x04 /* 30-Second Adjastment */ #define RCR2_RESET 0x02 /* Frequency divider circuits are reset*/ #define RCR2_START 0x01 /* 0 - sec, min, hr, day-of-week, month, year counters are stopped 1 - sec, min, hr, day-of-week, month, year counters operate normally */ /* * Timer Unit (TMU) */ /* Timer Output Control Register (byte) - TOCR */ #define TOCR_REGOFS 0xD80000 /* offset */ #define TOCR P4_REG32(TOCR_REGOFS) #define TOCR_A7 A7_REG32(TOCR_REGOFS) #define TOCR_TCOE 0x01 /* Timer Clock Pin Control: 0 - TCLK is used as external clock input or input capture control 1 - TCLK is used as on-chip RTC output clock pin */ /* Timer Start Register (byte) - TSTR */ #define TSTR_REGOFS 0xD80004 /* offset */ #define TSTR P4_REG32(TSTR_REGOFS) #define TSTR_A7 A7_REG32(TSTR_REGOFS) #define TSTR_STR2 0x04 /* TCNT2 performs count operations */ #define TSTR_STR1 0x02 /* TCNT1 performs count operations */ #define TSTR_STR0 0x01 /* TCNT0 performs count operations */ #define TSTR_STR(n) (1 << (n)) /* Timer Constant Register - TCOR0, TCOR1, TCOR2 */ #define TCOR_REGOFS(n) (0xD80008 + ((n)*12)) /* offset */ #define TCOR(n) P4_REG32(TCOR_REGOFS(n)) #define TCOR_A7(n) A7_REG32(TCOR_REGOFS(n)) #define TCOR0 TCOR(0) #define TCOR1 TCOR(1) #define TCOR2 TCOR(2) #define TCOR0_A7 TCOR_A7(0) #define TCOR1_A7 TCOR_A7(1) #define TCOR2_A7 TCOR_A7(2) /* Timer Counter Register - TCNT0, TCNT1, TCNT2 */ #define TCNT_REGOFS(n) (0xD8000C + ((n)*12)) /* offset */ #define TCNT(n) P4_REG32(TCNT_REGOFS(n)) #define TCNT_A7(n) A7_REG32(TCNT_REGOFS(n)) #define TCNT0 TCNT(0) #define TCNT1 TCNT(1) #define TCNT2 TCNT(2) #define TCNT0_A7 TCNT_A7(0) #define TCNT1_A7 TCNT_A7(1) #define TCNT2_A7 TCNT_A7(2) /* Timer Control Register (half) - TCR0, TCR1, TCR2 */ #define TCR_REGOFS(n) (0xD80010 + ((n)*12)) /* offset */ #define TCR(n) P4_REG32(TCR_REGOFS(n)) #define TCR_A7(n) A7_REG32(TCR_REGOFS(n)) #define TCR0 TCR(0) #define TCR1 TCR(1) #define TCR2 TCR(2) #define TCR0_A7 TCR_A7(0) #define TCR1_A7 TCR_A7(1) #define TCR2_A7 TCR_A7(2) #define TCR2_ICPF 0x200 /* Input Capture Interrupt Flag (1 - input capture has occured) */ #define TCR_UNF 0x100 /* Underflow flag */ #define TCR2_ICPE 0x0C0 /* Input Capture Control: */ #define TCR2_ICPE_DIS 0x000 /* Input Capture function is not used*/ #define TCR2_ICPE_NOINT 0x080 /* Input Capture function is used, but input capture interrupt is not enabled */ #define TCR2_ICPE_INT 0x0C0 /* Input Capture function is used, input capture interrupt enabled */ #define TCR_UNIE 0x020 /* Underflow Interrupt Control (1 - underflow interrupt enabled) */ #define TCR_CKEG 0x018 /* Clock Edge selection: */ #define TCR_CKEG_RAISE 0x000 /* Count/capture on rising edge */ #define TCR_CKEG_FALL 0x008 /* Count/capture on falling edge */ #define TCR_CKEG_BOTH 0x018 /* Count/capture on both rising and falling edges */ #define TCR_TPSC 0x007 /* Timer prescaler */ #define TCR_TPSC_DIV4 0x000 /* Counts on peripheral clock/4 */ #define TCR_TPSC_DIV16 0x001 /* Counts on peripheral clock/16 */ #define TCR_TPSC_DIV64 0x002 /* Counts on peripheral clock/64 */ #define TCR_TPSC_DIV256 0x003 /* Counts on peripheral clock/256 */ #define TCR_TPSC_DIV1024 0x004 /* Counts on peripheral clock/1024 */ #define TCR_TPSC_RTC 0x006 /* Counts on on-chip RTC output clk*/ #define TCR_TPSC_EXT 0x007 /* Counts on external clock */ /* Input Capture Register (read-only) - TCPR2 */ #define TCPR2_REGOFS 0xD8002C /* offset */ #define TCPR2 P4_REG32(TCPR2_REGOFS) #define TCPR2_A7 A7_REG32(TCPR2_REGOFS) /* * Bus State Controller - BSC */ /* Bus Control Register 1 - BCR1 */ #define BCR1_REGOFS 0x800000 /* offset */ #define BCR1 P4_REG32(BCR1_REGOFS) #define BCR1_A7 A7_REG32(BCR1_REGOFS) #define BCR1_ENDIAN 0x80000000 /* Endianness (1 - little endian) */ #define BCR1_MASTER 0x40000000 /* Master/Slave mode (1-master) */ #define BCR1_A0MPX 0x20000000 /* Area 0 Memory Type (0-SRAM,1-MPX)*/ #define BCR1_IPUP 0x02000000 /* Input Pin Pull-up Control: 0 - pull-up resistor is on for control input pins 1 - pull-up resistor is off */ #define BCR1_OPUP 0x01000000 /* Output Pin Pull-up Control: 0 - pull-up resistor is on for control output pins 1 - pull-up resistor is off */ #define BCR1_A1MBC 0x00200000 /* Area 1 SRAM Byte Control Mode: 0 - Area 1 SRAM is set to normal mode 1 - Area 1 SRAM is set to byte control mode */ #define BCR1_A4MBC 0x00100000 /* Area 4 SRAM Byte Control Mode: 0 - Area 4 SRAM is set to normal mode 1 - Area 4 SRAM is set to byte control mode */ #define BCR1_BREQEN 0x00080000 /* BREQ Enable: 0 - External requests are not accepted 1 - External requests are accepted */ #define BCR1_PSHR 0x00040000 /* Partial Sharing Bit: 0 - Master Mode 1 - Partial-sharing Mode */ #define BCR1_MEMMPX 0x00020000 /* Area 1 to 6 MPX Interface: 0 - SRAM/burst ROM interface 1 - MPX interface */ #define BCR1_HIZMEM 0x00008000 /* High Impendance Control. Specifies the state of A[25:0], BS\, CSn\, RD/WR\, CE2A\, CE2B\ in standby mode and when bus is released: 0 - signals go to High-Z mode 1 - signals driven */ #define BCR1_HIZCNT 0x00004000 /* High Impendance Control. Specifies the state of the RAS\, RAS2\, WEn\, CASn\, DQMn, RD\, CASS\, FRAME\, RD2\ signals in standby mode and when bus is released: 0 - signals go to High-Z mode 1 - signals driven */ #define BCR1_A0BST 0x00003800 /* Area 0 Burst ROM Control */ #define BCR1_A0BST_SRAM 0x0000 /* Area 0 accessed as SRAM i/f */ #define BCR1_A0BST_ROM4 0x0800 /* Area 0 accessed as burst ROM interface, 4 cosequtive access*/ #define BCR1_A0BST_ROM8 0x1000 /* Area 0 accessed as burst ROM interface, 8 cosequtive access*/ #define BCR1_A0BST_ROM16 0x1800 /* Area 0 accessed as burst ROM interface, 16 cosequtive access*/ #define BCR1_A0BST_ROM32 0x2000 /* Area 0 accessed as burst ROM interface, 32 cosequtive access*/ #define BCR1_A5BST 0x00000700 /* Area 5 Burst ROM Control */ #define BCR1_A5BST_SRAM 0x0000 /* Area 5 accessed as SRAM i/f */ #define BCR1_A5BST_ROM4 0x0100 /* Area 5 accessed as burst ROM interface, 4 cosequtive access*/ #define BCR1_A5BST_ROM8 0x0200 /* Area 5 accessed as burst ROM interface, 8 cosequtive access*/ #define BCR1_A5BST_ROM16 0x0300 /* Area 5 accessed as burst ROM interface, 16 cosequtive access*/ #define BCR1_A5BST_ROM32 0x0400 /* Area 5 accessed as burst ROM interface, 32 cosequtive access*/ #define BCR1_A6BST 0x000000E0 /* Area 6 Burst ROM Control */ #define BCR1_A6BST_SRAM 0x0000 /* Area 6 accessed as SRAM i/f */ #define BCR1_A6BST_ROM4 0x0020 /* Area 6 accessed as burst ROM interface, 4 cosequtive access*/ #define BCR1_A6BST_ROM8 0x0040 /* Area 6 accessed as burst ROM interface, 8 cosequtive access*/ #define BCR1_A6BST_ROM16 0x0060 /* Area 6 accessed as burst ROM interface, 16 cosequtive access*/ #define BCR1_A6BST_ROM32 0x0080 /* Area 6 accessed as burst ROM interface, 32 cosequtive access*/ #define BCR1_DRAMTP 0x001C /* Area 2 and 3 Memory Type */ #define BCR1_DRAMTP_2SRAM_3SRAM 0x0000 /* Area 2 and 3 are SRAM or MPX interface. */ #define BCR1_DRAMTP_2SRAM_3SDRAM 0x0008 /* Area 2 - SRAM/MPX, Area 3 - synchronous DRAM */ #define BCR1_DRAMTP_2SDRAM_3SDRAM 0x000C /* Area 2 and 3 are synchronous DRAM interface */ #define BCR1_DRAMTP_2SRAM_3DRAM 0x0010 /* Area 2 - SRAM/MPX, Area 3 - DRAM interface */ #define BCR1_DRAMTP_2DRAM_3DRAM 0x0014 /* Area 2 and 3 are DRAM interface */ #define BCR1_A56PCM 0x00000001 /* Area 5 and 6 Bus Type: 0 - SRAM interface 1 - PCMCIA interface */ /* Bus Control Register 2 (half) - BCR2 */ #define BCR2_REGOFS 0x800004 /* offset */ #define BCR2 P4_REG32(BCR2_REGOFS) #define BCR2_A7 A7_REG32(BCR2_REGOFS) #define BCR2_A0SZ 0xC000 /* Area 0 Bus Width */ #define BCR2_A0SZ_S 14 #define BCR2_A6SZ 0x3000 /* Area 6 Bus Width */ #define BCR2_A6SZ_S 12 #define BCR2_A5SZ 0x0C00 /* Area 5 Bus Width */ #define BCR2_A5SZ_S 10 #define BCR2_A4SZ 0x0300 /* Area 4 Bus Width */ #define BCR2_A4SZ_S 8 #define BCR2_A3SZ 0x00C0 /* Area 3 Bus Width */ #define BCR2_A3SZ_S 6 #define BCR2_A2SZ 0x0030 /* Area 2 Bus Width */ #define BCR2_A2SZ_S 4 #define BCR2_A1SZ 0x000C /* Area 1 Bus Width */ #define BCR2_A1SZ_S 2 #define BCR2_SZ_64 0 /* 64 bits */ #define BCR2_SZ_8 1 /* 8 bits */ #define BCR2_SZ_16 2 /* 16 bits */ #define BCR2_SZ_32 3 /* 32 bits */ #define BCR2_PORTEN 0x0001 /* Port Function Enable : 0 - D51-D32 are not used as a port 1 - D51-D32 are used as a port */ /* Wait Control Register 1 - WCR1 */ #define WCR1_REGOFS 0x800008 /* offset */ #define WCR1 P4_REG32(WCR1_REGOFS) #define WCR1_A7 A7_REG32(WCR1_REGOFS) #define WCR1_DMAIW 0x70000000 /* DACK Device Inter-Cycle Idle specification */ #define WCR1_DMAIW_S 28 #define WCR1_A6IW 0x07000000 /* Area 6 Inter-Cycle Idle spec. */ #define WCR1_A6IW_S 24 #define WCR1_A5IW 0x00700000 /* Area 5 Inter-Cycle Idle spec. */ #define WCR1_A5IW_S 20 #define WCR1_A4IW 0x00070000 /* Area 4 Inter-Cycle Idle spec. */ #define WCR1_A4IW_S 16 #define WCR1_A3IW 0x00007000 /* Area 3 Inter-Cycle Idle spec. */ #define WCR1_A3IW_S 12 #define WCR1_A2IW 0x00000700 /* Area 2 Inter-Cycle Idle spec. */ #define WCR1_A2IW_S 8 #define WCR1_A1IW 0x00000070 /* Area 1 Inter-Cycle Idle spec. */ #define WCR1_A1IW_S 4 #define WCR1_A0IW 0x00000007 /* Area 0 Inter-Cycle Idle spec. */ #define WCR1_A0IW_S 0 /* Wait Control Register 2 - WCR2 */ #define WCR2_REGOFS 0x80000C /* offset */ #define WCR2 P4_REG32(WCR2_REGOFS) #define WCR2_A7 A7_REG32(WCR2_REGOFS) #define WCR2_A6W 0xE0000000 /* Area 6 Wait Control */ #define WCR2_A6W_S 29 #define WCR2_A6B 0x1C000000 /* Area 6 Burst Pitch */ #define WCR2_A6B_S 26 #define WCR2_A5W 0x03800000 /* Area 5 Wait Control */ #define WCR2_A5W_S 23 #define WCR2_A5B 0x00700000 /* Area 5 Burst Pitch */ #define WCR2_A5B_S 20 #define WCR2_A4W 0x000E0000 /* Area 4 Wait Control */ #define WCR2_A4W_S 17 #define WCR2_A3W 0x0000E000 /* Area 3 Wait Control */ #define WCR2_A3W_S 13 #define WCR2_A2W 0x00000E00 /* Area 2 Wait Control */ #define WCR2_A2W_S 9 #define WCR2_A1W 0x000001C0 /* Area 1 Wait Control */ #define WCR2_A1W_S 6 #define WCR2_A0W 0x00000038 /* Area 0 Wait Control */ #define WCR2_A0W_S 3 #define WCR2_A0B 0x00000007 /* Area 0 Burst Pitch */ #define WCR2_A0B_S 0 #define WCR2_WS0 0 /* 0 wait states inserted */ #define WCR2_WS1 1 /* 1 wait states inserted */ #define WCR2_WS2 2 /* 2 wait states inserted */ #define WCR2_WS3 3 /* 3 wait states inserted */ #define WCR2_WS6 4 /* 6 wait states inserted */ #define WCR2_WS9 5 /* 9 wait states inserted */ #define WCR2_WS12 6 /* 12 wait states inserted */ #define WCR2_WS15 7 /* 15 wait states inserted */ #define WCR2_BPWS0 0 /* 0 wait states inserted from 2nd access */ #define WCR2_BPWS1 1 /* 1 wait states inserted from 2nd access */ #define WCR2_BPWS2 2 /* 2 wait states inserted from 2nd access */ #define WCR2_BPWS3 3 /* 3 wait states inserted from 2nd access */ #define WCR2_BPWS4 4 /* 4 wait states inserted from 2nd access */ #define WCR2_BPWS5 5 /* 5 wait states inserted from 2nd access */ #define WCR2_BPWS6 6 /* 6 wait states inserted from 2nd access */ #define WCR2_BPWS7 7 /* 7 wait states inserted from 2nd access */ /* DRAM CAS\ Assertion Delay (area 3,2) */ #define WCR2_DRAM_CAS_ASW1 0 /* 1 cycle */ #define WCR2_DRAM_CAS_ASW2 1 /* 2 cycles */ #define WCR2_DRAM_CAS_ASW3 2 /* 3 cycles */ #define WCR2_DRAM_CAS_ASW4 3 /* 4 cycles */ #define WCR2_DRAM_CAS_ASW7 4 /* 7 cycles */ #define WCR2_DRAM_CAS_ASW10 5 /* 10 cycles */ #define WCR2_DRAM_CAS_ASW13 6 /* 13 cycles */ #define WCR2_DRAM_CAS_ASW16 7 /* 16 cycles */ /* SDRAM CAS\ Latency Cycles */ #define WCR2_SDRAM_CAS_LAT1 1 /* 1 cycle */ #define WCR2_SDRAM_CAS_LAT2 2 /* 2 cycles */ #define WCR2_SDRAM_CAS_LAT3 3 /* 3 cycles */ #define WCR2_SDRAM_CAS_LAT4 4 /* 4 cycles */ #define WCR2_SDRAM_CAS_LAT5 5 /* 5 cycles */ /* Wait Control Register 3 - WCR3 */ #define WCR3_REGOFS 0x800010 /* offset */ #define WCR3 P4_REG32(WCR3_REGOFS) #define WCR3_A7 A7_REG32(WCR3_REGOFS) #define WCR3_A6S 0x04000000 /* Area 6 Write Strobe Setup time */ #define WCR3_A6H 0x03000000 /* Area 6 Data Hold Time */ #define WCR3_A6H_S 24 #define WCR3_A5S 0x00400000 /* Area 5 Write Strobe Setup time */ #define WCR3_A5H 0x00300000 /* Area 5 Data Hold Time */ #define WCR3_A5H_S 20 #define WCR3_A4S 0x00040000 /* Area 4 Write Strobe Setup time */ #define WCR3_A4H 0x00030000 /* Area 4 Data Hold Time */ #define WCR3_A4H_S 16 #define WCR3_A3S 0x00004000 /* Area 3 Write Strobe Setup time */ #define WCR3_A3H 0x00003000 /* Area 3 Data Hold Time */ #define WCR3_A3H_S 12 #define WCR3_A2S 0x00000400 /* Area 2 Write Strobe Setup time */ #define WCR3_A2H 0x00000300 /* Area 2 Data Hold Time */ #define WCR3_A2H_S 8 #define WCR3_A1S 0x00000040 /* Area 1 Write Strobe Setup time */ #define WCR3_A1H 0x00000030 /* Area 1 Data Hold Time */ #define WCR3_A1H_S 4 #define WCR3_A0S 0x00000004 /* Area 0 Write Strobe Setup time */ #define WCR3_A0H 0x00000003 /* Area 0 Data Hold Time */ #define WCR3_A0H_S 0 #define WCR3_DHWS_0 0 /* 0 wait states data hold time */ #define WCR3_DHWS_1 1 /* 1 wait states data hold time */ #define WCR3_DHWS_2 2 /* 2 wait states data hold time */ #define WCR3_DHWS_3 3 /* 3 wait states data hold time */ #define MCR_REGOFS 0x800014 /* offset */ #define MCR P4_REG32(MCR_REGOFS) #define MCR_A7 A7_REG32(MCR_REGOFS) #define MCR_RASD 0x80000000 /* RAS Down mode */ #define MCR_MRSET 0x40000000 /* SDRAM Mode Register Set */ #define MCR_PALL 0x00000000 /* SDRAM Precharge All cmd. Mode */ #define MCR_TRC 0x38000000 /* RAS Precharge Time at End of Refresh: */ #define MCR_TRC_0 0x00000000 /* 0 */ #define MCR_TRC_3 0x08000000 /* 3 */ #define MCR_TRC_6 0x10000000 /* 6 */ #define MCR_TRC_9 0x18000000 /* 9 */ #define MCR_TRC_12 0x20000000 /* 12 */ #define MCR_TRC_15 0x28000000 /* 15 */ #define MCR_TRC_18 0x30000000 /* 18 */ #define MCR_TRC_21 0x38000000 /* 21 */ #define MCR_TCAS 0x00800000 /* CAS Negation Period */ #define MCR_TCAS_1 0x00000000 /* 1 */ #define MCR_TCAS_2 0x00800000 /* 2 */ #define MCR_TPC 0x00380000 /* DRAM: RAS Precharge Period SDRAM: minimum number of cycles until the next bank active cmd is output after precharging */ #define MCR_TPC_S 19 #define MCR_TPC_SDRAM_1 0x00000000 /* 1 cycle */ #define MCR_TPC_SDRAM_2 0x00080000 /* 2 cycles */ #define MCR_TPC_SDRAM_3 0x00100000 /* 3 cycles */ #define MCR_TPC_SDRAM_4 0x00180000 /* 4 cycles */ #define MCR_TPC_SDRAM_5 0x00200000 /* 5 cycles */ #define MCR_TPC_SDRAM_6 0x00280000 /* 6 cycles */ #define MCR_TPC_SDRAM_7 0x00300000 /* 7 cycles */ #define MCR_TPC_SDRAM_8 0x00380000 /* 8 cycles */ #define MCR_RCD 0x00030000 /* DRAM: RAS-CAS Assertion Delay time SDRAM: bank active-read/write cmd delay time */ #define MCR_RCD_DRAM_2 0x00000000 /* DRAM delay 2 clocks */ #define MCR_RCD_DRAM_3 0x00010000 /* DRAM delay 3 clocks */ #define MCR_RCD_DRAM_4 0x00020000 /* DRAM delay 4 clocks */ #define MCR_RCD_DRAM_5 0x00030000 /* DRAM delay 5 clocks */ #define MCR_RCD_SDRAM_2 0x00010000 /* DRAM delay 2 clocks */ #define MCR_RCD_SDRAM_3 0x00020000 /* DRAM delay 3 clocks */ #define MCR_RCD_SDRAM_4 0x00030000 /* DRAM delay 4 clocks */ #define MCR_TRWL 0x0000E000 /* SDRAM Write Precharge Delay */ #define MCR_TRWL_1 0x00000000 /* 1 */ #define MCR_TRWL_2 0x00002000 /* 2 */ #define MCR_TRWL_3 0x00004000 /* 3 */ #define MCR_TRWL_4 0x00006000 /* 4 */ #define MCR_TRWL_5 0x00008000 /* 5 */ #define MCR_TRAS 0x00001C00 /* DRAM: CAS-Before-RAS Refresh RAS asserting period SDRAM: Command interval after synchronous DRAM refresh */ #define MCR_TRAS_DRAM_2 0x00000000 /* 2 */ #define MCR_TRAS_DRAM_3 0x00000400 /* 3 */ #define MCR_TRAS_DRAM_4 0x00000800 /* 4 */ #define MCR_TRAS_DRAM_5 0x00000C00 /* 5 */ #define MCR_TRAS_DRAM_6 0x00001000 /* 6 */ #define MCR_TRAS_DRAM_7 0x00001400 /* 7 */ #define MCR_TRAS_DRAM_8 0x00001800 /* 8 */ #define MCR_TRAS_DRAM_9 0x00001C00 /* 9 */ #define MCR_TRAS_SDRAM_TRC_4 0x00000000 /* 4 + TRC */ #define MCR_TRAS_SDRAM_TRC_5 0x00000400 /* 5 + TRC */ #define MCR_TRAS_SDRAM_TRC_6 0x00000800 /* 6 + TRC */ #define MCR_TRAS_SDRAM_TRC_7 0x00000C00 /* 7 + TRC */ #define MCR_TRAS_SDRAM_TRC_8 0x00001000 /* 8 + TRC */ #define MCR_TRAS_SDRAM_TRC_9 0x00001400 /* 9 + TRC */ #define MCR_TRAS_SDRAM_TRC_10 0x00001800 /* 10 + TRC */ #define MCR_TRAS_SDRAM_TRC_11 0x00001C00 /* 11 + TRC */ #define MCR_BE 0x00000200 /* Burst Enable */ #define MCR_SZ 0x00000180 /* Memory Data Size */ #define MCR_SZ_64 0x00000000 /* 64 bits */ #define MCR_SZ_16 0x00000100 /* 16 bits */ #define MCR_SZ_32 0x00000180 /* 32 bits */ #define MCR_AMX 0x00000078 /* Address Multiplexing */ #define MCR_AMX_S 3 #define MCR_AMX_DRAM_8BIT_COL 0x00000000 /* 8-bit column addr */ #define MCR_AMX_DRAM_9BIT_COL 0x00000008 /* 9-bit column addr */ #define MCR_AMX_DRAM_10BIT_COL 0x00000010 /* 10-bit column addr */ #define MCR_AMX_DRAM_11BIT_COL 0x00000018 /* 11-bit column addr */ #define MCR_AMX_DRAM_12BIT_COL 0x00000020 /* 12-bit column addr */ /* See SH7750 Hardware Manual for SDRAM address multiplexor selection */ #define MCR_RFSH 0x00000004 /* Refresh Control */ #define MCR_RMODE 0x00000002 /* Refresh Mode: */ #define MCR_RMODE_NORMAL 0x00000000 /* Normal Refresh Mode */ #define MCR_RMODE_SELF 0x00000002 /* Self-Refresh Mode */ #define MCR_RMODE_EDO 0x00000001 /* EDO Mode */ /* SDRAM Mode Set address */ #define SDRAM_MODE_A2_BASE 0xFF900000 #define SDRAM_MODE_A3_BASE 0xFF940000 #define SDRAM_MODE_A2_32BIT(x) (SDRAM_MODE_A2_BASE + ((x) << 2)) #define SDRAM_MODE_A3_32BIT(x) (SDRAM_MODE_A3_BASE + ((x) << 2)) #define SDRAM_MODE_A2_64BIT(x) (SDRAM_MODE_A2_BASE + ((x) << 3)) #define SDRAM_MODE_A3_64BIT(x) (SDRAM_MODE_A3_BASE + ((x) << 3)) /* PCMCIA Control Register (half) - PCR */ #define PCR_REGOFS 0x800018 /* offset */ #define PCR P4_REG32(PCR_REGOFS) #define PCR_A7 A7_REG32(PCR_REGOFS) #define PCR_A5PCW 0xC000 /* Area 5 PCMCIA Wait - Number of wait states to be added to the number of waits specified by WCR2 in a low-speed PCMCIA wait cycle */ #define PCR_A5PCW_0 0x0000 /* 0 waits inserted */ #define PCR_A5PCW_15 0x4000 /* 15 waits inserted */ #define PCR_A5PCW_30 0x8000 /* 30 waits inserted */ #define PCR_A5PCW_50 0xC000 /* 50 waits inserted */ #define PCR_A6PCW 0x3000 /* Area 6 PCMCIA Wait - Number of wait states to be added to the number of waits specified by WCR2 in a low-speed PCMCIA wait cycle */ #define PCR_A6PCW_0 0x0000 /* 0 waits inserted */ #define PCR_A6PCW_15 0x1000 /* 15 waits inserted */ #define PCR_A6PCW_30 0x2000 /* 30 waits inserted */ #define PCR_A6PCW_50 0x3000 /* 50 waits inserted */ #define PCR_A5TED 0x0E00 /* Area 5 Address-OE\/WE\ Assertion Delay, delay time from address output to OE\/WE\ assertion on the connected PCMCIA interface */ #define PCR_A5TED_S 9 #define PCR_A6TED 0x01C0 /* Area 6 Address-OE\/WE\ Assertion Delay*/ #define PCR_A6TED_S 6 #define PCR_TED_0WS 0 /* 0 Waits inserted */ #define PCR_TED_1WS 1 /* 1 Waits inserted */ #define PCR_TED_2WS 2 /* 2 Waits inserted */ #define PCR_TED_3WS 3 /* 3 Waits inserted */ #define PCR_TED_6WS 4 /* 6 Waits inserted */ #define PCR_TED_9WS 5 /* 9 Waits inserted */ #define PCR_TED_12WS 6 /* 12 Waits inserted */ #define PCR_TED_15WS 7 /* 15 Waits inserted */ #define PCR_A5TEH 0x0038 /* Area 5 OE\/WE\ Negation Address delay, address hold delay time from OE\/WE\ negation in a write on the connected PCMCIA interface */ #define PCR_A5TEH_S 3 #define PCR_A6TEH 0x0007 /* Area 6 OE\/WE\ Negation Address delay*/ #define PCR_A6TEH_S 0 #define PCR_TEH_0WS 0 /* 0 Waits inserted */ #define PCR_TEH_1WS 1 /* 1 Waits inserted */ #define PCR_TEH_2WS 2 /* 2 Waits inserted */ #define PCR_TEH_3WS 3 /* 3 Waits inserted */ #define PCR_TEH_6WS 4 /* 6 Waits inserted */ #define PCR_TEH_9WS 5 /* 9 Waits inserted */ #define PCR_TEH_12WS 6 /* 12 Waits inserted */ #define PCR_TEH_15WS 7 /* 15 Waits inserted */ /* Refresh Timer Control/Status Register (half) - RTSCR */ #define RTCSR_REGOFS 0x80001C /* offset */ #define RTCSR P4_REG32(RTCSR_REGOFS) #define RTCSR_A7 A7_REG32(RTCSR_REGOFS) #define RTCSR_KEY 0xA500 /* RTCSR write key */ #define RTCSR_CMF 0x0080 /* Compare-Match Flag (indicates a match between the refresh timer counter and refresh time constant) */ #define RTCSR_CMIE 0x0040 /* Compare-Match Interrupt Enable */ #define RTCSR_CKS 0x0038 /* Refresh Counter Clock Selects */ #define RTCSR_CKS_DIS 0x0000 /* Clock Input Disabled */ #define RTCSR_CKS_CKIO_DIV4 0x0008 /* Bus Clock / 4 */ #define RTCSR_CKS_CKIO_DIV16 0x0010 /* Bus Clock / 16 */ #define RTCSR_CKS_CKIO_DIV64 0x0018 /* Bus Clock / 64 */ #define RTCSR_CKS_CKIO_DIV256 0x0020 /* Bus Clock / 256 */ #define RTCSR_CKS_CKIO_DIV1024 0x0028 /* Bus Clock / 1024 */ #define RTCSR_CKS_CKIO_DIV2048 0x0030 /* Bus Clock / 2048 */ #define RTCSR_CKS_CKIO_DIV4096 0x0038 /* Bus Clock / 4096 */ #define RTCSR_OVF 0x0004 /* Refresh Count Overflow Flag */ #define RTCSR_OVIE 0x0002 /* Refresh Count Overflow Interrupt Enable */ #define RTCSR_LMTS 0x0001 /* Refresh Count Overflow Limit Select */ #define RTCSR_LMTS_1024 0x0000 /* Count Limit is 1024 */ #define RTCSR_LMTS_512 0x0001 /* Count Limit is 512 */ /* Refresh Timer Counter (half) - RTCNT */ #define RTCNT_REGOFS 0x800020 /* offset */ #define RTCNT P4_REG32(RTCNT_REGOFS) #define RTCNT_A7 A7_REG32(RTCNT_REGOFS) #define RTCNT_KEY 0xA500 /* RTCNT write key */ /* Refresh Time Constant Register (half) - RTCOR */ #define RTCOR_REGOFS 0x800024 /* offset */ #define RTCOR P4_REG32(RTCOR_REGOFS) #define RTCOR_A7 A7_REG32(RTCOR_REGOFS) #define RTCOR_KEY 0xA500 /* RTCOR write key */ /* Refresh Count Register (half) - RFCR */ #define RFCR_REGOFS 0x800028 /* offset */ #define RFCR P4_REG32(RFCR_REGOFS) #define RFCR_A7 A7_REG32(RFCR_REGOFS) #define RFCR_KEY 0xA400 /* RFCR write key */ /* * Direct Memory Access Controller (DMAC) */ /* DMA Source Address Register - SAR0, SAR1, SAR2, SAR3 */ #define SAR_REGOFS(n) (0xA00000 + ((n)*16)) /* offset */ #define SAR(n) P4_REG32(SAR_REGOFS(n)) #define SAR_A7(n) A7_REG32(SAR_REGOFS(n)) #define SAR0 SAR(0) #define SAR1 SAR(1) #define SAR2 SAR(2) #define SAR3 SAR(3) #define SAR0_A7 SAR_A7(0) #define SAR1_A7 SAR_A7(1) #define SAR2_A7 SAR_A7(2) #define SAR3_A7 SAR_A7(3) /* DMA Destination Address Register - DAR0, DAR1, DAR2, DAR3 */ #define DAR_REGOFS(n) (0xA00004 + ((n)*16)) /* offset */ #define DAR(n) P4_REG32(DAR_REGOFS(n)) #define DAR_A7(n) A7_REG32(DAR_REGOFS(n)) #define DAR0 DAR(0) #define DAR1 DAR(1) #define DAR2 DAR(2) #define DAR3 DAR(3) #define DAR0_A7 DAR_A7(0) #define DAR1_A7 DAR_A7(1) #define DAR2_A7 DAR_A7(2) #define DAR3_A7 DAR_A7(3) /* DMA Transfer Count Register - DMATCR0, DMATCR1, DMATCR2, DMATCR3 */ #define DMATCR_REGOFS(n) (0xA00008 + ((n)*16)) /* offset */ #define DMATCR(n) P4_REG32(DMATCR_REGOFS(n)) #define DMATCR_A7(n) A7_REG32(DMATCR_REGOFS(n)) #define DMATCR0_P4 DMATCR(0) #define DMATCR1_P4 DMATCR(1) #define DMATCR2_P4 DMATCR(2) #define DMATCR3_P4 DMATCR(3) #define DMATCR0_A7 DMATCR_A7(0) #define DMATCR1_A7 DMATCR_A7(1) #define DMATCR2_A7 DMATCR_A7(2) #define DMATCR3_A7 DMATCR_A7(3) /* DMA Channel Control Register - CHCR0, CHCR1, CHCR2, CHCR3 */ #define CHCR_REGOFS(n) (0xA0000C + ((n)*16)) /* offset */ #define CHCR(n) P4_REG32(CHCR_REGOFS(n)) #define CHCR_A7(n) A7_REG32(CHCR_REGOFS(n)) #define CHCR0 CHCR(0) #define CHCR1 CHCR(1) #define CHCR2 CHCR(2) #define CHCR3 CHCR(3) #define CHCR0_A7 CHCR_A7(0) #define CHCR1_A7 CHCR_A7(1) #define CHCR2_A7 CHCR_A7(2) #define CHCR3_A7 CHCR_A7(3) #define CHCR_SSA 0xE0000000 /* Source Address Space Attribute */ #define CHCR_SSA_PCMCIA 0x00000000 /* Reserved in PCMCIA access */ #define CHCR_SSA_DYNBSZ 0x20000000 /* Dynamic Bus Sizing I/O space */ #define CHCR_SSA_IO8 0x40000000 /* 8-bit I/O space */ #define CHCR_SSA_IO16 0x60000000 /* 16-bit I/O space */ #define CHCR_SSA_CMEM8 0x80000000 /* 8-bit common memory space */ #define CHCR_SSA_CMEM16 0xA0000000 /* 16-bit common memory space */ #define CHCR_SSA_AMEM8 0xC0000000 /* 8-bit attribute memory space */ #define CHCR_SSA_AMEM16 0xE0000000 /* 16-bit attribute memory space */ #define CHCR_STC 0x10000000 /* Source Address Wait Control Select, specifies CS5 or CS6 space wait control for PCMCIA access */ #define CHCR_DSA 0x0E000000 /* Source Address Space Attribute */ #define CHCR_DSA_PCMCIA 0x00000000 /* Reserved in PCMCIA access */ #define CHCR_DSA_DYNBSZ 0x02000000 /* Dynamic Bus Sizing I/O space */ #define CHCR_DSA_IO8 0x04000000 /* 8-bit I/O space */ #define CHCR_DSA_IO16 0x06000000 /* 16-bit I/O space */ #define CHCR_DSA_CMEM8 0x08000000 /* 8-bit common memory space */ #define CHCR_DSA_CMEM16 0x0A000000 /* 16-bit common memory space */ #define CHCR_DSA_AMEM8 0x0C000000 /* 8-bit attribute memory space */ #define CHCR_DSA_AMEM16 0x0E000000 /* 16-bit attribute memory space */ #define CHCR_DTC 0x01000000 /* Destination Address Wait Control Select, specifies CS5 or CS6 space wait control for PCMCIA access */ #define CHCR_DS 0x00080000 /* DREQ\ Select : */ #define CHCR_DS_LOWLVL 0x00000000 /* Low Level Detection */ #define CHCR_DS_FALL 0x00080000 /* Falling Edge Detection */ #define CHCR_RL 0x00040000 /* Request Check Level: */ #define CHCR_RL_ACTH 0x00000000 /* DRAK is an active high out */ #define CHCR_RL_ACTL 0x00040000 /* DRAK is an active low out */ #define CHCR_AM 0x00020000 /* Acknowledge Mode: */ #define CHCR_AM_RD 0x00000000 /* DACK is output in read cycle */ #define CHCR_AM_WR 0x00020000 /* DACK is output in write cycle*/ #define CHCR_AL 0x00010000 /* Acknowledge Level: */ #define CHCR_AL_ACTH 0x00000000 /* DACK is an active high out */ #define CHCR_AL_ACTL 0x00010000 /* DACK is an active low out */ #define CHCR_DM 0x0000C000 /* Destination Address Mode: */ #define CHCR_DM_FIX 0x00000000 /* Destination Addr Fixed */ #define CHCR_DM_INC 0x00004000 /* Destination Addr Incremented */ #define CHCR_DM_DEC 0x00008000 /* Destination Addr Decremented */ #define CHCR_SM 0x00003000 /* Source Address Mode: */ #define CHCR_SM_FIX 0x00000000 /* Source Addr Fixed */ #define CHCR_SM_INC 0x00001000 /* Source Addr Incremented */ #define CHCR_SM_DEC 0x00002000 /* Source Addr Decremented */ #define CHCR_RS 0x00000F00 /* Request Source Select: */ #define CHCR_RS_ER_DA_EA_TO_EA 0x000 /* External Request, Dual Address Mode (External Addr Space-> External Addr Space) */ #define CHCR_RS_ER_SA_EA_TO_ED 0x200 /* External Request, Single Address Mode (External Addr Space -> External Device) */ #define CHCR_RS_ER_SA_ED_TO_EA 0x300 /* External Request, Single Address Mode, (External Device -> External Addr Space)*/ #define CHCR_RS_AR_EA_TO_EA 0x400 /* Auto-Request (External Addr Space -> External Addr Space)*/ #define CHCR_RS_AR_EA_TO_OCP 0x500 /* Auto-Request (External Addr Space -> On-chip Peripheral Module) */ #define CHCR_RS_AR_OCP_TO_EA 0x600 /* Auto-Request (On-chip Peripheral Module -> External Addr Space */ #define CHCR_RS_SCITX_EA_TO_SC 0x800 /* SCI Transmit-Data-Empty intr transfer request (external address space -> SCTDR1) */ #define CHCR_RS_SCIRX_SC_TO_EA 0x900 /* SCI Receive-Data-Full intr transfer request (SCRDR1 -> External Addr Space) */ #define CHCR_RS_SCIFTX_EA_TO_SC 0xA00 /* SCIF Transmit-Data-Empty intr transfer request (external address space -> SCFTDR1) */ #define CHCR_RS_SCIFRX_SC_TO_EA 0xB00 /* SCIF Receive-Data-Full intr transfer request (SCFRDR2 -> External Addr Space) */ #define CHCR_RS_TMU2_EA_TO_EA 0xC00 /* TMU Channel 2 (input capture interrupt), (external address space -> external address space) */ #define CHCR_RS_TMU2_EA_TO_OCP 0xD00 /* TMU Channel 2 (input capture interrupt), (external address space -> on-chip peripheral module) */ #define CHCR_RS_TMU2_OCP_TO_EA 0xE00 /* TMU Channel 2 (input capture interrupt), (on-chip peripheral module -> external address space) */ #define CHCR_TM 0x00000080 /* Transmit mode: */ #define CHCR_TM_CSTEAL 0x00000000 /* Cycle Steal Mode */ #define CHCR_TM_BURST 0x00000080 /* Burst Mode */ #define CHCR_TS 0x00000070 /* Transmit Size: */ #define CHCR_TS_QUAD 0x00000000 /* Quadword Size (64 bits) */ #define CHCR_TS_BYTE 0x00000010 /* Byte Size (8 bit) */ #define CHCR_TS_WORD 0x00000020 /* Word Size (16 bit) */ #define CHCR_TS_LONG 0x00000030 /* Longword Size (32 bit) */ #define CHCR_TS_BLOCK 0x00000040 /* 32-byte block transfer */ #define CHCR_IE 0x00000004 /* Interrupt Enable */ #define CHCR_TE 0x00000002 /* Transfer End */ #define CHCR_DE 0x00000001 /* DMAC Enable */ /* DMA Operation Register - DMAOR */ #define DMAOR_REGOFS 0xA00040 /* offset */ #define DMAOR P4_REG32(DMAOR_REGOFS) #define DMAOR_A7 A7_REG32(DMAOR_REGOFS) #define DMAOR_DDT 0x00008000 /* On-Demand Data Transfer Mode */ #define DMAOR_PR 0x00000300 /* Priority Mode: */ #define DMAOR_PR_0123 0x00000000 /* CH0 > CH1 > CH2 > CH3 */ #define DMAOR_PR_0231 0x00000100 /* CH0 > CH2 > CH3 > CH1 */ #define DMAOR_PR_2013 0x00000200 /* CH2 > CH0 > CH1 > CH3 */ #define DMAOR_PR_RR 0x00000300 /* Round-robin mode */ #define DMAOR_COD 0x00000010 /* Check Overrun for DREQ\ */ #define DMAOR_AE 0x00000004 /* Address Error flag */ #define DMAOR_NMIF 0x00000002 /* NMI Flag */ #define DMAOR_DME 0x00000001 /* DMAC Master Enable */ /* * Serial Communication Interface - SCI * Serial Communication Interface with FIFO - SCIF */ /* SCI Receive Data Register (byte, read-only) - SCRDR1, SCFRDR2 */ #define SCRDR_REGOFS(n) ((n) == 1 ? 0xE00014 : 0xE80014) /* offset */ #define SCRDR(n) P4_REG32(SCRDR_REGOFS(n)) #define SCRDR1 SCRDR(1) #define SCRDR2 SCRDR(2) #define SCRDR_A7(n) A7_REG32(SCRDR_REGOFS(n)) #define SCRDR1_A7 SCRDR_A7(1) #define SCRDR2_A7 SCRDR_A7(2) /* SCI Transmit Data Register (byte) - SCTDR1, SCFTDR2 */ #define SCTDR_REGOFS(n) ((n) == 1 ? 0xE0000C : 0xE8000C) /* offset */ #define SCTDR(n) P4_REG32(SCTDR_REGOFS(n)) #define SCTDR1 SCTDR(1) #define SCTDR2 SCTDR(2) #define SCTDR_A7(n) A7_REG32(SCTDR_REGOFS(n)) #define SCTDR1_A7 SCTDR_A7(1) #define SCTDR2_A7 SCTDR_A7(2) /* SCI Serial Mode Register - SCSMR1(byte), SCSMR2(half) */ #define SCSMR_REGOFS(n) ((n) == 1 ? 0xE00000 : 0xE80000) /* offset */ #define SCSMR(n) P4_REG32(SCSMR_REGOFS(n)) #define SCSMR1 SCSMR(1) #define SCSMR2 SCSMR(2) #define SCSMR_A7(n) A7_REG32(SCSMR_REGOFS(n)) #define SCSMR1_A7 SCSMR_A7(1) #define SCSMR2_A7 SCSMR_A7(2) #define SCSMR1_CA 0x80 /* Communication Mode (C/A\): */ #define SCSMR1_CA_ASYNC 0x00 /* Asynchronous Mode */ #define SCSMR1_CA_SYNC 0x80 /* Synchronous Mode */ #define SCSMR_CHR 0x40 /* Character Length: */ #define SCSMR_CHR_8 0x00 /* 8-bit data */ #define SCSMR_CHR_7 0x40 /* 7-bit data */ #define SCSMR_PE 0x20 /* Parity Enable */ #define SCSMR_PM 0x10 /* Parity Mode: */ #define SCSMR_PM_EVEN 0x00 /* Even Parity */ #define SCSMR_PM_ODD 0x10 /* Odd Parity */ #define SCSMR_STOP 0x08 /* Stop Bit Length: */ #define SCSMR_STOP_1 0x00 /* 1 stop bit */ #define SCSMR_STOP_2 0x08 /* 2 stop bit */ #define SCSMR1_MP 0x04 /* Multiprocessor Mode */ #define SCSMR_CKS 0x03 /* Clock Select */ #define SCSMR_CKS_S 0 #define SCSMR_CKS_DIV1 0x00 /* Periph clock */ #define SCSMR_CKS_DIV4 0x01 /* Periph clock / 4 */ #define SCSMR_CKS_DIV16 0x02 /* Periph clock / 16 */ #define SCSMR_CKS_DIV64 0x03 /* Periph clock / 64 */ /* SCI Serial Control Register - SCSCR1(byte), SCSCR2(half) */ #define SCSCR_REGOFS(n) ((n) == 1 ? 0xE00008 : 0xE80008) /* offset */ #define SCSCR(n) P4_REG32(SCSCR_REGOFS(n)) #define SCSCR1 SCSCR(1) #define SCSCR2 SCSCR(2) #define SCSCR_A7(n) A7_REG32(SCSCR_REGOFS(n)) #define SCSCR1_A7 SCSCR_A7(1) #define SCSCR2_A7 SCSCR_A7(2) #define SCSCR_TIE 0x80 /* Transmit Interrupt Enable */ #define SCSCR_RIE 0x40 /* Receive Interrupt Enable */ #define SCSCR_TE 0x20 /* Transmit Enable */ #define SCSCR_RE 0x10 /* Receive Enable */ #define SCSCR1_MPIE 0x08 /* Multiprocessor Interrupt Enable */ #define SCSCR2_REIE 0x08 /* Receive Error Interrupt Enable */ #define SCSCR1_TEIE 0x04 /* Transmit End Interrupt Enable */ #define SCSCR1_CKE 0x03 /* Clock Enable: */ #define SCSCR_CKE_INTCLK 0x00 /* Use Internal Clock */ #define SCSCR_CKE_EXTCLK 0x02 /* Use External Clock from SCK*/ #define SCSCR1_CKE_ASYNC_SCK_CLKOUT 0x01 /* Use SCK as a clock output in asynchronous mode */ /* SCI Serial Status Register - SCSSR1(byte), SCSSR2(half) */ #define SCSSR_REGOFS(n) ((n) == 1 ? 0xE00010 : 0xE80010) /* offset */ #define SCSSR(n) P4_REG32(SCSSR_REGOFS(n)) #define SCSSR1 SCSSR(1) #define SCSSR2 SCSSR(2) #define SCSSR_A7(n) A7_REG32(SCSSR_REGOFS(n)) #define SCSSR1_A7 SCSSR_A7(1) #define SCSSR2_A7 SCSSR_A7(2) #define SCSSR1_TDRE 0x80 /* Transmit Data Register Empty */ #define SCSSR1_RDRF 0x40 /* Receive Data Register Full */ #define SCSSR1_ORER 0x20 /* Overrun Error */ #define SCSSR1_FER 0x10 /* Framing Error */ #define SCSSR1_PER 0x08 /* Parity Error */ #define SCSSR1_TEND 0x04 /* Transmit End */ #define SCSSR1_MPB 0x02 /* Multiprocessor Bit */ #define SCSSR1_MPBT 0x01 /* Multiprocessor Bit Transfer */ #define SCSSR2_PERN 0xF000 /* Number of Parity Errors */ #define SCSSR2_PERN_S 12 #define SCSSR2_FERN 0x0F00 /* Number of Framing Errors */ #define SCSSR2_FERN_S 8 #define SCSSR2_ER 0x0080 /* Receive Error */ #define SCSSR2_TEND 0x0040 /* Transmit End */ #define SCSSR2_TDFE 0x0020 /* Transmit FIFO Data Empty */ #define SCSSR2_BRK 0x0010 /* Break Detect */ #define SCSSR2_FER 0x0008 /* Framing Error */ #define SCSSR2_PER 0x0004 /* Parity Error */ #define SCSSR2_RDF 0x0002 /* Receive FIFO Data Full */ #define SCSSR2_DR 0x0001 /* Receive Data Ready */ /* SCI Serial Port Register - SCSPTR1(byte) */ #define SCSPTR1_REGOFS 0xE0001C /* offset */ #define SCSPTR1 P4_REG32(SCSPTR1_REGOFS) #define SCSPTR1_A7 A7_REG32(SCSPTR1_REGOFS) #define SCSPTR1_EIO 0x80 /* Error Interrupt Only */ #define SCSPTR1_SPB1IO 0x08 /* 1: Output SPB1DT bit to SCK pin */ #define SCSPTR1_SPB1DT 0x04 /* Serial Port Clock Port Data */ #define SCSPTR1_SPB0IO 0x02 /* 1: Output SPB0DT bit to TxD pin */ #define SCSPTR1_SPB0DT 0x01 /* Serial Port Break Data */ /* SCIF Serial Port Register - SCSPTR2(half) */ #define SCSPTR2_REGOFS 0xE80020 /* offset */ #define SCSPTR2 P4_REG32(SCSPTR2_REGOFS) #define SCSPTR2_A7 A7_REG32(SCSPTR2_REGOFS) #define SCSPTR2_RTSIO 0x0080 /* 1: Output RTSDT bit to RTS2\ pin */ #define SCSPTR2_RTSDT 0x0040 /* RTS Port Data */ #define SCSPTR2_CTSIO 0x0020 /* 1: Output CTSDT bit to CTS2\ pin */ #define SCSPTR2_CTSDT 0x0010 /* CTS Port Data */ #define SCSPTR2_SPB2IO 0x0002 /* 1: Output SPBDT bit to TxD2 pin */ #define SCSPTR2_SPB2DT 0x0001 /* Serial Port Break Data */ /* SCI Bit Rate Register - SCBRR1(byte), SCBRR2(byte) */ #define SCBRR_REGOFS(n) ((n) == 1 ? 0xE00004 : 0xE80004) /* offset */ #define SCBRR(n) P4_REG32(SCBRR_REGOFS(n)) #define SCBRR1 SCBRR_P4(1) #define SCBRR2 SCBRR_P4(2) #define SCBRR_A7(n) A7_REG32(SCBRR_REGOFS(n)) #define SCBRR1_A7 SCBRR(1) #define SCBRR2_A7 SCBRR(2) /* SCIF FIFO Control Register - SCFCR2(half) */ #define SCFCR2_REGOFS 0xE80018 /* offset */ #define SCFCR2 P4_REG32(SCFCR2_REGOFS) #define SCFCR2_A7 A7_REG32(SCFCR2_REGOFS) #define SCFCR2_RSTRG 0x700 /* RTS2\ Output Active Trigger; RTS2\ signal goes to high level when the number of received data stored in FIFO exceeds the trigger number */ #define SCFCR2_RSTRG_15 0x000 /* 15 bytes */ #define SCFCR2_RSTRG_1 0x000 /* 1 byte */ #define SCFCR2_RSTRG_4 0x000 /* 4 bytes */ #define SCFCR2_RSTRG_6 0x000 /* 6 bytes */ #define SCFCR2_RSTRG_8 0x000 /* 8 bytes */ #define SCFCR2_RSTRG_10 0x000 /* 10 bytes */ #define SCFCR2_RSTRG_14 0x000 /* 14 bytes */ #define SCFCR2_RTRG 0x0C0 /* Receive FIFO Data Number Trigger, Receive Data Full (RDF) Flag sets when number of receive data bytes is equal or greater than the trigger number */ #define SCFCR2_RTRG_1 0x000 /* 1 byte */ #define SCFCR2_RTRG_4 0x040 /* 4 bytes */ #define SCFCR2_RTRG_8 0x080 /* 8 bytes */ #define SCFCR2_RTRG_14 0x0C0 /* 14 bytes */ #define SCFCR2_TTRG 0x030 /* Transmit FIFO Data Number Trigger, Transmit FIFO Data Register Empty (TDFE) flag sets when the number of remaining transmit data bytes is equal or less than the trigger number */ #define SCFCR2_TTRG_8 0x000 /* 8 bytes */ #define SCFCR2_TTRG_4 0x010 /* 4 bytes */ #define SCFCR2_TTRG_2 0x020 /* 2 bytes */ #define SCFCR2_TTRG_1 0x030 /* 1 byte */ #define SCFCR2_MCE 0x008 /* Modem Control Enable */ #define SCFCR2_TFRST 0x004 /* Transmit FIFO Data Register Reset, invalidates the transmit data in the transmit FIFO */ #define SCFCR2_RFRST 0x002 /* Receive FIFO Data Register Reset, invalidates the receive data in the receive FIFO data register and resets it to the empty state */ #define SCFCR2_LOOP 0x001 /* Loopback Test */ /* SCIF FIFO Data Count Register - SCFDR2(half, read-only) */ #define SCFDR2_REGOFS 0xE8001C /* offset */ #define SCFDR2 P4_REG32(SCFDR2_REGOFS) #define SCFDR2_A7 A7_REG32(SCFDR2_REGOFS) #define SCFDR2_T 0x1F00 /* Number of untransmitted data bytes in transmit FIFO */ #define SCFDR2_T_S 8 #define SCFDR2_R 0x001F /* Number of received data bytes in receive FIFO */ #define SCFDR2_R_S 0 /* SCIF Line Status Register - SCLSR2(half, read-only) */ #define SCLSR2_REGOFS 0xE80024 /* offset */ #define SCLSR2 P4_REG32(SCLSR2_REGOFS) #define SCLSR2_A7 A7_REG32(SCLSR2_REGOFS) #define SCLSR2_ORER 0x0001 /* Overrun Error */ /* * SCI-based Smart Card Interface */ /* Smart Card Mode Register - SCSCMR1(byte) */ #define SCSCMR1_REGOFS 0xE00018 /* offset */ #define SCSCMR1 P4_REG32(SCSCMR1_REGOFS) #define SCSCMR1_A7 A7_REG32(SCSCMR1_REGOFS) #define SCSCMR1_SDIR 0x08 /* Smart Card Data Transfer Direction: */ #define SCSCMR1_SDIR_LSBF 0x00 /* LSB-first */ #define SCSCMR1_SDIR_MSBF 0x08 /* MSB-first */ #define SCSCMR1_SINV 0x04 /* Smart Card Data Inversion */ #define SCSCMR1_SMIF 0x01 /* Smart Card Interface Mode Select */ /* Smart-card specific bits in other registers */ /* SCSMR1: */ #define SCSMR1_GSM 0x80 /* GSM mode select */ /* SCSSR1: */ #define SCSSR1_ERS 0x10 /* Error Signal Status */ /* * I/O Ports */ /* Port Control Register A - PCTRA */ #define PCTRA_REGOFS 0x80002C /* offset */ #define PCTRA P4_REG32(PCTRA_REGOFS) #define PCTRA_A7 A7_REG32(PCTRA_REGOFS) #define PCTRA_PBPUP(n) 0 /* Bit n is pulled up */ #define PCTRA_PBNPUP(n) (1 << ((n)*2+1)) /* Bit n is not pulled up */ #define PCTRA_PBINP(n) 0 /* Bit n is an input */ #define PCTRA_PBOUT(n) (1 << ((n)*2)) /* Bit n is an output */ /* Port Data Register A - PDTRA(half) */ #define PDTRA_REGOFS 0x800030 /* offset */ #define PDTRA P4_REG32(PDTRA_REGOFS) #define PDTRA_A7 A7_REG32(PDTRA_REGOFS) #define PDTRA_BIT(n) (1 << (n)) /* Port Control Register B - PCTRB */ #define PCTRB_REGOFS 0x800040 /* offset */ #define PCTRB P4_REG32(PCTRB_REGOFS) #define PCTRB_A7 A7_REG32(PCTRB_REGOFS) #define PCTRB_PBPUP(n) 0 /* Bit n is pulled up */ #define PCTRB_PBNPUP(n) (1 << ((n-16)*2+1)) /* Bit n is not pulled up */ #define PCTRB_PBINP(n) 0 /* Bit n is an input */ #define PCTRB_PBOUT(n) (1 << ((n-16)*2)) /* Bit n is an output */ /* Port Data Register B - PDTRB(half) */ #define PDTRB_REGOFS 0x800044 /* offset */ #define PDTRB P4_REG32(PDTRB_REGOFS) #define PDTRB_A7 A7_REG32(PDTRB_REGOFS) #define PDTRB_BIT(n) (1 << ((n)-16)) /* GPIO Interrupt Control Register - GPIOIC(half) */ #define GPIOIC_REGOFS 0x800048 /* offset */ #define GPIOIC P4_REG32(GPIOIC_REGOFS) #define GPIOIC_A7 A7_REG32(GPIOIC_REGOFS) #define GPIOIC_PTIREN(n) (1 << (n)) /* Port n is used as a GPIO int */ /* * Interrupt Controller - INTC */ /* Interrupt Control Register - ICR (half) */ #define ICR_REGOFS 0xD00000 /* offset */ #define ICR P4_REG32(ICR_REGOFS) #define ICR_A7 A7_REG32(ICR_REGOFS) #define ICR_NMIL 0x8000 /* NMI Input Level */ #define ICR_MAI 0x4000 /* NMI Interrupt Mask */ #define ICR_NMIB 0x0200 /* NMI Block Mode: */ #define ICR_NMIB_BLK 0x0000 /* NMI requests held pending while SR.BL bit is set to 1 */ #define ICR_NMIB_NBLK 0x0200 /* NMI requests detected when SR.BL bit set to 1 */ #define ICR_NMIE 0x0100 /* NMI Edge Select: */ #define ICR_NMIE_FALL 0x0000 /* Interrupt request detected on falling edge of NMI input */ #define ICR_NMIE_RISE 0x0100 /* Interrupt request detected on rising edge of NMI input */ #define ICR_IRLM 0x0080 /* IRL Pin Mode: */ #define ICR_IRLM_ENC 0x0000 /* IRL\ pins used as a level-encoded interrupt requests */ #define ICR_IRLM_RAW 0x0080 /* IRL\ pins used as a four independent interrupt requests */ /* Interrupt Priority Register A - IPRA (half) */ #define IPRA_REGOFS 0xD00004 /* offset */ #define IPRA P4_REG32(IPRA_REGOFS) #define IPRA_A7 A7_REG32(IPRA_REGOFS) #define IPRA_TMU0 0xF000 /* TMU0 interrupt priority */ #define IPRA_TMU0_S 12 #define IPRA_TMU1 0x0F00 /* TMU1 interrupt priority */ #define IPRA_TMU1_S 8 #define IPRA_TMU2 0x00F0 /* TMU2 interrupt priority */ #define IPRA_TMU2_S 4 #define IPRA_RTC 0x000F /* RTC interrupt priority */ #define IPRA_RTC_S 0 /* Interrupt Priority Register B - IPRB (half) */ #define IPRB_REGOFS 0xD00008 /* offset */ #define IPRB P4_REG32(IPRB_REGOFS) #define IPRB_A7 A7_REG32(IPRB_REGOFS) #define IPRB_WDT 0xF000 /* WDT interrupt priority */ #define IPRB_WDT_S 12 #define IPRB_REF 0x0F00 /* Memory Refresh unit interrupt priority */ #define IPRB_REF_S 8 #define IPRB_SCI1 0x00F0 /* SCI1 interrupt priority */ #define IPRB_SCI1_S 4 /* Interrupt Priority Register C - IPRC (half) */ #define IPRC_REGOFS 0xD00004 /* offset */ #define IPRC P4_REG32(IPRC_REGOFS) #define IPRC_A7 A7_REG32(IPRC_REGOFS) #define IPRC_GPIO 0xF000 /* GPIO interrupt priority */ #define IPRC_GPIO_S 12 #define IPRC_DMAC 0x0F00 /* DMAC interrupt priority */ #define IPRC_DMAC_S 8 #define IPRC_SCIF 0x00F0 /* SCIF interrupt priority */ #define IPRC_SCIF_S 4 #define IPRC_HUDI 0x000F /* H-UDI interrupt priority */ #define IPRC_HUDI_S 0 /* * User Break Controller registers */ #ifndef BARA #define BARA 0x200000 /* Break address regiser A */ #define BAMRA 0x200004 /* Break address mask regiser A */ #define BBRA 0x200008 /* Break bus cycle regiser A */ #define BARB 0x20000c /* Break address regiser B */ #define BAMRB 0x200010 /* Break address mask regiser B */ #define BBRB 0x200014 /* Break bus cycle regiser B */ #define BASRB 0x000018 /* Break ASID regiser B */ #define BDRB 0x200018 /* Break data regiser B */ #define BDMRB 0x20001c /* Break data mask regiser B */ #define BRCR 0x200020 /* Break control register */ #define BRCR_UDBE 0x0001 /* User break debug enable bit */ #endif /* BARA */ #endif /* __SH7750_REGS_H__ */ <file_sep>/lib/SDL_gui/RealScreen.cc // Modified by SWAT // http://www.dc-swat.ru #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" extern "C" { void ScreenChanged(); void UpdateActiveMouseCursor(); } #define MAX_UPDATES 200 GUI_RealScreen::GUI_RealScreen(const char *aname, SDL_Surface *surface) : GUI_Screen(aname, surface) { n_updates = 0; //updates = new SDL_Rect[MAX_UPDATES]; } GUI_RealScreen::~GUI_RealScreen(void) { //delete [] updates; } void GUI_RealScreen::FlushUpdates(void) { if (n_updates) { n_updates = 0; ScreenChanged(); UpdateActiveMouseCursor(); } } /* return true if r1 is inside r2 */ /* static int inside(const SDL_Rect *r1, const SDL_Rect *r2) { return r1->x >= r2->x && r1->x + r1->w <= r2->x + r2->w && r1->y >= r2->y && r1->y + r1->h <= r2->y + r2->h; } */ void GUI_RealScreen::UpdateRect(const SDL_Rect *r) { #if 0 if (r->x < 0 || r->y < 0 || r->x + r->w > screen_surface->GetWidth() || r->y + r->h > screen_surface->GetHeight()) { printf("Bad UpdateRect x=%d y=%d w=%d h=%d screen w=%d h=%d\n", r->x, r->y, r->w, r->h, screen_surface->GetWidth(), screen_surface->GetHeight()); //abort(); return; } int i; for (i=0; i<n_updates; i++) { /* if the new rect is inside one that is already */ /* being updated, then just ignore it. */ if (inside(r, &updates[i])) return; /* if the new rect contains a rect already being */ /* updated, then replace the new rect. */ /* FIXME: ideally, it should remove all rects which are inside */ if (inside(&updates[i], r)) { updates[i] = *r; return; } } updates[n_updates++] = *r; if (n_updates >= MAX_UPDATES) FlushUpdates(); #else n_updates++; #endif } void GUI_RealScreen::Update(int force) { // if (screen_surface->IsDoubleBuffered()) // force = 1; GUI_Screen::Update(force); // if (screen_surface->IsDoubleBuffered()) // ScreenChanged(); //screen_surface->Flip(); // FlushUpdates(); } extern "C" { void GUI_RealScreenUpdate(GUI_Screen *screen, int force) { //screen->Update(force); } // void GUI_RealScreenDoUpdate(GUI_Screen *screen, int force) // { // screen->DoUpdate(force); // } void GUI_RealScreenUpdateRect(GUI_Screen *screen, const SDL_Rect *r) { //screen->UpdateRect(r); } GUI_Screen *GUI_RealScreenCreate(const char *aname, SDL_Surface *surface) { return new GUI_RealScreen(aname, surface); } void GUI_RealScreenFlushUpdates(GUI_Screen *screen) { //screen->FlushUpdates(); } } <file_sep>/applications/region_changer/modules/flashrom.c /* Region Changer ##version## flashrom.c Copyright (C)2007-2014 SWAT */ #include "rc.h" int flash_clear(int block) { int size, start; if (flashrom_info(block, &start, &size) < 0) { ds_printf("DS_ERROR: Get offset error\n"); return -1; } if (flashrom_delete(start) < 0) { ds_printf("DS_ERROR: Deleting old flash factory data error\n"); return -1; } return 0; } int flash_write_factory(uint8 *data) { int size, start; if (flashrom_info(FLASHROM_PT_SYSTEM, &start, &size) < 0) { printf("Get offset error\n"); return -1; } if (flashrom_delete(start) < 0) { ds_printf("DS_ERROR: Deleting old flash factory data error\n"); return -1; } if (flashrom_write(start, data, size) < 0) { ds_printf("DS_ERROR: Write new flash factory data error\n"); return -1; } return 0; } uint8 *flash_read_factory() { int size, start; uint8 *data; if (flashrom_info(FLASHROM_PT_SYSTEM, &start, &size) < 0) { size = 8192; data = (uint8 *) malloc(size); if (data == NULL) { ds_printf("DS_ERROR: Not enough of memory\n"); return NULL; } memcpy(data, (uint8 *)0x0021A000, size); } else { data = (uint8 *) malloc(size); if (data == NULL) { ds_printf("DS_ERROR: Not enough of memory\n"); return NULL; } if (flashrom_read(start, data, size) < 0) { ds_printf("DS_ERROR: Flash read lash factory failed\n"); return NULL; } } return data; } /* Read file to RAM and write to flashrom */ int flash_write_file(const char *filename) { file_t fd; uint8 *data = NULL; size_t size; fd = fs_open(filename, O_RDONLY); if (fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open %s\n", filename); return -1; } size = fs_total(fd); if (size > 0x20000) { size = 0x20000; } data = (uint8*) memalign(32, size); if (data == NULL) { ds_printf("DS_ERROR: Not enough of memory\n"); goto error; } if (fs_read(fd, data, size) < 0) { ds_printf("DS_ERROR: Error in reading file: %d\n", errno); goto error; } if (flashrom_write(0, data, size) < 0) { ds_printf("DS_ERROR: Write new flash data error\n"); goto error; } fs_close(fd); free(data); return 0; error: fs_close(fd); if(data) free(data); return -1; } /* Read flashrom to RAM and write to file */ int flash_read_file(const char *filename) { file_t fd; uint8 *data = NULL; size_t size = 0x20000; fd = fs_open(filename, O_WRONLY); if (fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open %s\n", filename); return -1; } data = (uint8*) memalign(32, size); if (data == NULL) { ds_printf("DS_ERROR: Not enough of memory\n"); goto error; } if (flashrom_read(0, data, size) < 0) { ds_printf("DS_ERROR: Read flash data error\n"); goto error; } if (fs_write(fd, data, size) < 0) { ds_printf("DS_ERROR: Error in writing to file: %d\n", errno); goto error; } fs_close(fd); free(data); return 0; error: fs_close(fd); if(data) free(data); return -1; } <file_sep>/commands/ping/main.c /* DreamShell ##version## main.c - Ping Copyright (C) 2009 <NAME> Copyright (C) 2009-2019 SWAT */ #include "ds.h" #include <netdb.h> #define DATA_SIZE 56 int main(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s host\n", argv[0]); return CMD_NO_ARG; } uint8 ip[4]; int i, scan_ip[4] = { 0, 0, 0 ,0 }; uint8 data[DATA_SIZE]; char *name = argv[1]; struct hostent *hent; struct in_addr addr; i = sscanf(name, "%d.%d.%d.%d", &scan_ip[0], &scan_ip[1], &scan_ip[2], &scan_ip[3]); if (i < 4) { hent = gethostbyname((const char *)name); if(hent) { memcpy(&addr, hent->h_addr, hent->h_length); name = inet_ntoa(addr); ds_printf("DS_OK: %s %s\n", hent->h_name, name); } else { ds_printf("DS_ERROR: Can't lookup host %s\n", name); return CMD_ERROR; } i = sscanf(name, "%d.%d.%d.%d", &scan_ip[0], &scan_ip[1], &scan_ip[2], &scan_ip[3]); if (i < 4) { ds_printf("DS_ERROR: Bad format: %d %s\n", i, name); return CMD_ERROR; } } for(i = 0; i < 4; ++i) { ip[i] = (uint8)(scan_ip[i] & 0xff); } /* Fill in the data for the ping packet... this is pretty simple and doesn't really have any real meaning... */ for(i = 0; i < DATA_SIZE; ++i) { data[i] = (uint8)i; } ds_printf("DS_PROCESS: Connecting to %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]); /* Send out 4 pings, waiting 250ms between attempts. */ for(i = 0; i < 4; ++i) { if (net_icmp_send_echo(net_default_dev, ip, 0, i, data, DATA_SIZE) < 0) { ds_printf("DS_ERROR: send echo error %d\n", errno); return CMD_ERROR; } thd_sleep(250); } ds_printf("DS_OK: Done.\n"); return CMD_OK; } <file_sep>/modules/isofs/internal.h /** * \file internal.h * \brief isofs utils * \date 2014-2016 * \author SWAT www.dc-swat.ru */ #ifndef _ISOFS_INTERNAL_H #define _ISOFS_INTERNAL_H #include <arch/types.h> #include <isofs/ciso.h> #define TRACK_FLAG_PREEMPH 0x10 /* Pre-emphasis (audio only) */ #define TRACK_FLAG_COPYPERM 0x20 /* Copy permitted */ #define TRACK_FLAG_DATA 0x40 /* Data track */ #define TRACK_FLAG_FOURCHAN 0x80 /* 4-channel audio */ int read_sectors_data(file_t fd, uint32 sector_count, uint16 sector_size, uint8 *buff); /** * Spoof TOC for GD session 1 */ void spoof_toc_3track_gd_session_1(CDROM_TOC *toc); /** * Spoof TOC for GD session 2 */ void spoof_toc_3track_gd_session_2(CDROM_TOC *toc); void spoof_multi_toc_3track_gd(CDROM_TOC *toc); void spoof_multi_toc_iso(CDROM_TOC *toc, file_t fd, uint32 lba); void spoof_multi_toc_cso(CDROM_TOC *toc, CISO_header_t *hdr, uint32 lba); #endif /* _ISOFS_INTERNAL_H */ <file_sep>/modules/mp3/libmp3/xingmp3/cupl3.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** cupL3.c *************************************************** unpack Layer III mod 8/18/97 bugfix crc problem mod 10/9/97 add band_limit12 for short blocks mod 10/22/97 zero buf_ptrs in init mod 5/15/98 mpeg 2.5 mod 8/19/98 decode 22 sf bands ******************************************************************/ /*--------------------------------------- TO DO: Test mixed blocks (mixed long/short) No mixed blocks in mpeg-1 test stream being used for development -----------------------------------------*/ #include <float.h> #include <math.h> #include <string.h> #include "L3.h" #include "mhead.h" /* mpeg header structure */ #include "jdw.h" #include "protos.h" /*====================================================================*/ static int mp_sr20_table[2][4] = {{441, 480, 320, -999}, {882, 960, 640, -999}}; static int mp_br_tableL3[2][16] = {{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, /* mpeg 2 */ {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0}}; /*====================================================================*/ /*-- global band tables */ /*-- short portion is 3*x !! --*/ /*====================================================================*/ /*---------------------------------*/ /*---------------------------------*/ /*- sample union of int/float sample[ch][gr][576] */ /* Sample is the same as cup.sample */ void sbt_dual_L3(MPEG *m, float *sample, short *pcm, int n); IN_OUT L3audio_decode_MPEG1(void *mv, unsigned char *bs, unsigned char *pcm); IN_OUT L3audio_decode_MPEG2(void *mv, unsigned char *bs, unsigned char *pcm); /* static DECODE_FUNCTION decode_function = L3audio_decode_MPEG1; */ /*====================================================================*/ /* get bits from bitstream in endian independent way */ /*------------- initialize bit getter -------------*/ static void bitget_init(MPEG *m, unsigned char *buf) { m->cupl.bitdat.bs_ptr0 = m->cupl.bitdat.bs_ptr = buf; m->cupl.bitdat.bits = 0; m->cupl.bitdat.bitbuf = 0; } /*------------- initialize bit getter -------------*/ static void bitget_init_end(MPEG *m, unsigned char *buf_end) { m->cupl.bitdat.bs_ptr_end = buf_end; } /*------------- get n bits from bitstream -------------*/ int bitget_bits_used(MPEG *m) { int n; /* compute bits used from last init call */ n = ((m->cupl.bitdat.bs_ptr - m->cupl.bitdat.bs_ptr0) << 3) - m->cupl.bitdat.bits; return n; } /*------------- get n bits from bitstream -------------*/ unsigned int bitget(MPEG *m, int n) { unsigned int x; if (m->cupl.bitdat.bits < n) { /* refill bit buf if necessary */ while (m->cupl.bitdat.bits <= 24) { m->cupl.bitdat.bitbuf = (m->cupl.bitdat.bitbuf << 8) | *m->cupl.bitdat.bs_ptr++; m->cupl.bitdat.bits += 8; } } m->cupl.bitdat.bits -= n; x = m->cupl.bitdat.bitbuf >> m->cupl.bitdat.bits; m->cupl.bitdat.bitbuf -= x << m->cupl.bitdat.bits; return x; } /*====================================================================*/ static void Xform_mono(void *mv, void *pcm, int igr) { MPEG *m = mv; int igr_prev, n1, n2; /*--- hybrid + sbt ---*/ n1 = n2 = m->cupl.nsamp[igr][0]; /* total number bands */ if (m->cupl.side_info.gr[igr][0].block_type == 2) { /* long bands */ n1 = 0; if (m->cupl.side_info.gr[igr][0].mixed_block_flag) n1 = m->cupl.sfBandIndex[0][m->cupl.ncbl_mixed - 1]; } if (n1 > m->cupl.band_limit) n1 = m->cupl.band_limit; if (n2 > m->cupl.band_limit) n2 = m->cupl.band_limit; igr_prev = igr ^ 1; m->cupl.nsamp[igr][0] = hybrid(m,m->cupl.sample[0][igr], m->cupl.sample[0][igr_prev], m->cupl.yout, m->cupl.side_info.gr[igr][0].block_type, n1, n2, m->cupl.nsamp[igr_prev][0]); FreqInvert(m->cupl.yout, m->cupl.nsamp[igr][0]); m->cupl.sbt_L3(m,m->cupl.yout, pcm, 0); } /*--------------------------------------------------------------------*/ static void Xform_dual_right(void *mv, void *pcm, int igr) { MPEG *m = mv; int igr_prev, n1, n2; /*--- hybrid + sbt ---*/ n1 = n2 = m->cupl.nsamp[igr][1]; /* total number bands */ if (m->cupl.side_info.gr[igr][1].block_type == 2) { /* long bands */ n1 = 0; if (m->cupl.side_info.gr[igr][1].mixed_block_flag) n1 = m->cupl.sfBandIndex[0][m->cupl.ncbl_mixed - 1]; } if (n1 > m->cupl.band_limit) n1 = m->cupl.band_limit; if (n2 > m->cupl.band_limit) n2 = m->cupl.band_limit; igr_prev = igr ^ 1; m->cupl.nsamp[igr][1] = hybrid(m,m->cupl.sample[1][igr], m->cupl.sample[1][igr_prev], m->cupl.yout, m->cupl.side_info.gr[igr][1].block_type, n1, n2, m->cupl.nsamp[igr_prev][1]); FreqInvert(m->cupl.yout, m->cupl.nsamp[igr][1]); m->cupl.sbt_L3(m,m->cupl.yout, pcm, 0); } /*--------------------------------------------------------------------*/ static void Xform_dual(void *mv, void *pcm, int igr) { MPEG *m = mv; int ch; int igr_prev, n1, n2; /*--- hybrid + sbt ---*/ igr_prev = igr ^ 1; for (ch = 0; ch < m->cupl.nchan; ch++) { n1 = n2 = m->cupl.nsamp[igr][ch]; /* total number bands */ if (m->cupl.side_info.gr[igr][ch].block_type == 2) { /* long bands */ n1 = 0; if (m->cupl.side_info.gr[igr][ch].mixed_block_flag) n1 = m->cupl.sfBandIndex[0][m->cupl.ncbl_mixed - 1]; } if (n1 > m->cupl.band_limit) n1 = m->cupl.band_limit; if (n2 > m->cupl.band_limit) n2 = m->cupl.band_limit; m->cupl.nsamp[igr][ch] = hybrid(m,m->cupl.sample[ch][igr], m->cupl.sample[ch][igr_prev], m->cupl.yout, m->cupl.side_info.gr[igr][ch].block_type, n1, n2, m->cupl.nsamp[igr_prev][ch]); FreqInvert(m->cupl.yout, m->cupl.nsamp[igr][ch]); m->cupl.sbt_L3(m,m->cupl.yout, pcm, ch); } } /*--------------------------------------------------------------------*/ static void Xform_dual_mono(void *mv, void *pcm, int igr) { MPEG *m = mv; int igr_prev, n1, n2, n3; /*--- hybrid + sbt ---*/ igr_prev = igr ^ 1; if ((m->cupl.side_info.gr[igr][0].block_type == m->cupl.side_info.gr[igr][1].block_type) && (m->cupl.side_info.gr[igr][0].mixed_block_flag == 0) && (m->cupl.side_info.gr[igr][1].mixed_block_flag == 0)) { n2 = m->cupl.nsamp[igr][0]; /* total number bands max of L R */ if (n2 < m->cupl.nsamp[igr][1]) n2 = m->cupl.nsamp[igr][1]; if (n2 > m->cupl.band_limit) n2 = m->cupl.band_limit; n1 = n2; /* n1 = number long bands */ if (m->cupl.side_info.gr[igr][0].block_type == 2) n1 = 0; sum_f_bands(m->cupl.sample[0][igr], m->cupl.sample[1][igr], n2); n3 = m->cupl.nsamp[igr][0] = hybrid(m,m->cupl.sample[0][igr], m->cupl.sample[0][igr_prev], m->cupl.yout, m->cupl.side_info.gr[igr][0].block_type, n1, n2, m->cupl.nsamp[igr_prev][0]); } else { /* transform and then sum (not tested - never happens in test) */ /*-- left chan --*/ n1 = n2 = m->cupl.nsamp[igr][0]; /* total number bands */ if (m->cupl.side_info.gr[igr][0].block_type == 2) { n1 = 0; /* long bands */ if (m->cupl.side_info.gr[igr][0].mixed_block_flag) n1 = m->cupl.sfBandIndex[0][m->cupl.ncbl_mixed - 1]; } n3 = m->cupl.nsamp[igr][0] = hybrid(m,m->cupl.sample[0][igr], m->cupl.sample[0][igr_prev], m->cupl.yout, m->cupl.side_info.gr[igr][0].block_type, n1, n2, m->cupl.nsamp[igr_prev][0]); /*-- right chan --*/ n1 = n2 = m->cupl.nsamp[igr][1]; /* total number bands */ if (m->cupl.side_info.gr[igr][1].block_type == 2) { n1 = 0; /* long bands */ if (m->cupl.side_info.gr[igr][1].mixed_block_flag) n1 = m->cupl.sfBandIndex[0][m->cupl.ncbl_mixed - 1]; } m->cupl.nsamp[igr][1] = hybrid_sum(m, m->cupl.sample[1][igr], m->cupl.sample[0][igr], m->cupl.yout, m->cupl.side_info.gr[igr][1].block_type, n1, n2); if (n3 < m->cupl.nsamp[igr][1]) n1 = m->cupl.nsamp[igr][1]; } /*--------*/ FreqInvert(m->cupl.yout, n3); m->cupl.sbt_L3(m,m->cupl.yout, pcm, 0); } /*--------------------------------------------------------------------*/ /*====================================================================*/ static int unpack_side_MPEG1(MPEG *m) { int prot; int br_index; int igr, ch; int side_bytes; /* decode partial header plus initial side info */ /* at entry bit getter points at id, sync skipped by caller */ m->cupl.id = bitget(m, 1); /* id */ bitget(m, 2); /* skip layer */ prot = bitget(m, 1); /* bitget prot bit */ br_index = bitget(m, 4); m->cupl.sr_index = bitget(m, 2); m->cupl.pad = bitget(m, 1); bitget(m, 1); /* skip to mode */ m->cupl.side_info.mode = bitget(m, 2); /* mode */ m->cupl.side_info.mode_ext = bitget(m, 2); /* mode ext */ if (m->cupl.side_info.mode != 1) m->cupl.side_info.mode_ext = 0; /* adjust global gain in ms mode to avoid having to mult by 1/sqrt(2) */ m->cupl.ms_mode = m->cupl.side_info.mode_ext >> 1; m->cupl.is_mode = m->cupl.side_info.mode_ext & 1; m->cupl.crcbytes = 0; if (prot) bitget(m, 4); /* skip to data */ else { bitget(m, 20); /* skip crc */ m->cupl.crcbytes = 2; } if (br_index > 0) /* framebytes fixed for free format */ { m->cupl.framebytes = 2880 * mp_br_tableL3[m->cupl.id][br_index] / mp_sr20_table[m->cupl.id][m->cupl.sr_index]; } m->cupl.side_info.main_data_begin = bitget(m, 9); if (m->cupl.side_info.mode == 3) { m->cupl.side_info.private_bits = bitget(m, 5); m->cupl.nchan = 1; m->cupl.stereo_flag = 0; side_bytes = (4 + 17); /*-- with header --*/ } else { m->cupl.side_info.private_bits = bitget(m, 3); m->cupl.nchan = 2; m->cupl.stereo_flag = 1; side_bytes = (4 + 32); /*-- with header --*/ } for (ch = 0; ch < m->cupl.nchan; ch++) m->cupl.side_info.scfsi[ch] = bitget(m, 4); /* this always 0 (both igr) for short blocks */ for (igr = 0; igr < 2; igr++) { for (ch = 0; ch < m->cupl.nchan; ch++) { m->cupl.side_info.gr[igr][ch].part2_3_length = bitget(m, 12); m->cupl.side_info.gr[igr][ch].big_values = bitget(m, 9); if (m->cupl.side_info.gr[igr][ch].big_values > 288) return -1; m->cupl.side_info.gr[igr][ch].global_gain = bitget(m, 8) + m->cupl.gain_adjust; if (m->cupl.ms_mode) m->cupl.side_info.gr[igr][ch].global_gain -= 2; m->cupl.side_info.gr[igr][ch].scalefac_compress = bitget(m, 4); m->cupl.side_info.gr[igr][ch].window_switching_flag = bitget(m, 1); if (m->cupl.side_info.gr[igr][ch].window_switching_flag) { m->cupl.side_info.gr[igr][ch].block_type = bitget(m, 2); m->cupl.side_info.gr[igr][ch].mixed_block_flag = bitget(m, 1); m->cupl.side_info.gr[igr][ch].table_select[0] = bitget(m, 5); m->cupl.side_info.gr[igr][ch].table_select[1] = bitget(m, 5); m->cupl.side_info.gr[igr][ch].subblock_gain[0] = bitget(m, 3); m->cupl.side_info.gr[igr][ch].subblock_gain[1] = bitget(m, 3); m->cupl.side_info.gr[igr][ch].subblock_gain[2] = bitget(m, 3); /* region count set in terms of long block cb's/bands */ /* r1 set so r0+r1+1 = 21 (lookup produces 576 bands ) */ /* if(window_switching_flag) always 36 samples in region0 */ m->cupl.side_info.gr[igr][ch].region0_count = (8 - 1); /* 36 samples */ m->cupl.side_info.gr[igr][ch].region1_count = 20 - (8 - 1); } else { m->cupl.side_info.gr[igr][ch].mixed_block_flag = 0; m->cupl.side_info.gr[igr][ch].block_type = 0; m->cupl.side_info.gr[igr][ch].table_select[0] = bitget(m, 5); m->cupl.side_info.gr[igr][ch].table_select[1] = bitget(m, 5); m->cupl.side_info.gr[igr][ch].table_select[2] = bitget(m, 5); m->cupl.side_info.gr[igr][ch].region0_count = bitget(m, 4); m->cupl.side_info.gr[igr][ch].region1_count = bitget(m, 3); } m->cupl.side_info.gr[igr][ch].preflag = bitget(m, 1); m->cupl.side_info.gr[igr][ch].scalefac_scale = bitget(m, 1); m->cupl.side_info.gr[igr][ch].count1table_select = bitget(m, 1); } } /* return bytes in header + side info */ return side_bytes; } /*====================================================================*/ static int unpack_side_MPEG2(MPEG *m, int igr) { int prot; int br_index; int ch; int side_bytes; /* decode partial header plus initial side info */ /* at entry bit getter points at id, sync skipped by caller */ m->cupl.id = bitget(m, 1); /* id */ bitget(m, 2); /* skip layer */ prot = bitget(m, 1); /* bitget prot bit */ br_index = bitget(m, 4); m->cupl.sr_index = bitget(m, 2); m->cupl.pad = bitget(m, 1); bitget(m, 1); /* skip to mode */ m->cupl.side_info.mode = bitget(m, 2); /* mode */ m->cupl.side_info.mode_ext = bitget(m, 2); /* mode ext */ if (m->cupl.side_info.mode != 1) m->cupl.side_info.mode_ext = 0; /* adjust global gain in ms mode to avoid having to mult by 1/sqrt(2) */ m->cupl.ms_mode = m->cupl.side_info.mode_ext >> 1; m->cupl.is_mode = m->cupl.side_info.mode_ext & 1; m->cupl.crcbytes = 0; if (prot) bitget(m, 4); /* skip to data */ else { bitget(m, 20); /* skip crc */ m->cupl.crcbytes = 2; } if (br_index > 0) { /* framebytes fixed for free format */ if (m->cupl.mpeg25_flag == 0) { m->cupl.framebytes = 1440 * mp_br_tableL3[m->cupl.id][br_index] / mp_sr20_table[m->cupl.id][m->cupl.sr_index]; } else { m->cupl.framebytes = 2880 * mp_br_tableL3[m->cupl.id][br_index] / mp_sr20_table[m->cupl.id][m->cupl.sr_index]; //if( sr_index == 2 ) return 0; // fail mpeg25 8khz } } m->cupl.side_info.main_data_begin = bitget(m, 8); if (m->cupl.side_info.mode == 3) { m->cupl.side_info.private_bits = bitget(m, 1); m->cupl.nchan = 1; m->cupl.stereo_flag = 0; side_bytes = (4 + 9); /*-- with header --*/ } else { m->cupl.side_info.private_bits = bitget(m, 2); m->cupl.nchan = 2; m->cupl.stereo_flag = 1; side_bytes = (4 + 17); /*-- with header --*/ } m->cupl.side_info.scfsi[1] = m->cupl.side_info.scfsi[0] = 0; for (ch = 0; ch < m->cupl.nchan; ch++) { m->cupl.side_info.gr[igr][ch].part2_3_length = bitget(m, 12); m->cupl.side_info.gr[igr][ch].big_values = bitget(m, 9); if (m->cupl.side_info.gr[igr][ch].big_values > 288) return -1; // to catch corrupt sideband data m->cupl.side_info.gr[igr][ch].global_gain = bitget(m, 8) + m->cupl.gain_adjust; if (m->cupl.ms_mode) m->cupl.side_info.gr[igr][ch].global_gain -= 2; m->cupl.side_info.gr[igr][ch].scalefac_compress = bitget(m, 9); m->cupl.side_info.gr[igr][ch].window_switching_flag = bitget(m, 1); if (m->cupl.side_info.gr[igr][ch].window_switching_flag) { m->cupl.side_info.gr[igr][ch].block_type = bitget(m, 2); m->cupl.side_info.gr[igr][ch].mixed_block_flag = bitget(m, 1); m->cupl.side_info.gr[igr][ch].table_select[0] = bitget(m, 5); m->cupl.side_info.gr[igr][ch].table_select[1] = bitget(m, 5); m->cupl.side_info.gr[igr][ch].subblock_gain[0] = bitget(m, 3); m->cupl.side_info.gr[igr][ch].subblock_gain[1] = bitget(m, 3); m->cupl.side_info.gr[igr][ch].subblock_gain[2] = bitget(m, 3); /* region count set in terms of long block cb's/bands */ /* r1 set so r0+r1+1 = 21 (lookup produces 576 bands ) */ /* bt=1 or 3 54 samples */ /* bt=2 mixed=0 36 samples */ /* bt=2 mixed=1 54 (8 long sf) samples? or maybe 36 */ /* region0 discussion says 54 but this would mix long */ /* and short in region0 if scale factors switch */ /* at band 36 (6 long scale factors) */ if ((m->cupl.side_info.gr[igr][ch].block_type == 2)) { m->cupl.side_info.gr[igr][ch].region0_count = (6 - 1); /* 36 samples */ m->cupl.side_info.gr[igr][ch].region1_count = 20 - (6 - 1); } else { /* long block type 1 or 3 */ m->cupl.side_info.gr[igr][ch].region0_count = (8 - 1); /* 54 samples */ m->cupl.side_info.gr[igr][ch].region1_count = 20 - (8 - 1); } } else { m->cupl.side_info.gr[igr][ch].mixed_block_flag = 0; m->cupl.side_info.gr[igr][ch].block_type = 0; m->cupl.side_info.gr[igr][ch].table_select[0] = bitget(m, 5); m->cupl.side_info.gr[igr][ch].table_select[1] = bitget(m, 5); m->cupl.side_info.gr[igr][ch].table_select[2] = bitget(m, 5); m->cupl.side_info.gr[igr][ch].region0_count = bitget(m, 4); m->cupl.side_info.gr[igr][ch].region1_count = bitget(m, 3); } m->cupl.side_info.gr[igr][ch].preflag = 0; m->cupl.side_info.gr[igr][ch].scalefac_scale = bitget(m, 1); m->cupl.side_info.gr[igr][ch].count1table_select = bitget(m, 1); } /* return bytes in header + side info */ return side_bytes; } /*-----------------------------------------------------------------*/ static void unpack_main(MPEG *m, unsigned char *pcm, int igr) { int ch; int bit0; int n1, n2, n3, n4, nn2, nn3; int nn4; int qbits; int m0; for (ch = 0; ch < m->cupl.nchan; ch++) { bitget_init(m, m->cupl.buf + (m->cupl.main_pos_bit >> 3)); bit0 = (m->cupl.main_pos_bit & 7); if (bit0) bitget(m, bit0); m->cupl.main_pos_bit += m->cupl.side_info.gr[igr][ch].part2_3_length; bitget_init_end(m, m->cupl.buf + ((m->cupl.main_pos_bit + 39) >> 3)); /*-- scale factors --*/ if (m->cupl.id) unpack_sf_sub_MPEG1(m, &m->cupl.sf[igr][ch], &m->cupl.side_info.gr[igr][ch], m->cupl.side_info.scfsi[ch], igr); else unpack_sf_sub_MPEG2(m, &m->cupl.sf[igr][ch], &m->cupl.side_info.gr[igr][ch], m->cupl.is_mode & ch, &m->cupl.is_sf_info); if (m->eq.enableEQ) m->cupl.side_info.gr[igr][ch].global_gain += m->eq.EQ_gain_adjust; /*--- huff data ---*/ n1 = m->cupl.sfBandIndex[0][m->cupl.side_info.gr[igr][ch].region0_count]; n2 = m->cupl.sfBandIndex[0][m->cupl.side_info.gr[igr][ch].region0_count + m->cupl.side_info.gr[igr][ch].region1_count + 1]; n3 = m->cupl.side_info.gr[igr][ch].big_values; n3 = n3 + n3; if (n3 > m->cupl.band_limit) n3 = m->cupl.band_limit; if (n2 > n3) n2 = n3; if (n1 > n3) n1 = n3; nn3 = n3 - n2; nn2 = n2 - n1; unpack_huff(m, m->cupl.sample[ch][igr], n1, m->cupl.side_info.gr[igr][ch].table_select[0]); unpack_huff(m, m->cupl.sample[ch][igr] + n1, nn2, m->cupl.side_info.gr[igr][ch].table_select[1]); unpack_huff(m, m->cupl.sample[ch][igr] + n2, nn3, m->cupl.side_info.gr[igr][ch].table_select[2]); qbits = m->cupl.side_info.gr[igr][ch].part2_3_length - (bitget_bits_used(m) - bit0); nn4 = unpack_huff_quad(m, m->cupl.sample[ch][igr] + n3, m->cupl.band_limit - n3, qbits, m->cupl.side_info.gr[igr][ch].count1table_select); n4 = n3 + nn4; m->cupl.nsamp[igr][ch] = n4; //limit n4 or allow deqaunt to sf band 22 if (m->cupl.side_info.gr[igr][ch].block_type == 2) n4 = min(n4, m->cupl.band_limit12); else n4 = min(n4, m->cupl.band_limit21); if (n4 < 576) memset(m->cupl.sample[ch][igr] + n4, 0, sizeof(SAMPLE) * (576 - n4)); if (m->cupl.bitdat.bs_ptr > m->cupl.bitdat.bs_ptr_end) { // bad data overrun memset(m->cupl.sample[ch][igr], 0, sizeof(SAMPLE) * (576)); } } /*--- dequant ---*/ for (ch = 0; ch < m->cupl.nchan; ch++) { dequant(m,m->cupl.sample[ch][igr], &m->cupl.nsamp[igr][ch], /* nsamp updated for shorts */ &m->cupl.sf[igr][ch], &m->cupl.side_info.gr[igr][ch], &m->cupl.cb_info[igr][ch], m->cupl.ncbl_mixed); } /*--- ms stereo processing ---*/ if (m->cupl.ms_mode) { if (m->cupl.is_mode == 0) { m0 = m->cupl.nsamp[igr][0]; /* process to longer of left/right */ if (m0 < m->cupl.nsamp[igr][1]) m0 = m->cupl.nsamp[igr][1]; } else { /* process to last cb in right */ m0 = m->cupl.sfBandIndex[m->cupl.cb_info[igr][1].cbtype][m->cupl.cb_info[igr][1].cbmax]; } ms_process(m->cupl.sample[0][igr], m0); } /*--- is stereo processing ---*/ if (m->cupl.is_mode) { if (m->cupl.id) is_process_MPEG1(m, m->cupl.sample[0][igr], &m->cupl.sf[igr][1], m->cupl.cb_info[igr], m->cupl.nsamp[igr][0], m->cupl.ms_mode); else is_process_MPEG2(m,m->cupl.sample[0][igr], &m->cupl.sf[igr][1], m->cupl.cb_info[igr], &m->cupl.is_sf_info, m->cupl.nsamp[igr][0], m->cupl.ms_mode); } /*-- adjust ms and is modes to max of left/right */ if (m->cupl.side_info.mode_ext) { if (m->cupl.nsamp[igr][0] < m->cupl.nsamp[igr][1]) m->cupl.nsamp[igr][0] = m->cupl.nsamp[igr][1]; else m->cupl.nsamp[igr][1] = m->cupl.nsamp[igr][0]; } /*--- antialias ---*/ for (ch = 0; ch < m->cupl.nchan; ch++) { if (m->cupl.cb_info[igr][ch].ncbl == 0) continue; /* have no long blocks */ if (m->cupl.side_info.gr[igr][ch].mixed_block_flag) n1 = 1; /* 1 -> 36 samples */ else n1 = (m->cupl.nsamp[igr][ch] + 7) / 18; if (n1 > 31) n1 = 31; antialias(m, m->cupl.sample[ch][igr], n1); n1 = 18 * n1 + 8; /* update number of samples */ if (n1 > m->cupl.nsamp[igr][ch]) m->cupl.nsamp[igr][ch] = n1; } /*--- hybrid + sbt ---*/ m->cupl.Xform(m, pcm, igr); /*-- done --*/ } /*--------------------------------------------------------------------*/ /*-----------------------------------------------------------------*/ IN_OUT L3audio_decode(void *mv, unsigned char *bs, unsigned char *pcm) { MPEG *m = mv; return m->cupl.decode_function((MPEG *)mv, bs, pcm); } /*--------------------------------------------------------------------*/ IN_OUT L3audio_decode_MPEG1(void *mv, unsigned char *bs, unsigned char *pcm) { MPEG *m = mv; int sync; IN_OUT in_out; int side_bytes; int nbytes; m->cupl.iframe++; bitget_init(m, bs); /* initialize bit getter */ /* test sync */ in_out.in_bytes = 0; /* assume fail */ in_out.out_bytes = 0; sync = bitget(m, 12); if (sync != 0xFFF) return in_out; /* sync fail */ /*-----------*/ /*-- unpack side info --*/ side_bytes = unpack_side_MPEG1(m); if (side_bytes < 0) { in_out.in_bytes = 0; return in_out; } m->cupl.padframebytes = m->cupl.framebytes + m->cupl.pad; in_out.in_bytes = m->cupl.padframebytes; /*-- load main data and update buf pointer --*/ /*------------------------------------------- if start point < 0, must just cycle decoder if jumping into middle of stream, w---------------------------------------------*/ m->cupl.buf_ptr0 = m->cupl.buf_ptr1 - m->cupl.side_info.main_data_begin; /* decode start point */ if (m->cupl.buf_ptr1 > BUF_TRIGGER) { /* shift buffer */ memmove(m->cupl.buf, m->cupl.buf + m->cupl.buf_ptr0, m->cupl.side_info.main_data_begin); m->cupl.buf_ptr0 = 0; m->cupl.buf_ptr1 = m->cupl.side_info.main_data_begin; } nbytes = m->cupl.padframebytes - side_bytes - m->cupl.crcbytes; // RAK: This is no bueno. :-( if (nbytes < 0 || nbytes > NBUF) { in_out.in_bytes = 0; return in_out; } memmove(m->cupl.buf + m->cupl.buf_ptr1, bs + side_bytes + m->cupl.crcbytes, nbytes); m->cupl.buf_ptr1 += nbytes; /*-----------------------*/ if (m->cupl.buf_ptr0 >= 0) { // dump_frame(buf+buf_ptr0, 64); m->cupl.main_pos_bit = m->cupl.buf_ptr0 << 3; unpack_main(m,pcm, 0); unpack_main(m,pcm + m->cupl.half_outbytes, 1); in_out.out_bytes = m->cupl.outbytes; } else { memset(pcm, m->cupl.zero_level_pcm, m->cupl.outbytes); /* fill out skipped frames */ in_out.out_bytes = m->cupl.outbytes; /* iframe--; in_out.out_bytes = 0; // test test */ } return in_out; } /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ IN_OUT L3audio_decode_MPEG2(void *mv, unsigned char *bs, unsigned char *pcm) { MPEG *m = mv; int sync; IN_OUT in_out; int side_bytes; int nbytes; static int igr = 0; m->cupl.iframe++; bitget_init(m, bs); /* initialize bit getter */ /* test sync */ in_out.in_bytes = 0; /* assume fail */ in_out.out_bytes = 0; sync = bitget(m, 12); // if( sync != 0xFFF ) return in_out; /* sync fail */ m->cupl.mpeg25_flag = 0; if (sync != 0xFFF) { m->cupl.mpeg25_flag = 1; /* mpeg 2.5 sync */ if (sync != 0xFFE) return in_out; /* sync fail */ } /*-----------*/ /*-- unpack side info --*/ side_bytes = unpack_side_MPEG2(m,igr); if (side_bytes < 0) { in_out.in_bytes = 0; return in_out; } m->cupl.padframebytes = m->cupl.framebytes + m->cupl.pad; in_out.in_bytes = m->cupl.padframebytes; m->cupl.buf_ptr0 = m->cupl.buf_ptr1 - m->cupl.side_info.main_data_begin; /* decode start point */ if (m->cupl.buf_ptr1 > BUF_TRIGGER) { /* shift buffer */ memmove(m->cupl.buf, m->cupl.buf + m->cupl.buf_ptr0, m->cupl.side_info.main_data_begin); m->cupl.buf_ptr0 = 0; m->cupl.buf_ptr1 = m->cupl.side_info.main_data_begin; } nbytes = m->cupl.padframebytes - side_bytes - m->cupl.crcbytes; // RAK: This is no bueno. :-( if (nbytes < 0 || nbytes > NBUF) { in_out.in_bytes = 0; return in_out; } memmove(m->cupl.buf + m->cupl.buf_ptr1, bs + side_bytes + m->cupl.crcbytes, nbytes); m->cupl.buf_ptr1 += nbytes; /*-----------------------*/ if (m->cupl.buf_ptr0 >= 0) { m->cupl.main_pos_bit = m->cupl.buf_ptr0 << 3; unpack_main(m,pcm, igr); in_out.out_bytes = m->cupl.outbytes; } else { memset(pcm, m->cupl.zero_level_pcm, m->cupl.outbytes); /* fill out skipped frames */ in_out.out_bytes = m->cupl.outbytes; // iframe--; in_out.out_bytes = 0; return in_out;// test test */ } igr = igr ^ 1; return in_out; } /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ static int const sr_table[8] = {22050, 24000, 16000, 1, 44100, 48000, 32000, 1}; static const struct { int l[23]; int s[14]; } sfBandIndexTable[3][3] = { /* mpeg-2 */ { { { 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 } , { 0, 4, 8, 12, 18, 24, 32, 42, 56, 74, 100, 132, 174, 192 } } , { { 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 114, 136, 162, 194, 232, 278, 332, 394, 464, 540, 576 } , { 0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 136, 180, 192 } } , { { 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 } , { 0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192 } } , } , /* mpeg-1 */ { { { 0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110, 134, 162, 196, 238, 288, 342, 418, 576 } , { 0, 4, 8, 12, 16, 22, 30, 40, 52, 66, 84, 106, 136, 192 } } , { { 0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106, 128, 156, 190, 230, 276, 330, 384, 576 } , { 0, 4, 8, 12, 16, 22, 28, 38, 50, 64, 80, 100, 126, 192 } } , { { 0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126, 156, 194, 240, 296, 364, 448, 550, 576 } , { 0, 4, 8, 12, 16, 22, 30, 42, 58, 78, 104, 138, 180, 192 } } } , /* mpeg-2.5, 11 & 12 KHz seem ok, 8 ok */ { { { 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 } , { 0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192 } } , { { 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 } , { 0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192 } } , // this 8khz table, and only 8khz, from mpeg123) { { 0, 12, 24, 36, 48, 60, 72, 88, 108, 132, 160, 192, 232, 280, 336, 400, 476, 566, 568, 570, 572, 574, 576 } , { 0, 8, 16, 24, 36, 52, 72, 96, 124, 160, 162, 164, 166, 192 } } , } , }; void sbt_mono_L3(MPEG *m, float *sample, signed short *pcm, int ch); void sbt_dual_L3(MPEG *m, float *sample, signed short *pcm, int ch); void sbt16_mono_L3(MPEG *m, float *sample, signed short *pcm, int ch); void sbt16_dual_L3(MPEG *m, float *sample, signed short *pcm, int ch); void sbt8_mono_L3(MPEG *m, float *sample, signed short *pcm, int ch); void sbt8_dual_L3(MPEG *m, float *sample, signed short *pcm, int ch); void sbtB_mono_L3(MPEG *m, float *sample, unsigned char *pcm, int ch); void sbtB_dual_L3(MPEG *m, float *sample, unsigned char *pcm, int ch); void sbtB16_mono_L3(MPEG *m, float *sample, unsigned char *pcm, int ch); void sbtB16_dual_L3(MPEG *m, float *sample, unsigned char *pcm, int ch); void sbtB8_mono_L3(MPEG *m, float *sample, unsigned char *pcm, int ch); void sbtB8_dual_L3(MPEG *m, float *sample, unsigned char *pcm, int ch); static SBT_FUNCTION_F sbt_table[2][3][2] = { {{ (SBT_FUNCTION_F) sbt_mono_L3, (SBT_FUNCTION_F) sbt_dual_L3 } , { (SBT_FUNCTION_F) sbt16_mono_L3, (SBT_FUNCTION_F) sbt16_dual_L3 } , { (SBT_FUNCTION_F) sbt8_mono_L3, (SBT_FUNCTION_F) sbt8_dual_L3 }} , /*-- 8 bit output -*/ {{ (SBT_FUNCTION_F) sbtB_mono_L3, (SBT_FUNCTION_F) sbtB_dual_L3 }, { (SBT_FUNCTION_F) sbtB16_mono_L3, (SBT_FUNCTION_F) sbtB16_dual_L3 }, { (SBT_FUNCTION_F) sbtB8_mono_L3, (SBT_FUNCTION_F) sbtB8_dual_L3 }} }; void Xform_mono(void *mv, void *pcm, int igr); void Xform_dual(void *mv, void *pcm, int igr); void Xform_dual_mono(void *mv, void *pcm, int igr); void Xform_dual_right(void *mv, void *pcm, int igr); static XFORM_FUNCTION xform_table[5] = { Xform_mono, Xform_dual, Xform_dual_mono, Xform_mono, /* left */ Xform_dual_right, }; int L3table_init(MPEG *m); void msis_init(MPEG *m); void sbt_init(MPEG *m); #if 0 typedef int iARRAY22[22]; #endif iARRAY22 *quant_init_band_addr(); iARRAY22 *msis_init_band_addr(); /*---------------------------------------------------------*/ /* mpeg_head defined in mhead.h frame bytes is without pad */ int L3audio_decode_init(void *mv, MPEG_HEAD * h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit) { MPEG *m = mv; int i, j, k; // static int first_pass = 1; int samprate; int limit; int bit_code; int out_chans; m->cupl.buf_ptr0 = 0; m->cupl.buf_ptr1 = 0; /* check if code handles */ if (h->option != 1) return 0; /* layer III only */ if (h->id) m->cupl.ncbl_mixed = 8; /* mpeg-1 */ else m->cupl.ncbl_mixed = 6; /* mpeg-2 */ m->cupl.framebytes = framebytes_arg; transform_code = transform_code; /* not used, asm compatability */ bit_code = 0; if (convert_code & 8) bit_code = 1; convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ if (reduction_code < 0) reduction_code = 0; if (reduction_code > 2) reduction_code = 2; if (freq_limit < 1000) freq_limit = 1000; samprate = sr_table[4 * h->id + h->sr_index]; if ((h->sync & 1) == 0) samprate = samprate / 2; // mpeg 2.5 /*----- compute nsb_limit --------*/ m->cupl.nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; /*- caller limit -*/ limit = (32 >> reduction_code); if (limit > 8) limit--; if (m->cupl.nsb_limit > limit) m->cupl.nsb_limit = limit; limit = 18 * m->cupl.nsb_limit; k = h->id; if ((h->sync & 1) == 0) k = 2; // mpeg 2.5 if (k == 1) { m->cupl.band_limit12 = 3 * sfBandIndexTable[k][h->sr_index].s[13]; m->cupl.band_limit = m->cupl.band_limit21 = sfBandIndexTable[k][h->sr_index].l[22]; } else { m->cupl.band_limit12 = 3 * sfBandIndexTable[k][h->sr_index].s[12]; m->cupl.band_limit = m->cupl.band_limit21 = sfBandIndexTable[k][h->sr_index].l[21]; } m->cupl.band_limit += 8; /* allow for antialias */ if (m->cupl.band_limit > limit) m->cupl.band_limit = limit; if (m->cupl.band_limit21 > m->cupl.band_limit) m->cupl.band_limit21 = m->cupl.band_limit; if (m->cupl.band_limit12 > m->cupl.band_limit) m->cupl.band_limit12 = m->cupl.band_limit; m->cupl.band_limit_nsb = (m->cupl.band_limit + 17) / 18; /* limit nsb's rounded up */ /*----------------------------------------------*/ m->cupl.gain_adjust = 0; /* adjust gain e.g. cvt to mono sum channel */ if ((h->mode != 3) && (convert_code == 1)) m->cupl.gain_adjust = -4; m->cupl.outvalues = 1152 >> reduction_code; if (h->id == 0) m->cupl.outvalues /= 2; out_chans = 2; if (h->mode == 3) out_chans = 1; if (convert_code) out_chans = 1; m->cupl.sbt_L3 = sbt_table[bit_code][reduction_code][out_chans - 1]; k = 1 + convert_code; if (h->mode == 3) k = 0; m->cupl.Xform = xform_table[k]; m->cupl.outvalues *= out_chans; if (bit_code) m->cupl.outbytes = m->cupl.outvalues; else m->cupl.outbytes = sizeof(short) * m->cupl.outvalues; if (bit_code) m->cupl.zero_level_pcm = 128; /* 8 bit output */ else m->cupl.zero_level_pcm = 0; m->cup.decinfo.channels = out_chans; m->cup.decinfo.outvalues = m->cupl.outvalues; m->cup.decinfo.samprate = samprate >> reduction_code; if (bit_code) m->cup.decinfo.bits = 8; else m->cup.decinfo.bits = sizeof(short) * 8; m->cup.decinfo.framebytes = m->cupl.framebytes; m->cup.decinfo.type = 0; m->cupl.half_outbytes = m->cupl.outbytes / 2; /*------------------------------------------*/ /*- init band tables --*/ k = h->id; if ((h->sync & 1) == 0) k = 2; // mpeg 2.5 for (i = 0; i < 22; i++) m->cupl.sfBandIndex[0][i] = sfBandIndexTable[k][h->sr_index].l[i + 1]; for (i = 0; i < 13; i++) m->cupl.sfBandIndex[1][i] = 3 * sfBandIndexTable[k][h->sr_index].s[i + 1]; for (i = 0; i < 22; i++) m->cupl.nBand[0][i] = sfBandIndexTable[k][h->sr_index].l[i + 1] - sfBandIndexTable[k][h->sr_index].l[i]; for (i = 0; i < 13; i++) m->cupl.nBand[1][i] = sfBandIndexTable[k][h->sr_index].s[i + 1] - sfBandIndexTable[k][h->sr_index].s[i]; /* init tables */ L3table_init(m); /* init ms and is stereo modes */ msis_init(m); /*----- init sbt ---*/ sbt_init(m); /*--- clear buffers --*/ for (i = 0; i < 576; i++) m->cupl.yout[i] = 0.0f; for (j = 0; j < 2; j++) { for (k = 0; k < 2; k++) { for (i = 0; i < 576; i++) { m->cupl.sample[j][k][i].x = 0.0f; m->cupl.sample[j][k][i].s = 0; } } } if (h->id == 1) m->cupl.decode_function = L3audio_decode_MPEG1; else m->cupl.decode_function = L3audio_decode_MPEG2; return 1; } /*---------------------------------------------------------*/ /*==========================================================*/ void cup3_init(MPEG *m) { m->cupl.sbt_L3 = sbt_dual_L3; m->cupl.Xform = Xform_dual; m->cupl.sbt_L3 = sbt_dual_L3; m->cupl.decode_function = L3audio_decode_MPEG1; } <file_sep>/modules/mp3/libmp3/xingmp3/iwinbQ.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /*----- iwinbq.c --------------------------------------------------- portable c mpeg1/2 Layer I/II audio decode conditional include to iwinm.c quick integer window - 8 bit output mods 1/8/97 warnings --------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ void i_windowB(WININT * vbuf, int vb_ptr, unsigned char *pcm) { int i, j; unsigned int si, bx; WINCOEF *coef; INT32 sum; /*-- first 16 --*/ si = (vb_ptr + (16 + 3 * 64)) & 511; bx = (si + (32 + 512 - 3 * 64 + 2 * 64)) & 511; coef = iwincoef; for (i = 0; i < 16; i++) { sum = -WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx = (bx + 64) & 511; sum += WINMULT(vbuf[si], (*coef++)); si = (si + 64) & 511; sum -= WINMULT(vbuf[bx], (*coef++)); } si = (si + (5 * 64 + 1)) & 511; bx = (bx + (64 + 4 * 64 - 1)) & 511; sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm++ = (unsigned char) ((sum >> 8) ^ 0x80); } /*-- special case --*/ bx = (bx + (512 - 64)) & 511; sum = WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx = (bx + 64) & 511; sum += WINMULT(vbuf[bx], (*coef++)); } sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm++ = (unsigned char) ((sum >> 8) ^ 0x80); /*-- last 15 --*/ coef = iwincoef + 111; /* back pass through coefs */ si = (si + (512 - 3 * 64 + 2 * 64 - 1)) & 511; bx = (bx + (64 + 3 * 64 + 2 * 64 + 1)) & 511; for (i = 0; i < 15; i++) { sum = WINMULT(vbuf[si], (*coef--)); for (j = 0; j < 3; j++) { si = (si + 64) & 511; sum += WINMULT(vbuf[bx], (*coef--)); bx = (bx + 64) & 511; sum += WINMULT(vbuf[si], (*coef--)); } si = (si + (64 - 1 + 4 * 64)) & 511; bx = (bx + (5 * 64 + 1)) & 511; sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm++ = (unsigned char) ((sum >> 8) ^ 0x80); } } /*------------------------------------------------------------*/ void i_windowB_dual(WININT * vbuf, int vb_ptr, unsigned char *pcm) { /* dual window interleaves output */ int i, j; unsigned int si, bx; WINCOEF *coef; INT32 sum; /*-- first 16 --*/ si = (vb_ptr + (16 + 3 * 64)) & 511; bx = (si + (32 + 512 - 3 * 64 + 2 * 64)) & 511; coef = iwincoef; for (i = 0; i < 16; i++) { sum = -WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx = (bx + 64) & 511; sum += WINMULT(vbuf[si], (*coef++)); si = (si + 64) & 511; sum -= WINMULT(vbuf[bx], (*coef++)); } si = (si + (5 * 64 + 1)) & 511; bx = (bx + (64 + 4 * 64 - 1)) & 511; sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; } /*-- special case --*/ bx = (bx + (512 - 64)) & 511; sum = WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx = (bx + 64) & 511; sum += WINMULT(vbuf[bx], (*coef++)); } sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; /*-- last 15 --*/ coef = iwincoef + 111; /* back pass through coefs */ si = (si + (512 - 3 * 64 + 2 * 64 - 1)) & 511; bx = (bx + (64 + 3 * 64 + 2 * 64 + 1)) & 511; for (i = 0; i < 15; i++) { sum = WINMULT(vbuf[si], (*coef--)); for (j = 0; j < 3; j++) { si = (si + 64) & 511; sum += WINMULT(vbuf[bx], (*coef--)); bx = (bx + 64) & 511; sum += WINMULT(vbuf[si], (*coef--)); } si = (si + (64 - 1 + 4 * 64)) & 511; bx = (bx + (5 * 64 + 1)) & 511; sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; } } /*------------------------------------------------------------*/ void i_windowB_dual_right(WININT * vbuf, int vb_ptr, unsigned char *pcm) { /* right identical to dual, for asm */ /* dual window interleaves output */ int i, j; unsigned int si, bx; WINCOEF *coef; INT32 sum; /*-- first 16 --*/ si = (vb_ptr + (16 + 3 * 64)) & 511; bx = (si + (32 + 512 - 3 * 64 + 2 * 64)) & 511; coef = iwincoef; for (i = 0; i < 16; i++) { sum = -WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx = (bx + 64) & 511; sum += WINMULT(vbuf[si], (*coef++)); si = (si + 64) & 511; sum -= WINMULT(vbuf[bx], (*coef++)); } si = (si + (5 * 64 + 1)) & 511; bx = (bx + (64 + 4 * 64 - 1)) & 511; sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; } /*-- special case --*/ bx = (bx + (512 - 64)) & 511; sum = WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx = (bx + 64) & 511; sum += WINMULT(vbuf[bx], (*coef++)); } sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; /*-- last 15 --*/ coef = iwincoef + 111; /* back pass through coefs */ si = (si + (512 - 3 * 64 + 2 * 64 - 1)) & 511; bx = (bx + (64 + 3 * 64 + 2 * 64 + 1)) & 511; for (i = 0; i < 15; i++) { sum = WINMULT(vbuf[si], (*coef--)); for (j = 0; j < 3; j++) { si = (si + 64) & 511; sum += WINMULT(vbuf[bx], (*coef--)); bx = (bx + 64) & 511; sum += WINMULT(vbuf[si], (*coef--)); } si = (si + (64 - 1 + 4 * 64)) & 511; bx = (bx + (5 * 64 + 1)) & 511; sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; } } /*------------------------------------------------------------*/ /*------------------------------------------------------------*/ /*------------------- 16 pt window ------------------------------*/ void i_windowB16(WININT * vbuf, int vb_ptr, unsigned char *pcm) { int i, j; unsigned char si, bx; WINCOEF *coef; INT32 sum; /*-- first 8 --*/ si = (unsigned char) (vb_ptr + 8 + 3 * 32); bx = (unsigned char) (si + (16 + 256 - 3 * 32 + 2 * 32)); coef = iwincoef; for (i = 0; i < 8; i++) { sum = -WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx += 32; sum += WINMULT(vbuf[si], (*coef++)); si += 32; sum -= WINMULT(vbuf[bx], (*coef++)); } si += (5 * 32 + 1); bx += (32 + 4 * 32 - 1); coef += 7; sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm++ = (unsigned char) ((sum >> 8) ^ 0x80); } /*-- special case --*/ bx += (256 - 32); sum = WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx += 32; sum += WINMULT(vbuf[bx], (*coef++)); } sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm++ = (unsigned char) ((sum >> 8) ^ 0x80); /*-- last 7 --*/ coef = iwincoef + (111 - 7); /* back pass through coefs */ si += (256 + -3 * 32 + 2 * 32 - 1); bx += (32 + 3 * 32 + 2 * 32 + 1); for (i = 0; i < 7; i++) { sum = WINMULT(vbuf[si], (*coef--)); for (j = 0; j < 3; j++) { si += 32; sum += WINMULT(vbuf[bx], (*coef--)); bx += 32; sum += WINMULT(vbuf[si], (*coef--)); } si += (32 - 1 + 4 * 32); bx += (5 * 32 + 1); coef -= 7; sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm++ = (unsigned char) ((sum >> 8) ^ 0x80); } } /*--------------- 16 pt dual window (interleaved output) -----------------*/ void i_windowB16_dual(WININT * vbuf, int vb_ptr, unsigned char *pcm) { int i, j; unsigned char si, bx; WINCOEF *coef; INT32 sum; /*-- first 8 --*/ si = (unsigned char) (vb_ptr + 8 + 3 * 32); bx = (unsigned char) (si + (16 + 256 - 3 * 32 + 2 * 32)); coef = iwincoef; for (i = 0; i < 8; i++) { sum = -WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx += 32; sum += WINMULT(vbuf[si], (*coef++)); si += 32; sum -= WINMULT(vbuf[bx], (*coef++)); } si += (5 * 32 + 1); bx += (32 + 4 * 32 - 1); coef += 7; sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; } /*-- special case --*/ bx += (256 - 32); sum = WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx += 32; sum += WINMULT(vbuf[bx], (*coef++)); } sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; /*-- last 7 --*/ coef = iwincoef + (111 - 7); /* back pass through coefs */ si += (256 + -3 * 32 + 2 * 32 - 1); bx += (32 + 3 * 32 + 2 * 32 + 1); for (i = 0; i < 7; i++) { sum = WINMULT(vbuf[si], (*coef--)); for (j = 0; j < 3; j++) { si += 32; sum += WINMULT(vbuf[bx], (*coef--)); bx += 32; sum += WINMULT(vbuf[si], (*coef--)); } si += (32 - 1 + 4 * 32); bx += (5 * 32 + 1); coef -= 7; sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; } } /*--------------- 16 pt dual window (interleaved output) -----------------*/ void i_windowB16_dual_right(WININT * vbuf, int vb_ptr, unsigned char *pcm) { /* right identical to dual, for asm */ int i, j; unsigned char si, bx; WINCOEF *coef; INT32 sum; /*-- first 8 --*/ si = (unsigned char) (vb_ptr + 8 + 3 * 32); bx = (unsigned char) (si + (16 + 256 - 3 * 32 + 2 * 32)); coef = iwincoef; for (i = 0; i < 8; i++) { sum = -WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx += 32; sum += WINMULT(vbuf[si], (*coef++)); si += 32; sum -= WINMULT(vbuf[bx], (*coef++)); } si += (5 * 32 + 1); bx += (32 + 4 * 32 - 1); coef += 7; sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; } /*-- special case --*/ bx += (256 - 32); sum = WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx += 32; sum += WINMULT(vbuf[bx], (*coef++)); } sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; /*-- last 7 --*/ coef = iwincoef + (111 - 7); /* back pass through coefs */ si += (256 + -3 * 32 + 2 * 32 - 1); bx += (32 + 3 * 32 + 2 * 32 + 1); for (i = 0; i < 7; i++) { sum = WINMULT(vbuf[si], (*coef--)); for (j = 0; j < 3; j++) { si += 32; sum += WINMULT(vbuf[bx], (*coef--)); bx += 32; sum += WINMULT(vbuf[si], (*coef--)); } si += (32 - 1 + 4 * 32); bx += (5 * 32 + 1); coef -= 7; sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; } } /*------------------------------------------------------------*/ /*------------------- 8 pt window ------------------------------*/ void i_windowB8(WININT * vbuf, int vb_ptr, unsigned char *pcm) { int i, j; unsigned int si, bx; WINCOEF *coef; INT32 sum; /*-- first 4 --*/ si = (vb_ptr + (4 + 3 * 16)) & 127; bx = (si + (8 + 128 - 3 * 16 + 2 * 16)) & 127; coef = iwincoef; for (i = 0; i < 4; i++) { sum = -WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx = (bx + 16) & 127; sum += WINMULT(vbuf[si], (*coef++)); si = (si + 16) & 127; sum -= WINMULT(vbuf[bx], (*coef++)); } si = (si + (5 * 16 + 1)) & 127; bx = (bx + (16 + 4 * 16 - 1)) & 127; coef += (3 * 7); sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm++ = (unsigned char) ((sum >> 8) ^ 0x80); } /*-- special case --*/ bx = (bx + (128 - 16)) & 127; sum = WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx = (bx + 16) & 127; sum += WINMULT(vbuf[bx], (*coef++)); } sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm++ = (unsigned char) ((sum >> 8) ^ 0x80); /*-- last 3 --*/ coef = iwincoef + (111 - 3 * 7); /* back pass through coefs */ si = (si + (128 - 3 * 16 + 2 * 16 - 1)) & 127; bx = (bx + (16 + 3 * 16 + 2 * 16 + 1)) & 127; for (i = 0; i < 3; i++) { sum = WINMULT(vbuf[si], (*coef--)); for (j = 0; j < 3; j++) { si = (si + 16) & 127; sum += WINMULT(vbuf[bx], (*coef--)); bx = (bx + 16) & 127; sum += WINMULT(vbuf[si], (*coef--)); } si = (si + (16 - 1 + 4 * 16)) & 127; bx = (bx + (5 * 16 + 1)) & 127; coef -= (3 * 7); sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm++ = (unsigned char) ((sum >> 8) ^ 0x80); } } /*--------------- 8 pt dual window (interleaved output) --------------*/ void i_windowB8_dual(WININT * vbuf, int vb_ptr, unsigned char *pcm) { int i, j; unsigned int si, bx; WINCOEF *coef; INT32 sum; /*-- first 4 --*/ si = (vb_ptr + (4 + 3 * 16)) & 127; bx = (si + (8 + 128 - 3 * 16 + 2 * 16)) & 127; coef = iwincoef; for (i = 0; i < 4; i++) { sum = -WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx = (bx + 16) & 127; sum += WINMULT(vbuf[si], (*coef++)); si = (si + 16) & 127; sum -= WINMULT(vbuf[bx], (*coef++)); } si = (si + (5 * 16 + 1)) & 127; bx = (bx + (16 + 4 * 16 - 1)) & 127; coef += (3 * 7); sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; } /*-- special case --*/ bx = (bx + (128 - 16)) & 127; sum = WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx = (bx + 16) & 127; sum += WINMULT(vbuf[bx], (*coef++)); } sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; /*-- last 3 --*/ coef = iwincoef + (111 - 3 * 7); /* back pass through coefs */ si = (si + (128 - 3 * 16 + 2 * 16 - 1)) & 127; bx = (bx + (16 + 3 * 16 + 2 * 16 + 1)) & 127; for (i = 0; i < 3; i++) { sum = WINMULT(vbuf[si], (*coef--)); for (j = 0; j < 3; j++) { si = (si + 16) & 127; sum += WINMULT(vbuf[bx], (*coef--)); bx = (bx + 16) & 127; sum += WINMULT(vbuf[si], (*coef--)); } si = (si + (16 - 1 + 4 * 16)) & 127; bx = (bx + (5 * 16 + 1)) & 127; coef -= (3 * 7); sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; } } /*------------------------------------------------------------*/ /*--------------- 8 pt dual window (interleaved output) --------------*/ void i_windowB8_dual_right(WININT * vbuf, int vb_ptr, unsigned char *pcm) { int i, j; unsigned int si, bx; WINCOEF *coef; INT32 sum; /* right identical to dual, for asm */ /*-- first 4 --*/ si = (vb_ptr + (4 + 3 * 16)) & 127; bx = (si + (8 + 128 - 3 * 16 + 2 * 16)) & 127; coef = iwincoef; for (i = 0; i < 4; i++) { sum = -WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx = (bx + 16) & 127; sum += WINMULT(vbuf[si], (*coef++)); si = (si + 16) & 127; sum -= WINMULT(vbuf[bx], (*coef++)); } si = (si + (5 * 16 + 1)) & 127; bx = (bx + (16 + 4 * 16 - 1)) & 127; coef += (3 * 7); sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; } /*-- special case --*/ bx = (bx + (128 - 16)) & 127; sum = WINMULT(vbuf[bx], (*coef++)); for (j = 0; j < 3; j++) { bx = (bx + 16) & 127; sum += WINMULT(vbuf[bx], (*coef++)); } sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; /*-- last 3 --*/ coef = iwincoef + (111 - 3 * 7); /* back pass through coefs */ si = (si + (128 - 3 * 16 + 2 * 16 - 1)) & 127; bx = (bx + (16 + 3 * 16 + 2 * 16 + 1)) & 127; for (i = 0; i < 3; i++) { sum = WINMULT(vbuf[si], (*coef--)); for (j = 0; j < 3; j++) { si = (si + 16) & 127; sum += WINMULT(vbuf[bx], (*coef--)); bx = (bx + 16) & 127; sum += WINMULT(vbuf[si], (*coef--)); } si = (si + (16 - 1 + 4 * 16)) & 127; bx = (bx + (5 * 16 + 1)) & 127; coef -= (3 * 7); sum >>= WINBITS; if (sum > 32767) sum = 32767; else if (sum < -32768) sum = -32768; *pcm = (unsigned char) ((sum >> 8) ^ 0x80); pcm += 2; } } /*--------------------------------------------------------*/ <file_sep>/modules/s3m/module.c /* DreamShell ##version## module.c - s3m module Copyright (C)2009-2014 SWAT */ #include "ds.h" #include "audio/s3m.h" DEFAULT_MODULE_EXPORTS_CMD(s3m, "S3M Player"); int builtin_s3m_cmd(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s option args...\n\n" "Options: \n" " -p, --play -Start playing\n" " -s, --stop -Stop playing\n\n" "Arguments: \n" " -f, --file -File for playing\n\n" "Examples: %s --play --file /cd/file.s3m\n" " %s -s", argv[0], argv[0], argv[0]); return CMD_NO_ARG; } int start = 0, stop = 0, stat = 0; char *file = NULL; struct cfg_option options[] = { {"play", 'p', NULL, CFG_BOOL, (void *) &start, 0}, {"stop", 's', NULL, CFG_BOOL, (void *) &stop, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(start) { if(file == NULL) { ds_printf("DS_ERROR: Need file for playing\n"); return CMD_ERROR; } stat = s3m_play(file); if(stat != S3M_SUCCESS) { switch (stat) { case S3M_ERROR_IO: ds_printf("DS_ERROR: Unabled to open s3m file\n"); return CMD_ERROR; case S3M_ERROR_MEM: ds_printf("DS_ERROR: s3m file exceeds available SRAM\n"); return CMD_ERROR; default: ds_printf("DS_ERROR: s3m uknown error.\n"); return CMD_ERROR; } } } if(stop) s3m_stop(); if(!start && !stop) { ds_printf("DS_ERROR: There is no option.\n"); return CMD_NO_ARG; } return CMD_OK; } <file_sep>/lib/SDL_gui/RTF.cc #include <kos.h> #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" extern "C" { SDL_Surface *GetScreen(); static char FontList[8][NAME_MAX]; /* Note, this is only one way of looking up fonts */ static int FontFamilyToIndex(RTF_FontFamily family) { switch(family) { case RTF_FontDefault: return 0; case RTF_FontRoman: return 1; case RTF_FontSwiss: return 2; case RTF_FontModern: return 3; case RTF_FontScript: return 4; case RTF_FontDecor: return 5; case RTF_FontTech: return 6; case RTF_FontBidi: return 7; default: return 0; } } static Uint16 UTF8_to_UNICODE(const char *utf8, int *advance) { int i = 0; Uint16 ch; ch = ((const unsigned char *)utf8)[i]; if ( ch >= 0xF0 ) { ch = (Uint16)(utf8[i]&0x07) << 18; ch |= (Uint16)(utf8[++i]&0x3F) << 12; ch |= (Uint16)(utf8[++i]&0x3F) << 6; ch |= (Uint16)(utf8[++i]&0x3F); } else if ( ch >= 0xE0 ) { ch = (Uint16)(utf8[i]&0x3F) << 12; ch |= (Uint16)(utf8[++i]&0x3F) << 6; ch |= (Uint16)(utf8[++i]&0x3F); } else if ( ch >= 0xC0 ) { ch = (Uint16)(utf8[i]&0x3F) << 6; ch |= (Uint16)(utf8[++i]&0x3F); } *advance = (i+1); return ch; } static void *CreateFont(const char *name, RTF_FontFamily family, int charset, int size, int style) { int index; TTF_Font *font; index = FontFamilyToIndex(family); if (!FontList[index][0]) index = 0; font = TTF_OpenFont(FontList[index], size); if (font) { int TTF_style = TTF_STYLE_NORMAL; if ( style & RTF_FontBold ) TTF_style |= TTF_STYLE_BOLD; if ( style & RTF_FontItalic ) TTF_style |= TTF_STYLE_ITALIC; if ( style & RTF_FontUnderline ) TTF_style |= TTF_STYLE_UNDERLINE; TTF_SetFontStyle(font, style); } /* FIXME: What do we do with the character set? */ return font; } static int GetLineSpacing(void *_font) { TTF_Font *font = (TTF_Font *)_font; return TTF_FontLineSkip(font); } static int GetCharacterOffsets(void *_font, const char *text, int *byteOffsets, int *pixelOffsets, int maxOffsets) { TTF_Font *font = (TTF_Font *)_font; int i = 0; int bytes = 0; int pixels = 0; int advance; Uint16 ch; while ( *text && i < maxOffsets ) { byteOffsets[i] = bytes; pixelOffsets[i] = pixels; ++i; ch = UTF8_to_UNICODE(text, &advance); text += advance; bytes += advance; TTF_GlyphMetrics(font, ch, NULL, NULL, NULL, NULL, &advance); pixels += advance; } if ( i < maxOffsets ) { byteOffsets[i] = bytes; pixelOffsets[i] = pixels; } return i; } static SDL_Surface *RenderText(void *_font, const char *text, SDL_Color fg) { TTF_Font *font = (TTF_Font *)_font; return TTF_RenderUTF8_Blended(font, text, fg); } static void FreeFont(void *_font) { TTF_Font *font = (TTF_Font *)_font; TTF_CloseFont(font); } } GUI_RTF::GUI_RTF(const char *aname, const char *file, const char *default_font, int x, int y, int w, int h) : GUI_Widget(aname, x, y, w, h) { SetupFonts(default_font); ctx = RTF_CreateContext(&font); /* file_t f = fs_open(file, O_RDONLY); uint32 bsize = fs_total(f); uint8 *buff = (uint8*) malloc(bsize); fs_read(f, buff, bsize); fs_close(f); SDL_RWops *rw = SDL_RWFromMem(buff, bsize); */ if(ctx == NULL || RTF_Load(ctx, file) < 0) { assert(0); } //if(buff) free(buff); SetupSurface(); } GUI_RTF::GUI_RTF(const char *aname, SDL_RWops *src, int freesrc, const char *default_font, int x, int y, int w, int h) : GUI_Widget(aname, x, y, w, h) { memset(&FontList[0][0], 0, sizeof(FontList)); SetupFonts(default_font); ctx = RTF_CreateContext(&font); if(ctx == NULL || RTF_Load_RW(ctx, src, freesrc) < 0) { assert(0); } SetupSurface(); } GUI_RTF::~GUI_RTF() { RTF_FreeContext(ctx); surface->DecRef(); } void GUI_RTF::SetupFonts(const char *default_font) { font.version = RTF_FONT_ENGINE_VERSION; font.CreateFont = CreateFont; font.GetLineSpacing = GetLineSpacing; font.GetCharacterOffsets = GetCharacterOffsets; font.RenderText = RenderText; font.FreeFont = FreeFont; if(FontList[0][0] != '/') { int i; for(i = 0; i < 8; i++) { if(default_font != NULL) { strcpy(FontList[i], default_font); } else { sprintf(FontList[i], "%s/fonts/ttf/arial_lite.ttf", getenv("PATH")); } } } } void GUI_RTF::SetupSurface() { offset = 0; SDL_Surface *screen = GetScreen(); surface = GUI_SurfaceCreate("rtf_render", screen->flags, area.w, area.h, screen->format->BitsPerPixel, screen->format->Rmask, screen->format->Gmask, screen->format->Bmask, screen->format->Amask); SetBgColor(255, 255, 255); } int GUI_RTF::SetFont(RTF_FontFamily family, const char *file) { int i = FontFamilyToIndex(family); if(i > -1 && i < 8) { strcpy(FontList[i], file); MarkChanged(); return 1; } return 0; } int GUI_RTF::GetFullHeight() { return RTF_GetHeight(ctx, area.w); } void GUI_RTF::SetOffset(int value) { offset = value; MarkChanged(); } void GUI_RTF::SetBgColor(int r, int g, int b) { color = surface->MapRGB(r, g, b); MarkChanged(); } /* Get the title of an RTF document */ const char *GUI_RTF::GetTitle() { return RTF_GetTitle(ctx); } /* Get the subject of an RTF document */ const char *GUI_RTF::GetSubject() { return RTF_GetSubject(ctx); } /* Get the author of an RTF document */ const char *GUI_RTF::GetAuthor() { return RTF_GetAuthor(ctx); } void GUI_RTF::DrawWidget(const SDL_Rect *clip) { if (parent == 0) return; if (ctx && surface) { surface->Fill(NULL, color); RTF_Render(ctx, surface->GetSurface(), NULL, offset); SDL_Rect dr; SDL_Rect sr; sr.w = dr.w = surface->GetWidth(); sr.h = dr.h = surface->GetHeight(); sr.x = sr.y = 0; dr.x = area.x; dr.y = area.y + (area.h - dr.h) / 2; //if (GUI_ClipRect(&sr, &dr, clip)) parent->Draw(surface, &sr, &dr); } } extern "C" { GUI_Widget *GUI_RTF_Load(const char *name, const char *file, const char *default_font, int x, int y, int w, int h) { return new GUI_RTF(name, file, default_font, x, y, w, h); } GUI_Widget *GUI_RTF_LoadRW(const char *name, SDL_RWops *src, int freesrc, const char *default_font, int x, int y, int w, int h) { return new GUI_RTF(name, src, freesrc, default_font, x, y, w, h); } int GUI_RTF_GetFullHeight(GUI_Widget *widget) { return ((GUI_RTF *)widget)->GetFullHeight(); } void GUI_RTF_SetOffset(GUI_Widget *widget, int value) { ((GUI_RTF *)widget)->SetOffset(value); } void GUI_RTF_SetBgColor(GUI_Widget *widget, int r, int g, int b) { ((GUI_RTF *)widget)->SetBgColor(r, g, b); } int GUI_RTF_SetFont(GUI_Widget *widget, RTF_FontFamily family, const char *file) { return ((GUI_RTF *)widget)->SetFont(family, file); } const char *GUI_RTF_GetTitle(GUI_Widget *widget) { return ((GUI_RTF *)widget)->GetTitle(); } const char *GUI_RTF_GetSubject(GUI_Widget *widget) { return ((GUI_RTF *)widget)->GetSubject(); } const char *GUI_RTF_GetAuthor(GUI_Widget *widget) { return ((GUI_RTF *)widget)->GetAuthor(); } } <file_sep>/modules/openssl/Makefile # # openssl module for DreamShell # Copyright (C)2022 SWAT # http://www.dc-swat.ru # TARGET_NAME = openssl OBJS = module.o DBG_LIBS = -lds -lz LIBS = -lcrypto -lssl GCC_LIB = -lgcc EXPORTS_FILE = exports.txt VER_MAJOR = 1 VER_MINOR = 1 VER_MICRO = 1 TARGET_FULLNAME = $(TARGET_NAME)-$(VER_MAJOR).$(VER_MINOR).$(VER_MICRO)n KOS_CFLAGS += -I./$(TARGET_FULLNAME)/include KOS_LIB_PATHS += -L./$(TARGET_FULLNAME) all: rm-elf build include ../../sdk/Makefile.loadable $(TARGET_FULLNAME).tar.gz: wget https://www.openssl.org/source/$(TARGET_FULLNAME).tar.gz $(TARGET_FULLNAME)/Configure: $(TARGET_FULLNAME).tar.gz tar zxf $(TARGET_FULLNAME).tar.gz $(TARGET_FULLNAME)/Makefile: $(TARGET_FULLNAME)/Configure cd ./$(TARGET_FULLNAME) && ./Configure linux-generic32 \ --cross-compile-prefix=${KOS_CC_BASE}/bin/$(KOS_CC_PREFIX)- \ no-hw no-threads no-shared no-asm no-ui-console no-tests \ no-stdio no-sock no-deprecated no-dso no-pic zlib \ -DL_ENDIAN -UHAVE_CRYPTODEV -DNO_SYS_UN_H -DNO_SYSLOG -DPOSIX_TIMERS=0L \ --prefix="`pwd`/build" --openssldir="`pwd`/build" perl -i -pe's/_POSIX_TIMERS/POSIX_TIMERS/g' $(TARGET_FULLNAME)/crypto/rand/rand_unix.c build: $(TARGET_FULLNAME)/Makefile cd ./$(TARGET_FULLNAME) && make -j4 \ CFLAGS="$(KOS_CFLAGS) -I$(KOS_PORTS)/include/zlib" \ CXXFLAGS="$(KOS_CXXFLAGS)" LDFLAGS="$(KOS_LDFLAGS)" rm-elf: -rm -f $(TARGET) || true -rm -f $(TARGET_LIB) || true install: $(TARGET) $(TARGET_LIB) -rm -f $(DS_BUILD)/modules/$(TARGET) || true -rm -f $(DS_SDK)/lib/$(TARGET_LIB) || true cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/lib/SDL_gui/ScrollPanel.cc // ScrollPanel #include "SDL_gui.h" GUI_ScrollPanel::GUI_ScrollPanel(const char *aname, int x, int y, int w, int h) : GUI_Container(aname, x, y, w, h) { panel = new GUI_Panel("panel", 0, 0, w - 30, h - 30); AddWidget(panel); panel->DecRef(); scrollbar_y = new GUI_ScrollBar("scrollbar", w - 30, 0, 30, h - 30); scrollbar_x = new GUI_ScrollBar("scrollbar", 0, h - 30, w - 30, 30); //GUI_Surface *sf = new GUI_Surface("/home/spanz/development/c/space/pics/tiny-button.png"); //scrollbar_y->SetKnobImage(sf); //scrollbar_x->SetKnobImage(sf); //sf->DecRef(); AddWidget(scrollbar_y); AddWidget(scrollbar_x); //printf("scrollbar_y added\n"); scrollbar_y->DecRef(); scrollbar_x->DecRef(); GUI_EventHandler < GUI_ScrollPanel > *cb = new GUI_EventHandler < GUI_ScrollPanel > (this, &GUI_ScrollPanel::AdjustScrollbar); scrollbar_x->SetMovedCallback(cb); scrollbar_y->SetMovedCallback(cb); cb->DecRef(); maxx = 0; maxy = 0; offsetx = 0; offsety = 0; } GUI_ScrollPanel::~GUI_ScrollPanel() { scrollbar_y->DecRef(); scrollbar_x->DecRef(); panel->DecRef(); } void GUI_ScrollPanel::AdjustScrollbar(GUI_Object * sender) { if (sender == scrollbar_x) { int p = scrollbar_x->GetHorizontalPosition(); panel->SetXOffset(p); } if (sender == scrollbar_y) { int p = scrollbar_y->GetVerticalPosition(); panel->SetYOffset(p); } } void GUI_ScrollPanel::AddItem(GUI_Widget * w) { panel->AddWidget(w); bool changed = false; if (w->GetArea().x + w->GetArea().w > maxx) { maxx = w->GetArea().x + w->GetArea().w; //printf("new maxx %d\n",maxx); changed = true; } if (w->GetArea().y + w->GetArea().w > maxy) { maxy = w->GetArea().y + w->GetArea().h; // printf("new maxy %d\n",maxy); changed = true; } if (changed) { if (maxx < panel->GetArea().w + 1) { scrollbar_x->SetFlags(WIDGET_HIDDEN); //printf("hide scrollbar_x\n"); } else { scrollbar_x->WriteFlags(~WIDGET_HIDDEN, 0); //printf("show scrollbar_x\n"); } if (maxy < panel->GetArea().h) { scrollbar_y->SetFlags(WIDGET_HIDDEN); //printf("hide scrollbar_y\n"); } else { scrollbar_y->WriteFlags(~WIDGET_HIDDEN, 0); //printf("show scrollbar_y\n"); } Update(true); //MarkChanged(); } } void GUI_ScrollPanel::RemoveItem(GUI_Widget * w) { int n, i; panel->RemoveWidget(w); n = panel->GetWidgetCount(); maxx = 0; maxy = 0; offsetx = 0; offsety = 0; for (i = 0; i < n; i++) { w = panel->GetWidget(i); if (w->GetArea().x + w->GetArea().w > maxx) maxx = w->GetArea().x + w->GetArea().w; if (w->GetArea().y + w->GetArea().w > maxy) maxy = w->GetArea().y + w->GetArea().h; } if (maxx < panel->GetArea().w + 1) { scrollbar_x->SetFlags(WIDGET_HIDDEN); //printf("hide scrollbar_x\n"); } else { scrollbar_x->WriteFlags(~WIDGET_HIDDEN, 0); //printf("show scrollbar_x\n"); } if (maxy < panel->GetArea().h) { scrollbar_y->SetFlags(WIDGET_HIDDEN); //printf("hide scrollbar_y\n"); } else { scrollbar_y->WriteFlags(~WIDGET_HIDDEN, 0); //printf("show scrollbar_y\n"); } Update(true); } void GUI_ScrollPanel::Update(int force) { //GUI_Container::Update(force); if (flags & WIDGET_CHANGED) { force = 1; flags &= ~WIDGET_CHANGED; } if (force) { SDL_Rect r = area; r.x = x_offset; r.y = y_offset; Erase(&r); } for (int i = 0; i < n_widgets; i++) widgets[i]->DoUpdate(force); } int GUI_ScrollPanel::Event(const SDL_Event * event, int xoffset, int yoffset) { xoffset += area.x - x_offset; yoffset += area.y - y_offset; for (int i = 0; i < n_widgets; i++) if (widgets[i]->Event(event, xoffset, yoffset)) return 1; return GUI_Drawable::Event(event, xoffset, yoffset); } <file_sep>/include/fs.h /** * \file fs.h * \brief DreamShell filesystem * \date 2007-2023 * \author SWAT www.dc-swat.ru */ #ifndef _DS_FS_H #define _DS_FS_H #include <arch/types.h> #include <kos/blockdev.h> #include <ext2/fs_ext2.h> /** * Initialize SD Card * and mount all partitions with FAT or EXT2 filesystems */ int InitSDCard(); /** * Initialize G1-ATA device * and mount all partitions with FAT or EXT2 filesystems */ int InitIDE(); /** * Search romdisk images in BIOS ROM and mount it */ int InitRomdisk(); /** * Search DreamShell root directory on all usable devices */ int SearchRoot(); /** * Check for usable devices * 1 on success, 0 on fail */ int RootDeviceIsSupported(const char *name); /** * FAT filesystem API */ typedef enum fatfs_ioctl { FATFS_IOCTL_CTRL_SYNC = 0, /* Flush disk cache (for write functions) */ FATFS_IOCTL_GET_SECTOR_COUNT, /* Get media size (for only f_mkfs()), 4 byte unsigned */ FATFS_IOCTL_GET_SECTOR_SIZE, /* Get sector size (for multiple sector size (_MAX_SS >= 1024)), 2 byte unsigned */ FATFS_IOCTL_GET_BLOCK_SIZE, /* Get erase block size (for only f_mkfs()), 2 byte unsigned */ FATFS_IOCTL_CTRL_ERASE_SECTOR, /* Force erased a block of sectors (for only _USE_ERASE) */ FATFS_IOCTL_GET_BOOT_SECTOR_DATA, /* Get first sector data, ffconf.h _MAX_SS bytes */ FATFS_IOCTL_GET_FD_LBA, /* Get file LBA, 4 byte unsigned */ FATFS_IOCTL_GET_FD_LINK_MAP /* Get file clusters linkmap, 128+ bytes */ } fatfs_ioctl_t; /** * Initialize and shutdown FAT filesystem * return 0 on success, or < 0 if error */ int fs_fat_init(void); int fs_fat_shutdown(void); /** * Mount FAT filesystem on specified partition * For block device need reset to 0 start_block number * return 0 on success, or < 0 if error */ int fs_fat_mount(const char *mp, kos_blockdev_t *dev, int dma, int partition); /** * Unmount FAT filesystem * return 0 on success, or < 0 if error */ int fs_fat_unmount(const char *mp); /** * Check mount point for FAT filesystem * return 0 is not FAT */ int fs_fat_is_mounted(const char *mp); /** * Check partition type for FAT * return 0 if not FAT or 16/32 if FAT partition */ int is_fat_partition(uint8 partition_type); /** * Check partition type for EXT2 */ #define is_ext2_partition(partition_type) (partition_type == 0x83) #endif /* _DS_FS_H */ <file_sep>/modules/aicaos/arm/task.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <reent.h> #include <sys/queue.h> #include "../aica_common.h" #include "task.h" #include "interrupt.h" struct task *current_task; static unsigned int id = 0; struct TaskHandler { struct task * task; SLIST_ENTRY(TaskHandler) next; }; static SLIST_HEAD(Head, TaskHandler) tasks [PRIORITY_MAX+1]; void task_select(struct task *task) { /* Inside task_asm.S */ void __task_select(struct context *context); int_disable(); current_task = task; _impure_ptr = &task->reent; __task_select(&task->context); } /* Called from task_asm.S */ void __task_reschedule() { uint32_t i; struct TaskHandler *hdl; int_disable(); for (i = 0; i <= PRIORITY_MAX; i++) { SLIST_FOREACH(hdl, &tasks[i], next) { if (hdl->task != current_task) task_select(hdl->task); } } task_select(current_task); } void task_exit(void) { struct TaskHandler *hdl; unsigned int i; int_disable(); for (i = 0; i <= PRIORITY_MAX; i++) { SLIST_FOREACH(hdl, &tasks[i], next) { if (hdl->task == current_task) { /* Revert to the main stack */ __asm__ volatile("ldr sp,=__stack"); SLIST_REMOVE(&tasks[i], hdl, TaskHandler, next); free(hdl->task->stack); free(hdl->task); free(hdl); __task_reschedule(); } } } } struct task * task_create(void *func, void *param[4]) { struct task *task = malloc(sizeof(struct task)); if (!task) return NULL; /* Init the stack */ task->stack_size = DEFAULT_STACK_SIZE; task->stack = malloc(DEFAULT_STACK_SIZE); if (!task->stack) { free(task); return NULL; } if (param) memcpy(task->context.r0_r7, param, 4 * sizeof(void *)); task->context.r8_r14[5] = (uint32_t) task->stack + DEFAULT_STACK_SIZE; task->context.r8_r14[6] = (uint32_t) task_exit; task->context.pc = func; task->context.cpsr = 0x13; /* supervisor */ /* Init newlib's reent structure */ _REENT_INIT_PTR(&task->reent); task->id = id++; return task; } void task_add_to_runnable(struct task *task, unsigned char prio) { uint32_t cxt = int_disable(); struct TaskHandler *old = NULL, *new = malloc(sizeof(struct TaskHandler)), *hdl = SLIST_FIRST(&tasks[prio]); new->task = task; SLIST_FOREACH(hdl, &tasks[prio], next) old = hdl; if (old) SLIST_INSERT_AFTER(old, new, next); else SLIST_INSERT_HEAD(&tasks[prio], new, next); int_restore(cxt); } <file_sep>/applications/main/scripts/Dialup.lua ----------------------------------------- -- -- -- @name: Dial-up connect script -- -- @author: SWAT -- -- @url: http://www.dc-swat.ru -- -- -- ----------------------------------------- -- ShowConsole(); Sleep(500); print("To get back GUI press: Start, A, Start\n"); if OpenModule(os.getenv("PATH") .. "/modules/ppp.klf") then print("Dialing...\n"); os.execute("ppp -i"); end <file_sep>/modules/opkg/unsqfs.h #ifndef PRIVATE_H #define PRIVATE_H struct PkgData; struct PkgData *opk_sqfs_open(const char *image_name); void opk_sqfs_close(struct PkgData *pdata); int opk_sqfs_extract_file(struct PkgData *pdata, const char *name, void **out_data, size_t *out_size); int opk_sqfs_get_metadata(struct PkgData *pdata, const char **filename); #endif <file_sep>/include/plx/matrix.h /* Parallax for KallistiOS ##version## matrix.h (c)2002 <NAME> (c)2013 SWAT */ #ifndef __PARALLAX_MATRIX #define __PARALLAX_MATRIX #include <sys/cdefs.h> __BEGIN_DECLS /** \file Matrix primitives. Half of these are just wrappers for the DC arch matrix routines. The main purpose of this is to try to keep client code less architecture specific so we can potentially port later more easily. The second half are routines adapted from KGL, and are intended for 3D usage primarily, though they can also be used for 2D if you want to do that (rotate, translate, etc). Like KGL, these use degrees. */ #include <dc/matrix.h> #include <dc/matrix3d.h> /* dc/matrix.h -- basic matrix register operations. */ #define plx_mat_store mat_store #define plx_mat_load mat_load #define plx_mat_identity mat_identity #define plx_mat_apply mat_apply #define plx_mat_transform mat_transform #define plx_mat_tfip_3d mat_trans_single #define plx_mat_tfip_3dw mat_trans_single4 #define plx_mat_tfip_2d mat_trans_single3 /* dc/matrix3d.h -- some of these are still useful in 2D. All of the following work on the matrix registers. */ #define plx_mat_rotate_x mat_rotate_x #define plx_mat_rotate_y mat_rotate_y #define plx_mat_rotate_z mat_rotate_z #define plx_mat_rotate mat_rotate #define plx_mat_translate mat_translate #define plx_mat_scale mat_scale /* The 3D matrix operations, somewhat simplified from KGL. All of these use the matrix regs, but do not primarily keep their values in them. To get the values out into the matrix regs (and usable) you'll want to set everything up and then call plx_mat3d_apply(). */ /** Call before doing anything else, or after switching video modes to setup some basic parameters. */ void plx_mat3d_init(); /** Set which matrix we are working on */ void plx_mat3d_mode(int mode); /* Constants for plx_mat3d_mode and plx_mat3d_apply */ #define PLX_MAT_PROJECTION 0 /** Projection (frustum, screenview) matrix */ #define PLX_MAT_MODELVIEW 1 /** Modelview (rotate, scale) matrix */ #define PLX_MAT_SCREENVIEW 2 /** Internal screen view matrix */ #define PLX_MAT_SCRATCH 3 /** Temp matrix for user usage */ #define PLX_MAT_WORLDVIEW 4 /** Optional camera/worldview matrix */ #define PLX_MAT_COUNT 5 /** Load an identity matrix */ void plx_mat3d_identity(); /** Load a raw matrix */ void plx_mat3d_load(matrix_t * src); /** Save a raw matrix */ void plx_mat3d_store(matrix_t * src); /** Setup viewport parameters */ void plx_mat3d_viewport(int x1, int y1, int width, int height); /** Setup a perspective matrix */ void plx_mat3d_perspective(float angle, float aspect, float znear, float zfar); /** Setup a frustum matrix */ void plx_mat3d_frustum(float left, float right, float bottom, float top, float znear, float zfar); /** Setup a orthogonal matrix */ void plx_mat3d_ortho(float left, float right, float bottom, float top, float znear, float zfar); /** Push a matrix on the stack */ void plx_mat3d_push(); /** Pop a matrix from the stack and reload it */ void plx_mat3d_pop(); /** Reload a matrix from the top of the stack, but don't pop it */ void plx_mat3d_peek(); /** Rotation */ void plx_mat3d_rotate(float angle, float x, float y, float z); /** Scaling */ void plx_mat3d_scale(float x, float y, float z); /** Translation */ void plx_mat3d_translate(float x, float y, float z); /** Do a camera "look at" */ void plx_mat3d_lookat(const point_t * eye, const point_t * center, const vector_t * up); /** Apply a matrix from one of the matrix modes to the matrix regs */ void plx_mat3d_apply(int mode); /** Manually apply a matrix */ void plx_mat3d_apply_mat(matrix_t * src); /** Apply all the matrices for a normal 3D scene */ void plx_mat3d_apply_all(); __END_DECLS #endif /* __PARALLAX_MATRIX */ <file_sep>/lib/SDL_gui/SDLScreen.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" ////////////////////////////////////////////////////////////////////////////// static SDL_Rect ConvertRect(const GUI_Rect &r) { SDL_Rect sdl_r = { (Sint16) r.x, (Sint16) r.y, (Uint16) r.w, (Uint16) r.h }; return sdl_r; } static Uint32 MapColor(SDL_Surface *surface, const GUI_Color &c) { return SDL_MapRGB(surface->format, int(c.r * 255), int(c.g * 255), int(c.b * 255)); } ////////////////////////////////////////////////////////////////////////////// GUI_SDLScreen::GUI_SDLScreen(const char *aname, SDL_Surface *surf) : GUI_Window(aname, NULL, 0, 0, surf->w, surf->h) { surface = surf; } GUI_SDLScreen::~GUI_SDLScreen(void) { } void GUI_SDLScreen::UpdateAll(void) { SDL_UpdateRect(surface, 0, 0, area.w, area.h); } void GUI_SDLScreen::Update(const GUI_Rect &r) { SDL_UpdateRect(surface, r.x, r.y, r.w, r.h); } void GUI_SDLScreen::DrawImage(const GUI_Surface *image, const GUI_Rect &src_r, const GUI_Rect &dst_r) { // image->Blit(srp, surface, drp); } void GUI_SDLScreen::FillRect(const GUI_Rect &r, const GUI_Color &c) { Uint32 sdl_c = MapColor(surface, c); SDL_Rect sdl_r = ConvertRect(r); SDL_FillRect(surface, &sdl_r, sdl_c); } void GUI_SDLScreen::DrawRect(const GUI_Rect &r, const GUI_Color &c) { } void GUI_SDLScreen::DrawLine(int x1, int y1, int x2, int y2, const GUI_Color &c) { } void GUI_SDLScreen::DrawPixel(int x, int y, const GUI_Color &c) { } <file_sep>/firmware/isoldr/loader/kos/dc/g2bus.h /* KallistiOS ##version## g2bus.h (c)2002 <NAME> $Id: g2bus.h,v 1.5 2002/09/13 06:44:41 bardtx Exp $ */ #ifndef __DC_G2BUS_H #define __DC_G2BUS_H #include <sys/cdefs.h> __BEGIN_DECLS #include <arch/types.h> /* Read one byte from G2 */ uint8 g2_read_8(uint32 address); /* Write one byte to G2 */ void g2_write_8(uint32 address, uint8 value); /* Read one word from G2 */ uint16 g2_read_16(uint32 address); /* Write one word to G2 */ void g2_write_16(uint32 address, uint16 value); /* Read one dword from G2 */ uint32 g2_read_32(uint32 address); /* Write one dword to G2 */ void g2_write_32(uint32 address, uint32 value); /* Read a block of 8-bit values from G2 */ void g2_read_block_8(uint8 * output, uint32 address, int amt); /* Write a block 8-bit values to G2 */ void g2_write_block_8(const uint8 * input, uint32 address, int amt); /* Read a block of 16-bit values from G2 */ void g2_read_block_16(uint16 * output, uint32 address, int amt); /* Write a block of 16-bit values to G2 */ void g2_write_block_16(const uint16 * input, uint32 address, int amt); /* Read a block of 32-bit values from G2 */ void g2_read_block_32(uint32 * output, uint32 address, int amt); /* Write a block of 32-bit values to G2 */ void g2_write_block_32(const uint32 * input, uint32 address, int amt); /* When writing to the SPU RAM, this is required at least every 8 32-bit writes that you execute */ void g2_fifo_wait(); __END_DECLS #endif /* __DC_G2BUS_H */ <file_sep>/commands/flashrom/main.c /* DreamShell ##version## flashrom.c Copyright (C) 2007-2014 SWAT */ #include "ds.h" static const char * langs[] = { "Invalid", "Japanese", "English", "German", "French", "Spanish", "Italian" }; int main(int argc, char *argv[]) { uint8 *buffer; int start, size, i, part; flashrom_syscfg_t sc; file_t ff; if(argc == 1) { ds_printf("Usage: flashrom -flag arguments(if needed)...\n" "Flags Implements: \n" " -read - FLASHROM_READ syscall\n" " -write - FLASHROM_WRITE syscall\n" " -del - FLASHROM_DELETE syscall\n" " -inf - FLASHROM_INFO syscall\n" " -ps - Print settings\n\n" " -help - Print usages help\n"); return CMD_NO_ARG; } if (!strcmp(argv[1], "-help")) { ds_printf("Flag usages: \n" " -read offset size to_file\n" " -write offset from_file\n" " -del offset\n" " -inf part(0-4)\n" " -ps\n" " -help\n\n" "Parts(for -inf): \n" " 0 - Factory settings (read-only, 8K)\n" " 1 - Reserved (all 0s, 8K)\n" " 2 - Block allocated (16K)\n" " 3 - Game settings (block allocated, 32K)\n" " 4 - Block allocated (64K)\n"); return CMD_OK; } if (!strcmp(argv[1], "-read")) { start = atoi(argv[2]); size = atoi(argv[3]); buffer = (uint8 *)malloc(size); if(buffer == NULL) { ds_printf("DS_ERROR: No free memory\n"); return CMD_ERROR; } if(flashrom_read(start, buffer, size) < 0) { ds_printf("DS_ERROR: Can't read part %d\n", start); return CMD_ERROR; } ff = fs_open(argv[4], O_CREAT | O_WRONLY); if(ff == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open %s\n", argv[4]); return CMD_ERROR; } fs_write(ff, buffer, size); fs_close(ff); free(buffer); return CMD_OK; } if (!strcmp(argv[1], "-write")) { start = atoi(argv[2]); ff = fs_open(argv[3], O_RDONLY); if(ff == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open %s\n", argv[3]); return CMD_ERROR; } size = fs_total(ff); buffer = (uint8 *)malloc(size); if(buffer == NULL) { ds_printf("DS_ERROR: No free memory\n"); return CMD_ERROR; } fs_read(ff, buffer, size); flashrom_delete(start); if(flashrom_write(start, buffer, size) < 0) { ds_printf("DS_ERROR: Can't write part %d\n", start); return CMD_ERROR; } fs_close(ff); free(buffer); return CMD_OK; } if (!strcmp(argv[1], "-del")) { start = atoi(argv[2]); flashrom_delete(start); ds_printf("DS_INF: Complete.\n"); return CMD_OK; } if (!strcmp(argv[1], "-inf")) { part = atoi(argv[2]); flashrom_info(part, &start, &size); ds_printf("Part: %d\n", part); ds_printf("Offset: %d\n", start); ds_printf("Size: %12d\n", size); return CMD_OK; } if (!strcmp(argv[1], "-ps")) { ds_printf("\nDS_PROCESS: Reading flashrom...\n"); if (flashrom_info(0, &start, &size) < 0) { ds_printf("DS_ERROR: Couldn't get the start/size of partition 0\n"); return CMD_ERROR; } buffer = (uint8 *)malloc(size); if(buffer == NULL) { ds_printf("DS_ERROR: No free memory\n"); return CMD_ERROR; } if (flashrom_read(start, buffer, size) < 0) { ds_printf("DS_ERROR: Couldn't read partition 0\n"); free(buffer); return CMD_ERROR; } ds_printf("DS: Your flash header: '"); for (i=0; i < 16; i++) { ds_printf("%c", buffer[i]); } ds_printf("'\nDS: Again in hex:\n"); for (i=0; i < 16; i++) { ds_printf("%02x ", buffer[i]); } if (!memcmp(buffer, "00000", 5)) { ds_printf("This appears to be a Japanese DC.\n"); } else if (!memcmp(buffer, "00110", 5)) { ds_printf("This appears to be a USA DC.\n"); } else if (!memcmp(buffer, "00211", 5)) { ds_printf("This appears to be a European DC.\n"); } else { ds_printf("DS_ERROR: I don't know what the region of this DC is.\n"); } free(buffer); if (flashrom_get_syscfg(&sc) < 0) { ds_printf("DS_ERROR: flashrom_get_syscfg failed\n"); return CMD_ERROR; } i = sc.language; if (i > FLASHROM_LANG_ITALIAN) i = -1; ds_printf("Your selected language is %s.\n", langs[i+1]); i = sc.audio; ds_printf("Your audio is set to %s.\n",i ? "stereo" : "mono"); i = sc.autostart; ds_printf("Your auto-start is set to %s.\n",i ? "on" : "off"); return CMD_OK; } return CMD_OK; } <file_sep>/firmware/isoldr/loader/include/syscalls.h /** * DreamShell ISO Loader * BIOS syscalls emulation * (c)2009-2023 SWAT <http://www.dc-swat.ru> */ #ifndef _SYSCALLS_H #define _SYSCALLS_H #include <arch/types.h> #include <dc/cdrom.h> /** \defgroup cd_cmd_codes CD-ROM syscall command codes @{ */ #define CMD_CHECK_LICENSE 2 /**< \brief */ #define CMD_REQ_SPI_CMD 4 /**< \brief */ #define CMD_PIOREAD 16 /**< \brief Read via PIO */ #define CMD_DMAREAD 17 /**< \brief Read via DMA */ #define CMD_GETTOC 18 /**< \brief Read TOC */ #define CMD_GETTOC2 19 /**< \brief Read TOC */ #define CMD_PLAY 20 /**< \brief Play track */ #define CMD_PLAY2 21 /**< \brief Play sectors */ #define CMD_PAUSE 22 /**< \brief Pause playback */ #define CMD_RELEASE 23 /**< \brief Resume from pause */ #define CMD_INIT 24 /**< \brief Initialize the drive */ #define CMD_DMA_ABORT 25 /**< \brief */ #define CMD_OPEN_TRAY 26 /**< \brief */ #define CMD_SEEK 27 /**< \brief Seek to a new position */ #define CMD_DMAREAD_STREAM 28 /**< \brief */ #define CMD_NOP 29 /**< \brief */ #define CMD_REQ_MODE 30 /**< \brief */ #define CMD_SET_MODE 31 /**< \brief */ #define CMD_SCAN_CD 32 /**< \brief */ #define CMD_STOP 33 /**< \brief Stop the disc from spinning */ #define CMD_GETSCD 34 /**< \brief Get subcode data */ #define CMD_GETSES 35 /**< \brief Get session */ #define CMD_REQ_STAT 36 /**< \brief */ #define CMD_PIOREAD_STREAM 37 /**< \brief */ #define CMD_DMAREAD_STREAM_EX 38 /**< \brief Can get parts < sector size in reqDmaStrans */ #define CMD_PIOREAD_STREAM_EX 39 /**< \brief */ #define CMD_GET_VERS 40 /**< \brief */ #define CMD_MAX 47 /**< \brief */ /** @} */ /** \defgroup cd_cmd_status CD-ROM Command Status responses These are the raw values the status syscall returns. @{ */ #define CMD_STAT_FAILED -1 #define CMD_STAT_IDLE 0 #define CMD_STAT_PROCESSING 1 #define CMD_STAT_COMPLETED 2 #define CMD_STAT_STREAMING 3 #define CMD_STAT_BUSY 4 #define CMD_STAT_UNK1 5 #define CMD_STAT_UNK2 6 /** @} */ /** \defgroup cd_cmd_error CD-ROM command errors @{ */ #define CMD_ERR_NOERR 0x00 #define CMD_ERR_RECOVERED 0x01 #define CMD_ERR_NOTREADY 0x02 #define CMD_ERR_MEDIUM 0x03 #define CMD_ERR_HARDWARE 0x04 #define CMD_ERR_ILLEGALREQUEST 0x05 #define CMD_ERR_UNITATTENTION 0x06 #define CMD_ERR_DATAPROTECT 0x07 #define CMD_ERR_ABORTED 0x0B #define CMD_ERR_NOREADABLE 0x10 #define CMD_ERR_G1SEMAPHORE 0x20 /** @} */ /** \defgroup cd_cmd_wait CD-ROM command wait types @{ */ #define CMD_WAIT_INTERNAL 0x00 #define CMD_WAIT_IRQ 0x01 #define CMD_WAIT_DRQ_0 0x02 #define CMD_WAIT_DRQ_1 0x03 #define CMD_WAIT_BUSY 0x04 /** @} */ /** \defgroup cd_status_values CD-ROM status values These are the values that can be returned as the status parameter from the cdrom_get_status() function. @{ */ #define CD_STATUS_CANTREAD -1 #define CD_STATUS_BUSY 0x00 #define CD_STATUS_PAUSED 0x01 #define CD_STATUS_STANDBY 0x02 #define CD_STATUS_PLAYING 0x03 #define CD_STATUS_SEEK 0x04 #define CD_STATUS_SCAN 0x05 #define CD_STATUS_OPEN 0x06 #define CD_STATUS_NODISC 0x07 #define CD_STATUS_RETRY 0x08 #define CD_STATUS_ERROR 0x09 /** @} */ /* Values for CMD_GETSCD command */ #define SCD_REQ_ALL_SUBCODE 0x0 #define SCD_REQ_Q_SUBCODE 0x1 #define SCD_REQ_MEDIA_CATALOG 0x2 #define SCD_REQ_ISRC 0x3 #define SCD_REQ_RESERVED 0x4 #define SCD_AUDIO_STATUS_INVALID 0x00 #define SCD_AUDIO_STATUS_PLAYING 0x11 #define SCD_AUDIO_STATUS_PAUSED 0x12 #define SCD_AUDIO_STATUS_ENDED 0x13 #define SCD_AUDIO_STATUS_ERROR 0x14 #define SCD_AUDIO_STATUS_NO_INFO 0x15 #define SCD_DATA_SIZE_INDEX 3 #define GDC_PARAMS_COUNT 4 #define GDC_CHN_ERROR 0 /** * GD-ROM params */ typedef struct disk_format { int flags; int mode; int sec_size; } disk_format_t; typedef struct gd_state { int req_count; int cmd; int status; int ata_status; int cmd_abort; uint32 requested; uint32 transfered; uint32 callback; uint32 callback_param; uint32 param[GDC_PARAMS_COUNT]; uint32 true_async; /* Current values */ uint32 cdda_track; uint32 data_track; uint32 lba; int cdda_stat; int drv_stat; int drv_media; int disc_change; int disc_num; disk_format_t gdc; } gd_state_t; gd_state_t *get_GDS(void); /** * Lock/Unlock GD syscalls */ int lock_gdsys(void); int unlock_gdsys(void); extern volatile int gdc_lock_state; void gdcExitToGame(void); extern uint8 bios_patch_base[]; extern void *bios_patch_handler; extern uint8 bios_patch_end[]; extern void *gdc_redir; extern uint32 gdc_saved_vector; extern void gdc_syscall_enable(void); extern void gdc_syscall_save(void); extern void gdc_syscall_disable(void); void gdc_syscall_patch(void); extern uint32 menu_saved_vector; extern void menu_syscall_enable(void); extern void menu_syscall_save(void); extern void menu_syscall_disable(void); extern uint32 sys_saved_vector; extern void sys_syscall_enable(void); extern void sys_syscall_save(void); extern void sys_syscall_disable(void); extern uint32 flash_saved_vector; extern void flash_syscall_enable(void); extern void flash_syscall_save(void); extern void flash_syscall_disable(void); extern uint32 bfont_saved_vector; extern uint32 bfont_saved_addr; extern uint8* get_font_address(); extern void bfont_syscall_enable(void); extern void bfont_syscall_save(void); extern void bfont_syscall_disable(void); void enable_syscalls(int all); void disable_syscalls(int all); void restore_syscalls(void); int sys_misc_init(void); #endif <file_sep>/lib/SDL_gui/ProgressBar.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_ProgressBar::GUI_ProgressBar(const char *aname, int x, int y, int w, int h) : GUI_Widget(aname, x, y, w, h) { SDL_Rect in; in.x = 4; in.y = 4; in.w = area.w-8; in.h = area.h-8; SetTransparent(1); value = 0.5; image1 = new GUI_Surface("1", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); image2 = new GUI_Surface("2", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); image1->Fill(NULL, 0x00FFFFFF); image1->Fill(&in, 0xFF000000); image2->Fill(NULL, 0x00FFFFFF); image2->Fill(&in, 0x004040FF); } GUI_ProgressBar::~GUI_ProgressBar(void) { image1->DecRef(); image2->DecRef(); } void GUI_ProgressBar::Update(int force) { if (parent == 0) return; if (force) { int x = (int) (area.w * value); if (flags & WIDGET_TRANSPARENT) parent->Erase(&area); if (image1) { SDL_Rect sr, dr; sr.w = dr.w = image1->GetWidth() - x; sr.h = dr.h = image1->GetHeight(); dr.x = area.x + x; dr.y = area.y; sr.x = x; sr.y = 0; parent->Draw(image1, &sr, &dr); } x = area.w - x; if (image2) { SDL_Rect sr, dr; sr.w = dr.w = image2->GetWidth() - x; sr.h = dr.h = image2->GetHeight(); dr.x = area.x; dr.y = area.y; sr.x = 0; sr.y = 0; parent->Draw(image2, &sr, &dr); } } } void GUI_ProgressBar::SetImage1(GUI_Surface *image) { if (GUI_ObjectKeep((GUI_Object **) &image1, image)) MarkChanged(); } void GUI_ProgressBar::SetImage2(GUI_Surface *image) { if (GUI_ObjectKeep((GUI_Object **) &image2, image)) MarkChanged(); } void GUI_ProgressBar::SetPosition(double a_value) { if (a_value != value) { value = a_value; MarkChanged(); } } extern "C" { GUI_Widget *GUI_ProgressBarCreate(const char *name, int x, int y, int w, int h) { return new GUI_ProgressBar(name, x, y, w, h); } int GUI_ProgressBarCheck(GUI_Widget *widget) { // FIXME not implemented return 0; } void GUI_ProgressBarSetImage1(GUI_Widget *widget, GUI_Surface *image) { ((GUI_ProgressBar *) widget)->SetImage1(image); } void GUI_ProgressBarSetImage2(GUI_Widget *widget, GUI_Surface *image) { ((GUI_ProgressBar *) widget)->SetImage2(image); } void GUI_ProgressBarSetPosition(GUI_Widget *widget, double value) { ((GUI_ProgressBar *) widget)->SetPosition(value); } } <file_sep>/applications/vmu_manager/modules/app_module.h /* DreamShell ##version## app_module.h - VMU Manager app module header Copyright (C)2014-2015 megavolt85 */ #include "ds.h" void VMU_Manager_ItemContextClick(dirent_fm_t *fm_ent); int VMU_Manager_Dump(GUI_Widget *widget); void VMU_Manager_addfileman(GUI_Widget *widget); void Vmu_Manager_Init(App_t* app); void VMU_Manager_EnableMainPage(); void VMU_Manager_vmu(GUI_Widget *widget); void VMU_Manager_info_bar(GUI_Widget *widget); void VMU_Manager_info_bar_clr(GUI_Widget *widget); void VMU_Manager_Exit(GUI_Widget *widget); void VMU_Manager_ItemClick(dirent_fm_t *fm_ent); void VMU_Manager_addfileman(GUI_Widget *widget); void VMU_Manager_ItemContextClick(dirent_fm_t *fm_ent); int VMU_Manager_Dump(GUI_Widget *widget); void VMU_Manager_format(GUI_Widget *widget); void VMU_Manager_sel_dst_vmu(GUI_Widget *widget); void VMU_Manager_make_folder(GUI_Widget *widget); void VMU_Manager_clr_name(GUI_Widget *widget); <file_sep>/src/fs/fat/dc.c /**************************** * DreamShell ##version## * * DreamShell FAT fs * * Created by SWAT * * http://www.dc-swat.ru * ****************************/ #include "ds.h" #include "fs.h" #include "fatfs/diskio.h" #include "fatfs/ff.h" #include "fatfs/integer.h" // #define FATFS_DEBUG 1 // #define FATFS_DMA 1 #define MAX_FAT_MOUNTS _VOLUMES #define MAX_FAT_FILES 16 #define FATFS_LINK_TBL_SIZE 32 typedef struct fatfs_mnt { FATFS *fs; vfs_handler_t *vfsh; kos_blockdev_t *dev; DSTATUS dev_stat; BYTE dev_id; BYTE used; TCHAR dev_path[16]; #ifdef FATFS_DMA BYTE dma; uint8 *dmabuf; #endif } fatfs_mnt_t; typedef struct fatfs { FIL fil __attribute__((aligned(32))); DIR dir; int type; int used; int mode; DWORD lktbl[FATFS_LINK_TBL_SIZE]; dirent_t dent; fatfs_mnt_t *mnt; } fatfs_t; /* Mutex for file handles */ static mutex_t fat_mutex; static int initted = 0; static fatfs_t fh[MAX_FAT_FILES] __attribute__((aligned(32))); static fatfs_mnt_t fat_mnt[MAX_FAT_MOUNTS]; #if _MULTI_PARTITION /* Volume - Partition resolution table */ /* Physical drive number; Partition: 0:Auto detect, 1-4:Forced partition) */ PARTITION VolToPart[16] = { {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} }; #endif #ifdef FATFS_DEBUG # define DBG(x) dbglog x static void put_rc(FRESULT rc, const char *func) { const char *p; static const char str[] = "OK\0" "DISK_ERR\0" "INT_ERR\0" "NOT_READY\0" "NO_FILE\0" "NO_PATH\0" "INVALID_NAME\0" "DENIED\0" "EXIST\0" "INVALID_OBJECT\0" "WRITE_PROTECTED\0" "INVALID_DRIVE\0" "NOT_ENABLED\0" "NO_FILE_SYSTEM\0" "MKFS_ABORTED\0" "TIMEOUT\0" "LOCKED\0" "NOT_ENOUGH_CORE\0" "TOO_MANY_OPEN_FILES\0"; FRESULT i; for (p = str, i = 0; i != rc && *p; i++) { while(*p++); } DBG((DBG_DEBUG, "FATFS: %s: %u FR_%s\n", func, (UINT)rc, p)); } #else # define DBG(x) # define put_rc(r, f) #endif static void fatfs_set_errno(FRESULT rc) { switch(rc) { case FR_OK: /* (0) Succeeded */ errno = 0; break; case FR_DISK_ERR: /* (1) A hard error occurred in the low level disk I/O layer */ //errno = EIO; already set in driver break; case FR_INT_ERR: /* (2) Assertion failed */ errno = EFAULT; break; case FR_NOT_READY: /* (3) The physical drive cannot work */ errno = ENODEV; break; case FR_NO_FILE: /* (4) Could not find the file */ case FR_NO_PATH: /* (5) Could not find the path */ errno = ENOENT; break; case FR_INVALID_NAME: /* (6) The path name format is invalid */ errno = EINVAL; break; case FR_DENIED: /* (7) Access denied due to prohibited access or directory full */ errno = ENOSPC; break; case FR_EXIST: /* (8) Access denied due to prohibited access */ errno = EACCES; break; case FR_INVALID_OBJECT: /* (9) The file/directory object is invalid */ errno = EBADF; break; case FR_WRITE_PROTECTED: /* (10) The physical drive is write protected */ errno = EROFS; break; case FR_INVALID_DRIVE: /* (11) The logical drive number is invalid */ errno = ENXIO; break; case FR_NOT_ENABLED: /* (12) The volume has no work area */ errno = EIDRM; break; case FR_NO_FILESYSTEM: /* (13) There is no valid FAT volume */ errno = EIO; break; case FR_MKFS_ABORTED: /* (14) The f_mkfs() aborted due to any parameter error */ errno = EINVAL; break; case FR_TIMEOUT: /* (15) Could not get a grant to access the volume within defined period */ errno = ETIME; break; case FR_LOCKED: /* (16) The operation is rejected according to the file sharing policy */ errno = EAGAIN; break; case FR_NOT_ENOUGH_CORE: /* (17) LFN working buffer could not be allocated */ errno = ENOMEM; break; case FR_TOO_MANY_OPEN_FILES: /* (18) Number of open files > _FS_SHARE */ errno = EMFILE; break; case FR_INVALID_PARAMETER: /* (19) Given parameter is invalid */ errno = EINVAL; break; default: errno = 0; break; } } #define FAT_GET_HND(hnd, rv) \ file_t fd = ((file_t)hnd) - 1; \ fatfs_t *sf = NULL; \ \ mutex_lock(&fat_mutex); \ \ if(fd > -1 && fd < MAX_FAT_FILES) { \ sf = &fh[fd]; \ } else { \ errno = ENFILE; \ mutex_unlock(&fat_mutex); \ return rv; \ } static void *fat_open(vfs_handler_t * vfs, const char *fn, int flags) { file_t fd; fatfs_t *sf; fatfs_mnt_t *mnt; FRESULT rc; int fat_flags = 0, mode = (flags & O_MODE_MASK); mutex_lock(&fat_mutex); mnt = (fatfs_mnt_t*)vfs->privdata; if(mnt == NULL) { mutex_unlock(&fat_mutex); dbglog(DBG_ERROR, "FATFS: Error, not mounted.\n"); errno = ENOMEM; return NULL; } for(fd = 0; fd < MAX_FAT_FILES; ++fd) { if(fh[fd].used == 0) { sf = &fh[fd]; break; } } if(fd >= MAX_FAT_FILES) { errno = ENFILE; mutex_unlock(&fat_mutex); dbglog(DBG_ERROR, "FATFS: The maximum number of opened files exceeded.\n"); return NULL; } memset_sh4(sf, 0, sizeof(fatfs_t)); rc = f_chdrive(mnt->dev_path); if(rc != FR_OK) { dbglog(DBG_ERROR, "FATFS: Error change drive to - %s\n", mnt->dev_path); put_rc(rc, __func__); fatfs_set_errno(rc); mutex_unlock(&fat_mutex); return NULL; } sf->mode = flags; sf->mnt = mnt; /* Directory */ if(flags & O_DIR) { DBG((DBG_DEBUG, "FATFS: Opening directory - %s%s\n", mnt->dev_path, fn)); rc = f_opendir(&sf->dir, (const TCHAR*)(fn == NULL ? "/" : fn)); if(rc != FR_OK) { DBG((DBG_ERROR, "FATFS: Can't open directory - %s%s\n", mnt->dev_path, fn)); put_rc(rc, __func__); fatfs_set_errno(rc); mutex_unlock(&fat_mutex); return NULL; } sf->used = 1; sf->type = STAT_TYPE_DIR; mutex_unlock(&fat_mutex); return (void *)(fd + 1); } /* File */ switch(mode) { case O_RDONLY: fat_flags = (FA_OPEN_EXISTING | FA_READ); break; case O_WRONLY: fat_flags = FA_WRITE | (flags & O_TRUNC ? FA_CREATE_ALWAYS : FA_CREATE_NEW); break; case O_RDWR: fat_flags = (FA_WRITE | FA_READ) | (flags & O_TRUNC ? FA_CREATE_ALWAYS : FA_CREATE_NEW); break; default: DBG((DBG_ERROR, "FATFS: Uknown flags\n")); errno = EINVAL; mutex_unlock(&fat_mutex); return NULL; } DBG((DBG_DEBUG, "FATFS: Opening file - %s%s 0x%02x\n", mnt->dev_path, fn, (uint8)(fat_flags & 0xff))); sf->type = STAT_TYPE_FILE; rc = f_open(&sf->fil, (const TCHAR*)(fn == NULL ? "/" : fn), fat_flags); if(rc != FR_OK) { DBG((DBG_ERROR, "FATFS: Can't open file - %s%s\n", mnt->dev_path, fn)); put_rc(rc, __func__); fatfs_set_errno(rc); mutex_unlock(&fat_mutex); return NULL; } if(fat_flags & FA_WRITE) { f_sync(&sf->fil); } if((flags & O_APPEND) && sf->fil.fsize > 0) { DBG((DBG_ERROR, "FATFS: Append file...\n")); f_lseek(&sf->fil, sf->fil.fsize - 1); } sf->used = 1; mutex_unlock(&fat_mutex); return (void *)(fd + 1); } static int fat_close(void *hnd) { FAT_GET_HND(hnd, -1); sf->used = 0; FRESULT rc = FR_OK; DBG((DBG_ERROR, "FATFS: Closing file - %d\n", fd)); switch(sf->type) { case STAT_TYPE_FILE: if(sf->fil.cltbl != (DWORD*)&sf->lktbl && sf->fil.cltbl != NULL) { DBG((DBG_ERROR, "FATFS: Freeing linktable\n")); free(sf->fil.cltbl); sf->fil.cltbl = NULL; } rc = f_close(&sf->fil); break; case STAT_TYPE_DIR: rc = f_closedir(&sf->dir); break; default: mutex_unlock(&fat_mutex); return -1; } if(rc != FR_OK) { DBG((DBG_ERROR, "FATFS: Closing error\n")); put_rc(rc, __func__); fatfs_set_errno(rc); mutex_unlock(&fat_mutex); return -1; } mutex_unlock(&fat_mutex); return 0; } static ssize_t fat_read(void *hnd, void *buffer, size_t size) { UINT rs = 0; FRESULT rc; FAT_GET_HND(hnd, -1); if(sf->fil.cltbl == NULL && (sf->mode & O_MODE_MASK) == O_RDONLY) { /* Using fast seek feature */ memset_sh4(&sf->lktbl, 0, FATFS_LINK_TBL_SIZE * sizeof(DWORD)); sf->fil.cltbl = sf->lktbl; /* Enable fast seek feature */ sf->lktbl[0] = FATFS_LINK_TBL_SIZE; /* Set table size to the first item */ /* Create CLMT */ rc = f_lseek(&sf->fil, CREATE_LINKMAP); if(rc == FR_NOT_ENOUGH_CORE) { DBG((DBG_DEBUG, "FATFS: Creating linkmap %d < %ld, retry...", FATFS_LINK_TBL_SIZE, sf->lktbl[0])); size_t lms = sf->fil.cltbl[0]; sf->fil.cltbl = (DWORD*) calloc(lms, sizeof(DWORD)); if(sf->fil.cltbl != NULL) { sf->fil.cltbl[0] = lms; rc = f_lseek(&sf->fil, CREATE_LINKMAP); if(rc != FR_OK) { DBG((DBG_ERROR, "FATFS: Create linkmap %d error: %d", lms, rc)); free(sf->fil.cltbl); sf->fil.cltbl = NULL; } } } else if(rc != FR_OK) { sf->fil.cltbl = NULL; DBG((DBG_ERROR, "FATFS: Create linkmap %ld error: %d", sf->lktbl[0], rc)); } else { DBG((DBG_DEBUG, "FATFS: Created linkmap %ld dwords\n", sf->lktbl[0])); } } rc = f_read(&sf->fil, buffer, (UINT) size, &rs); if(rc != FR_OK) { put_rc(rc, __func__); fatfs_set_errno(rc); mutex_unlock(&fat_mutex); return -1; } // DBG((DBG_DEBUG, "FATFS: Read %d %d\n", size, rs)); mutex_unlock(&fat_mutex); return (ssize_t) rs; } static ssize_t fat_write(void * hnd, const void *buffer, size_t cnt) { UINT bw = 0; FRESULT rc; FAT_GET_HND(hnd, -1); rc = f_write(&sf->fil, buffer, (UINT) cnt, &bw); if(rc != FR_OK) { put_rc(rc, __func__); fatfs_set_errno(rc); mutex_unlock(&fat_mutex); return -1; } // DBG((DBG_DEBUG, "FATFS: Write %d %d\n", cnt, bw)); // f_sync(&sf->fil); mutex_unlock(&fat_mutex); return (ssize_t)bw; } static off_t fat_tell(void * hnd) { FAT_GET_HND(hnd, -1); off_t off = (off_t)f_tell(&sf->fil); mutex_unlock(&fat_mutex); return off; } static off_t fat_seek(void * hnd, off_t offset, int whence) { FRESULT rc; DWORD off; FAT_GET_HND(hnd, -1); switch (whence) { case SEEK_SET: off = (DWORD) offset; break; case SEEK_CUR: off = (DWORD) (sf->fil.fptr + offset); break; case SEEK_END: off = (DWORD) (sf->fil.fsize + offset); break; default: errno = EINVAL; mutex_unlock(&fat_mutex); return -1; } // DBG((DBG_DEBUG, "FATFS: Seeking: whence=%d req=%ld res=%ld\n", whence, offset, off)); rc = f_lseek(&sf->fil, off); if(rc != FR_OK) { put_rc(rc, __func__); fatfs_set_errno(rc); mutex_unlock(&fat_mutex); return -1; } mutex_unlock(&fat_mutex); return (off_t) sf->fil.fptr; } static size_t fat_total(void * hnd) { FAT_GET_HND(hnd, -1); size_t sz = (off_t)f_size(&sf->fil); mutex_unlock(&fat_mutex); return sz; } static dirent_t *fat_readdir(void * hnd) { FILINFO inf; FRESULT rc; FAT_GET_HND(hnd, NULL); memset_sh4(&sf->dent, 0, sizeof(dirent_t)); #if _USE_LFN inf.lfname = sf->dent.name; inf.lfsize = NAME_MAX; #endif rc = f_readdir(&sf->dir, &inf); if(rc != FR_OK) { DBG((DBG_ERROR, "FATFS: Error reading directory entry\n")); put_rc(rc, __func__); fatfs_set_errno(rc); mutex_unlock(&fat_mutex); return NULL; } if(inf.fname[0] == 0) { mutex_unlock(&fat_mutex); return NULL; } //#ifdef FATFS_DEBUG //#if _USE_LFN // dbglog(DBG_DEBUG, "FATFS: Dir entry = %s %ld\n", (*inf.lfname ? inf.lfname : inf.fname), inf.fsize); //#else // dbglog(DBG_DEBUG, "FATFS: Dir entry = %s %ld\n", inf.fname, inf.fsize); //#endif //#endif if(!*inf.lfname) { strncpy(sf->dent.name, inf.fname, 12); } // TODO date and time parsing sf->dent.time = (time_t) inf.ftime; if(inf.fattrib & AM_DIR) { sf->dent.attr = O_DIR; sf->dent.size = -1; } else { sf->dent.attr = 0; sf->dent.size = inf.fsize; } // if(inf.fattrib & AM_RDO) { // sf->dent.attr |= O_RDONLY; // } else { // sf->dent.attr |= O_RDWR; // } mutex_unlock(&fat_mutex); return &sf->dent; } static int fat_rewinddir(void * hnd) { FRESULT rc; FAT_GET_HND(hnd, -1); rc = f_rewinddir(&sf->dir); if(rc != FR_OK) { DBG((DBG_ERROR, "FATFS: Error rewind directory\n")); put_rc(rc, __func__); fatfs_set_errno(rc); mutex_unlock(&fat_mutex); return -1; } mutex_unlock(&fat_mutex); return 0; } /* !=0: Sector number, 0: Failed - invalid cluster# */ DWORD clust2sect(FATFS *fs, DWORD clst); static int fat_ioctl(void * hnd, int cmd, va_list ap) { DRESULT rc = RES_OK; FAT_GET_HND(hnd, -1); void *data = va_arg(ap, void *); switch(cmd) { case FATFS_IOCTL_GET_BOOT_SECTOR_DATA: rc = disk_read(sf->fil.fs->drv, (BYTE*)data, 0, 1); break; case FATFS_IOCTL_GET_FD_LBA: { DWORD lba = clust2sect(sf->fil.fs, sf->fil.sclust); if(lba > 0) { *(uint32 *)data = lba; rc = RES_OK; } else { rc = RES_ERROR; } break; } case FATFS_IOCTL_GET_FD_LINK_MAP: if(sf->fil.cltbl[0]) { memcpy_sh4(data, &sf->fil.cltbl, sf->fil.cltbl[0] * sizeof(DWORD)); } else { memset_sh4(data, 0, sizeof(DWORD)); } break; default: rc = disk_ioctl(sf->fil.fs->drv, (BYTE)cmd, data); break; } mutex_unlock(&fat_mutex); return rc == RES_OK ? 0 : -1; } #define FAT_GET_MNT() \ FRESULT rc = FR_OK; \ fatfs_mnt_t *mnt; \ mutex_lock(&fat_mutex); \ mnt = (fatfs_mnt_t*)vfs->privdata; \ if(mnt == NULL) \ goto error; \ if(f_chdrive(mnt->dev_path) != FR_OK) \ goto error static int fat_rename(struct vfs_handler * vfs, const char *fn1, const char *fn2) { FAT_GET_MNT(); if((rc = f_rename((const TCHAR*)fn1, (const TCHAR*)fn2)) != FR_OK) { goto error; } mutex_unlock(&fat_mutex); return 0; error: fatfs_set_errno(rc); put_rc(rc, __func__); mutex_unlock(&fat_mutex); return -1; } static int fat_unlink(struct vfs_handler * vfs, const char *fn) { FAT_GET_MNT(); if((rc = f_unlink((const TCHAR*)fn)) != FR_OK) { goto error; } mutex_unlock(&fat_mutex); return 0; error: fatfs_set_errno(rc); put_rc(rc, __func__); mutex_unlock(&fat_mutex); return -1; } static void *fat_mmap(void * hnd) { uint8 *data = NULL; int size = 0; int cnt = 0; size = fat_total(hnd); DBG((DBG_DEBUG, "FATFS: Mmap %d\n", size)); if(size) { data = (uint8*) memalign(32, size); cnt = fat_read(hnd, data, size); if(cnt != size) { free(data); return NULL; } return (void*) data; } return NULL; } static int fat_complete(void * hnd, ssize_t * rv) { FRESULT rc; FAT_GET_HND(hnd, -1); DBG((DBG_DEBUG, "FATFS: fs_complete\n")); if((rc = f_sync(&sf->fil)) != FR_OK) { goto error; } mutex_unlock(&fat_mutex); return 0; error: fatfs_set_errno(rc); put_rc(rc, __func__); mutex_unlock(&fat_mutex); return -1; } static int fat_mkdir(struct vfs_handler * vfs, const char * fn) { FAT_GET_MNT(); if((rc = f_mkdir((const TCHAR*)fn)) != FR_OK) { goto error; } mutex_unlock(&fat_mutex); return 0; error: fatfs_set_errno(rc); put_rc(rc, __func__); mutex_unlock(&fat_mutex); return -1; } static int fat_rmdir(struct vfs_handler * vfs, const char * fn) { FAT_GET_MNT(); if((rc = f_unlink((const TCHAR*)fn)) != FR_OK) { goto error; } mutex_unlock(&fat_mutex); return 0; error: fatfs_set_errno(rc); put_rc(rc, __func__); mutex_unlock(&fat_mutex); return -1; } static int fat_fcntl(void *hnd, int cmd, va_list ap) { int rv = -1; (void)ap; FAT_GET_HND(hnd, -1); switch(cmd) { case F_GETFL: rv = sf->mode; break; case F_SETFL: case F_GETFD: case F_SETFD: rv = 0; break; default: errno = EINVAL; } mutex_unlock(&fat_mutex); return rv; } static int fat_stat(struct vfs_handler *vfs, const char *fn, struct stat *st, int flag) { FILINFO inf; FAT_GET_MNT(); if((rc = f_stat((const TCHAR*)fn, &inf)) != FR_OK) { goto error; } memset_sh4(st, 0, sizeof(struct stat)); st->st_dev = (dev_t)((ptr_t)vfs); st->st_mode = S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH; st->st_nlink = 1; // TODO st->st_atime = inf.fdate + inf.ftime; st->st_mtime = inf.fdate + inf.ftime; st->st_ctime = inf.fdate + inf.ftime; if(inf.fattrib & AM_DIR) { st->st_mode |= S_IFDIR; } else { st->st_mode |= S_IFREG; st->st_size = inf.fsize; st->st_blksize = 1 << mnt->dev->l_block_size; st->st_blocks = inf.fsize >> mnt->dev->l_block_size; if(inf.fsize & (st->st_blksize - 1)) { ++st->st_blocks; } } mutex_unlock(&fat_mutex); return 0; error: fatfs_set_errno(rc); put_rc(rc, __func__); mutex_unlock(&fat_mutex); return -1; } static int fat_fstat(void *hnd, struct stat *st) { FAT_GET_HND(hnd, -1); memset_sh4(st, 0, sizeof(struct stat)); st->st_nlink = 1; st->st_blksize = 1 << sf->mnt->dev->l_block_size; st->st_dev = (dev_t)((ptr_t)sf->mnt->dev); st->st_mode = S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH; if(sf->type == STAT_TYPE_DIR) { st->st_mode |= S_IFDIR; } else { st->st_mode |= S_IFREG; st->st_size = sf->fil.fsize; st->st_blocks = sf->fil.fsize >> sf->mnt->dev->l_block_size; if(sf->fil.fsize & (st->st_blksize - 1)) { ++st->st_blocks; } } mutex_unlock(&fat_mutex); return 0; } int is_fat_partition(uint8 partition_type) { switch(partition_type) { case 0x04: /* 32MB */ case 0x06: /* Over 32 to 2GB */ return 16; case 0x0B: case 0x0C: return 32; default: return 0; } } #define FAT_GET_MOUNT \ fatfs_mnt_t *mnt = NULL; \ if(pdrv < MAX_FAT_MOUNTS && fat_mnt[pdrv].dev != NULL) { \ mnt = &fat_mnt[pdrv]; \ } else { \ DBG((DBG_ERROR, "FATFS: %s[%d] pdrv error\n", __func__, pdrv)); \ return STA_NOINIT; \ } DSTATUS disk_initialize ( BYTE pdrv /* Physical drive nmuber (0..) */ ) { FAT_GET_MOUNT; if(mnt->dev->init(mnt->dev) < 0) { mnt->dev_stat |= STA_NOINIT; } else { mnt->dev_stat &= ~STA_NOINIT; } DBG((DBG_DEBUG, "FATFS: %s[%d] 0x%02x\n", __func__, pdrv, mnt->dev_stat)); return mnt->dev_stat; } /*-----------------------------------------------------------------------*/ /* Get Disk Status */ /*-----------------------------------------------------------------------*/ DSTATUS disk_status ( BYTE pdrv /* Physical drive nmuber (0..) */ ) { FAT_GET_MOUNT; // DBG((DBG_DEBUG, "FATFS: %s[%d] 0x%02x\n", __func__, pdrv, mnt->dev_stat)); return mnt->dev_stat; } /*-----------------------------------------------------------------------*/ /* Read Sector(s) */ /*-----------------------------------------------------------------------*/ DRESULT disk_read ( BYTE pdrv, /* Physical drive nmuber (0..) */ BYTE *buff, /* Data buffer to store read data */ DWORD sector, /* Sector address (LBA) */ DWORD count /* Number of sectors to read */ ) { FAT_GET_MOUNT; uint8 *dest = buff; #ifdef FATFS_DMA if(mnt->dma && ((uint32)buff & 0x1F) && count <= mnt->fs->csize) { dest = mnt->dmabuf; } #endif DBG((DBG_DEBUG, "FATFS: %s[%d] %ld %d 0x%08lx 0x%08lx\n", __func__, pdrv, sector, (int)count, (uint32)buff, (uint32)dest)); if(mnt->dev->read_blocks(mnt->dev, sector, count, dest) < 0) { DBG((DBG_ERROR, "FATFS: %s[%d] dma error: %d\n", __func__, pdrv, errno)); return (errno == EOVERFLOW ? RES_PARERR : RES_ERROR); } if (dest != buff) { memcpy_sh4(buff, dest, count << mnt->dev->l_block_size); } return RES_OK; } /*-----------------------------------------------------------------------*/ /* Write Sector(s) */ /*-----------------------------------------------------------------------*/ #if _USE_WRITE DRESULT disk_write ( BYTE pdrv, /* Physical drive nmuber (0..) */ const BYTE *buff, /* Data to be written */ DWORD sector, /* Sector address (LBA) */ DWORD count /* Number of sectors to write */ ) { FAT_GET_MOUNT; uint8 *src = (uint8 *)buff; int rc; #ifdef FATFS_DMA if(mnt->dma && ((uint32)buff & 0x1F) && count <= mnt->fs->csize) { memcpy_sh4(mnt->dmabuf, buff, count << mnt->dev->l_block_size); src = mnt->dmabuf; } #endif DBG((DBG_DEBUG, "FATFS: %s[%d] %ld %d 0x%08lx 0x%08lx\n", __func__, pdrv, sector, (int)count, (uint32)buff, (uint32)src)); rc = mnt->dev->write_blocks(mnt->dev, sector, count, src); if(rc < 0) { DBG((DBG_ERROR, "FATFS: %s[%d]%s error: %d\n", __func__, pdrv, (mnt->dma ? " dma" : ""), errno)); return errno == EOVERFLOW ? RES_PARERR : RES_ERROR; } return RES_OK; } #endif /*-----------------------------------------------------------------------*/ /* Miscellaneous Functions */ /*-----------------------------------------------------------------------*/ #if _USE_IOCTL DRESULT disk_ioctl ( BYTE pdrv, /* Physical drive nmuber (0..) */ BYTE cmd, /* Control code */ void *buff /* Buffer to send/receive control data */ ) { FAT_GET_MOUNT; switch(cmd) { case CTRL_SYNC: mnt->dev->flush(mnt->dev); DBG((DBG_DEBUG, "FATFS: %s[%d] Sync\n", __func__, pdrv)); return RES_OK; case GET_SECTOR_COUNT: *(ulong*)buff = mnt->dev->count_blocks(mnt->dev); DBG((DBG_DEBUG, "FATFS: %s[%d] Sector count: %d\n", __func__, pdrv, *(ushort*)buff)); return RES_OK; case GET_SECTOR_SIZE: *(ushort*)buff = (1 << mnt->dev->l_block_size); DBG((DBG_DEBUG, "FATFS: %s[%d] Sector size: %d\n", __func__, pdrv, *(ushort*)buff)); return RES_OK; case GET_BLOCK_SIZE: *(ushort*)buff = (1 << mnt->dev->l_block_size); DBG((DBG_DEBUG, "FATFS: %s[%d] Block size: %d\n", __func__, pdrv, *(ushort*)buff)); return RES_OK; case CTRL_TRIM: DBG((DBG_DEBUG, "FATFS: %s[%d] Trim sector\n", __func__, pdrv)); return RES_OK; default: DBG((DBG_ERROR, "FATFS: %s[%d] Unknown control code: %d\n", __func__, pdrv, cmd)); return RES_PARERR; } } #endif /* This is a template that will be used for each mount */ static vfs_handler_t vh = { /* Name Handler */ { { 0 }, /* name */ 0, /* in-kernel */ 0x00010000, /* Version 1.0 */ NMMGR_FLAGS_NEEDSFREE, /* We malloc each VFS struct */ NMMGR_TYPE_VFS, /* VFS handler */ NMMGR_LIST_INIT /* list */ }, 0, NULL, /* no cacheing, privdata */ fat_open, /* open */ fat_close, /* close */ fat_read, /* read */ fat_write, /* write */ fat_seek, /* seek */ fat_tell, /* tell */ fat_total, /* total */ fat_readdir, /* readdir */ fat_ioctl, /* ioctl */ fat_rename, /* rename */ fat_unlink, /* unlink */ fat_mmap, /* mmap */ fat_complete, /* complete */ fat_stat, /* stat */ fat_mkdir, /* mkdir */ fat_rmdir, /* rmdir */ fat_fcntl, /* fcntl */ NULL, /* poll */ NULL, /* link */ NULL, /* symlink */ NULL, /* seek64 */ NULL, /* tell64 */ NULL, /* total64 */ NULL, /* readlink */ fat_rewinddir, /* rewinddir */ fat_fstat /* fstat */ }; int fs_fat_mount(const char *mp, kos_blockdev_t *dev, int dma, int partition) { fatfs_mnt_t *mnt = NULL; FRESULT rc; int i; if(!initted) { return -1; } mutex_lock(&fat_mutex); for(i = 0; i < MAX_FAT_MOUNTS; i++) { if(fat_mnt[i].dev == NULL) { mnt = &fat_mnt[i]; memset_sh4(mnt, 0, sizeof(fatfs_mnt_t)); mnt->dev_id = i; DBG((DBG_DEBUG, "FATFS: Mounting device %d to %s\n", mnt->dev_id, mp)); break; } } if(mnt == NULL) { dbglog(DBG_ERROR, "FATFS: The maximum number of mounts exceeded.\n"); goto error; } if(dev->init(dev) < 0) { dbglog(DBG_ERROR, "FATFS: Can't initialize block device: %d\n", errno); goto error; } mnt->dev = dev; VolToPart[mnt->dev_id].pd = mnt->dev_id; VolToPart[mnt->dev_id].pt = partition + 1; /* Create a VFS structure */ if(!(mnt->vfsh = (vfs_handler_t *)malloc(sizeof(vfs_handler_t)))) { dbglog(DBG_ERROR, "FATFS: Out of memory for creating vfs handler\n"); goto error; } memcpy_sh4(mnt->vfsh, &vh, sizeof(vfs_handler_t)); strcpy(mnt->vfsh->nmmgr.pathname, mp); mnt->vfsh->privdata = mnt; /* Create a FATFS structure */ if(!(mnt->fs = (FATFS *)malloc(sizeof(FATFS)))) { dbglog(DBG_ERROR, "FATFS: Out of memory for creating FATFS native mount structure\n"); goto error; } #ifdef FATFS_DMA mnt->dma = dma; if (mnt->dma) { uint8 tmp_dma[512] __attribute__((aligned(32))); mnt->dmabuf = &tmp_dma[0]; } #else if(dma) { dbglog(DBG_WARNING, "FATFS: DMA is disabled, force PIO mode.\n"); } #endif snprintf((TCHAR*)mnt->dev_path, sizeof(mnt->dev_path), "%d:", mnt->dev_id); rc = f_mount(mnt->fs, mnt->dev_path, 1); #ifdef FATFS_DMA mnt->dmabuf = NULL; #endif if(rc != FR_OK) { fatfs_set_errno(rc); dbglog(DBG_ERROR, "FATFS: Error %d in mounting a logical drive %d\n", errno, mnt->dev_id); #ifdef FATFS_DEBUG put_rc(rc, __func__); #endif goto error; } #ifdef FATFS_DMA if(mnt->dma) { DBG((DBG_DEBUG, "FATFS: Allocating %d bytes for DMA buffer\n", mnt->fs->csize * _MAX_SS)); if(!(mnt->dmabuf = (uint8 *)memalign(32, mnt->fs->csize * _MAX_SS))) { dbglog(DBG_ERROR, "FATFS: Out of memory for DMA buffer\n"); } else { DBG((DBG_DEBUG, "FATFS: Allocated %d bytes for DMA buffer at %p\n", mnt->fs->csize * _MAX_SS, mnt->dmabuf)); } } #endif FATFS *fs; DWORD fre_clust, fre_sect, tot_sect; rc = f_getfree(mnt->dev_path, &fre_clust, &fs); /* Get total sectors and free sectors */ tot_sect = (fs->n_fatent - 2) * fs->csize; fre_sect = fre_clust * fs->csize; if(rc == FR_OK) { dbglog(DBG_DEBUG, "FATFS: %lu KiB total drive space and %lu KiB available.\n", tot_sect / 2, fre_sect / 2); } DBG((DBG_DEBUG, "FATFS: FAT start sector: %ld\n", mnt->fs->fatbase)); DBG((DBG_DEBUG, "FATFS: Data start sector: %ld\n", mnt->fs->database)); DBG((DBG_DEBUG, "FATFS: Root directory start sector: %ld\n", mnt->fs->dirbase * mnt->fs->csize)); /* Register with the VFS */ if(nmmgr_handler_add(&mnt->vfsh->nmmgr)) { dbglog(DBG_ERROR, "FATFS: Couldn't add vfs to nmmgr\n"); goto error; } mutex_unlock(&fat_mutex); return 0; error: if(mnt) { if(mnt->vfsh) { free(mnt->vfsh); } if(mnt->fs) { free(mnt->fs); } if(mnt->dev) { mnt->dev = NULL; } #ifdef FATFS_DMA if(mnt->dmabuf) { free(mnt->dmabuf); } #endif memset_sh4(mnt, 0, sizeof(fatfs_mnt_t)); } if(dev) { dev->shutdown(dev); } mutex_unlock(&fat_mutex); return -1; } int fs_fat_unmount(const char *mp) { fatfs_mnt_t *mnt; int found = 0, rv = 0, i; mutex_lock(&fat_mutex); for(i = 0; i < MAX_FAT_MOUNTS; i++) { if(fat_mnt[i].vfsh != NULL && !strcmp(mp, fat_mnt[i].vfsh->nmmgr.pathname)) { mnt = &fat_mnt[i]; found = 1; break; } } if(found) { /* TODO Check for open files */ nmmgr_handler_remove(&mnt->vfsh->nmmgr); if(mnt) { if(mnt->vfsh) { free(mnt->vfsh); } if(mnt->fs) { free(mnt->fs); } if(mnt->dev) { mnt->dev->shutdown(mnt->dev); mnt->dev = NULL; } #ifdef FATFS_DMA if(mnt->dmabuf) { free(mnt->dmabuf); } #endif } } else { errno = ENOENT; rv = -1; } mutex_unlock(&fat_mutex); return rv; } int fs_fat_is_mounted(const char *mp) { int i, found = 0; mutex_lock(&fat_mutex); for(i = 0; i < MAX_FAT_MOUNTS; i++) { if(fat_mnt[i].vfsh != NULL && !strcmp(mp, fat_mnt[i].vfsh->nmmgr.pathname)) { found = i+1; break; } } mutex_unlock(&fat_mutex); return found; } int fs_fat_init(void) { if(initted) { return 0; } /* Reset mounts */ memset_sh4(fat_mnt, 0, sizeof(fat_mnt)); /* Reset fd's */ memset_sh4(fh, 0, sizeof(fh)); /* Init thread mutex */ mutex_init(&fat_mutex, MUTEX_TYPE_NORMAL); initted = 1; return 0; } int fs_fat_shutdown(void) { int i; fatfs_mnt_t *mnt; if(!initted) { return 0; } for(i = 0; i < MAX_FAT_MOUNTS; i++) { if(fat_mnt[i].dev != NULL) { mnt = &fat_mnt[i]; nmmgr_handler_remove(&mnt->vfsh->nmmgr); if(mnt->vfsh) free(mnt->vfsh); if(mnt->fs) free(mnt->fs); if(mnt->dev) { mnt->dev->shutdown(mnt->dev); mnt->dev = NULL; } #ifdef FATFS_DMA if(mnt->dmabuf) { free(mnt->dmabuf); } #endif } } mutex_destroy(&fat_mutex); initted = 0; return 0; } <file_sep>/applications/region_changer/modules/module.c /* DreamShell ##version## module.c - Region Changer module Copyright (C)2010-2014 SWAT */ #include "ds.h" #include "rc.h" DEFAULT_MODULE_HEADER(app_region_changer); int tolua_RC_open(lua_State* tolua_S); /* Japan (red swirl) - 0x30 Japan (black swirl) - 0x58 USA (red swirl) - 0x31 USA (black swirl) - 0x59 Europe (blue swirl) - 0x32 Europe (black swirl) - 0x5A */ uint8 *flash_factory_set_country(uint8 *data, int country, int black_swirl) { switch(country) { case 1: data[2] = black_swirl ? 0x58 : 0x30; break; case 2: data[2] = black_swirl ? 0x59 : 0x31; break; case 3: data[2] = black_swirl ? 0x5A : 0x32; break; default: break; } return data; } uint8 *flash_factory_set_broadcast(uint8 *data, int broadcast) { switch(broadcast) { case 1: data[4] = 0x30; break; case 2: data[4] = 0x31; break; case 3: data[4] = 0x32; break; case 4: data[4] = 0x33; break; default: break; } return data; } uint8 *flash_factory_set_lang(uint8 *data, int lang) { switch(lang) { case 1: data[3] = 0x30; break; case 2: data[3] = 0x31; break; case 3: data[3] = 0x32; break; case 4: data[3] = 0x33; break; case 5: data[3] = 0x34; break; case 6: data[3] = 0x35; break; default: break; } return data; } flash_factory_values_t *flash_factory_get_values(uint8 *data) { flash_factory_values_t *values = (flash_factory_values_t*) malloc(sizeof(flash_factory_values_t)); // Country if(data[2] == 0x58 || data[2] == 0x30) { values->country = 1; values->black_swirl = data[2] == 0x58 ? 1 : 0; } else if(data[2] == 0x59 || data[2] == 0x31) { values->country = 2; values->black_swirl = data[2] == 0x59 ? 1 : 0; } else if(data[2] == 0x5A || data[2] == 0x32) { values->country = 3; values->black_swirl = data[2] == 0x5A ? 1 : 0; } else { values->country = 0; values->black_swirl = 0; } // Lang if(data[3] == 0x30) { values->lang = 1; } else if(data[3] == 0x31) { values->lang = 2; } else if(data[3] == 0x32) { values->lang = 3; } else if(data[3] == 0x33) { values->lang = 4; } else if(data[3] == 0x34) { values->lang = 5; } else if(data[3] == 0x35) { values->lang = 6; } else { values->lang = 0; } // Broadcast if(data[4] == 0x30) { values->broadcast = 1; } else if(data[4] == 0x31) { values->broadcast = 2; } else if(data[4] == 0x32) { values->broadcast = 3; } else if(data[4] == 0x33) { values->broadcast = 4; } else { values->broadcast = 0; } return values; } void flash_factory_free_values(flash_factory_values_t *values) { free(values); } void flash_factory_free_data(uint8 *data) { free(data); } int lib_open(klibrary_t * lib) { lua_State *lua = GetLuaState(); if(lua != NULL) { tolua_RC_open(lua); } RegisterLuaLib(lib_get_name(), (LuaRegLibOpen *)tolua_RC_open); return nmmgr_handler_add(&ds_app_region_changer_hnd.nmmgr); } int lib_close(klibrary_t * lib) { UnregisterLuaLib(lib_get_name()); return nmmgr_handler_remove(&ds_app_region_changer_hnd.nmmgr); } <file_sep>/lib/libparallax/src/mat3d.c /* Parallax for KallistiOS ##version## mat3d.c (c)2001-2002 <NAME> (c)2002 <NAME> and <NAME> (c)2013-2014 SWAT */ #include <assert.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <dc/fmath.h> #include <dc/matrix.h> #include <dc/video.h> #include <plx/matrix.h> #include "utils.h" /* Most of this file was pulled from KGL's gltrans.c. Why did we do that instead of just suggesting linking with KGL to get them? Because: 1) There are things KGL does that aren't really necessary or germane for non-KGL usage, and you're trying to avoid initializing all of KGL, right? :) 2) KGL is a work in progress and is attempting over time to become more and more GL compliant. On the other hand, we just want simple and working 3D matrix functions. */ /* Degrees<->Radians conversion */ #define DEG2RAD (F_PI / 180.0f) #define RAD2DEG (180.0f / F_PI) /* Matrix stacks */ #define MAT_MV_STACK_CNT 32 #define MAT_P_STACK_CNT 2 static matrix_t mat_mv_stack[MAT_MV_STACK_CNT] __attribute__((aligned(32))); static int mat_mv_stack_top; static matrix_t mat_p_stack[MAT_P_STACK_CNT] __attribute__((aligned(32))); static int mat_p_stack_top; /* Active mode matrices */ static int matrix_mode; static matrix_t trans_mats[PLX_MAT_COUNT] __attribute__((aligned(32))); /* Screenview parameters */ static vector_t vp, vp_size, vp_scale, vp_offset; static float vp_z_fudge; static float depthrange_near, depthrange_far; /* Set which matrix we are working on */ void plx_mat3d_mode(int mode) { matrix_mode = mode; } /* Load the identitiy matrix */ void plx_mat3d_identity() { mat_identity(); mat_store(trans_mats + matrix_mode); } static matrix_t ml __attribute__((aligned(32))); /* Load an arbitrary matrix */ void plx_mat3d_load(matrix_t * m) { memcpy_sh4(trans_mats + matrix_mode, m, sizeof(matrix_t)); } /* Save the matrix (whoa!) */ void plx_mat3d_store(matrix_t * m) { memcpy_sh4(m, trans_mats + matrix_mode, sizeof(matrix_t)); } /* Set the depth range */ void plx_mat3d_depthrange(float n, float f) { /* clamp the values... */ if (n < 0.0f) n = 0.0f; if (n > 1.0f) n = 1.0f; if (f < 0.0f) f = 0.0f; if (f > 1.0f) f = 1.0f; depthrange_near = n; depthrange_far = f; /* Adjust the viewport scale and offset for Z */ vp_scale.z = ((f - n) / 2.0f); vp_offset.z = (n + f) / 2.0f; } /* Set the viewport */ void plx_mat3d_viewport(int x1, int y1, int width, int height) { vp.x = x1; vp.y = y1; vp_size.x = width; vp_size.y = height; /* Calculate the viewport scale and offset */ vp_scale.x = (float)width / 2.0f; vp_offset.x = vp_scale.x + (float)x1; vp_scale.y = (float)height / 2.0f; vp_offset.y = vp_scale.y + (float)y1; vp_scale.z = (depthrange_far -depthrange_near) / 2.0f; vp_offset.z = (depthrange_near + depthrange_far) / 2.0f; /* FIXME: Why does the depth value need some nudging? * This makes polys with Z=0 work. */ vp_offset.z += 0.0001f; } /* Setup perspective */ void plx_mat3d_perspective(float angle, float aspect, float znear, float zfar) { float xmin, xmax, ymin, ymax; ymax = znear * ftan(angle * F_PI / 360.0f); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; plx_mat3d_frustum(xmin, xmax, ymin, ymax, znear, zfar); } static matrix_t mf __attribute__((aligned(32))) = { { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, -1.0f }, { 0.0f, 0.0f, 0.0f, 0.0f } }; void plx_mat3d_frustum(float left, float right, float bottom, float top, float znear, float zfar) { float x, y, a, b, c, d; assert(znear > 0.0f); x = (2.0f * znear) / (right - left); y = (2.0f * znear) / (top - bottom); a = (right + left) / (right - left); b = (top + bottom) / (top - bottom); c = -(zfar + znear) / (zfar - znear); d = -(2.0f * zfar * znear) / (zfar - znear); mf[0][0] = x; mf[2][0] = a; mf[1][1] = y; mf[2][1] = b; mf[2][2] = c; mf[3][2] = d; mat_load(trans_mats + matrix_mode); mat_apply(&mf); mat_store(trans_mats + matrix_mode); } static matrix_t mo __attribute__((aligned(32))) = { { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }; void plx_mat3d_ortho(float left, float right, float bottom, float top, float znear, float zfar) { float x, y, z; float tx, ty, tz; x = 2.0f / (right - left); y = 2.0f / (top - bottom); z = -2.0f / (zfar - znear); tx = -(right + left) / (right - left); ty = -(top + bottom) / (top - bottom); tz = -(zfar + znear) / (zfar - znear); mo[0][0] = x; mo[1][1] = y; mo[2][2] = z; mo[3][0] = tx; mo[3][1] = ty; mo[3][2] = tz; mat_load(trans_mats + matrix_mode); mat_apply(&mo); mat_store(trans_mats + matrix_mode); } void plx_mat3d_push() { switch (matrix_mode) { case PLX_MAT_MODELVIEW: assert_msg(mat_mv_stack_top < MAT_MV_STACK_CNT, "Modelview stack overflow."); if (mat_mv_stack_top >= MAT_MV_STACK_CNT) return; memcpy_sh4(mat_mv_stack + mat_mv_stack_top, trans_mats + matrix_mode, sizeof(matrix_t)); mat_mv_stack_top++; break; case PLX_MAT_PROJECTION: assert_msg(mat_p_stack_top < MAT_P_STACK_CNT, "Projection stack overflow."); if (mat_p_stack_top >= MAT_P_STACK_CNT) return; memcpy_sh4(mat_p_stack + mat_p_stack_top, trans_mats + matrix_mode, sizeof(matrix_t)); mat_p_stack_top++; break; default: assert_msg( 0, "Invalid matrix type" ); } } void plx_mat3d_pop() { switch(matrix_mode) { case PLX_MAT_MODELVIEW: assert_msg(mat_mv_stack_top > 0, "Modelview stack underflow."); if (mat_mv_stack_top <= 0) return; mat_mv_stack_top--; memcpy_sh4(trans_mats + matrix_mode, mat_mv_stack + mat_mv_stack_top, sizeof(matrix_t)); break; case PLX_MAT_PROJECTION: assert_msg(mat_p_stack_top > 0, "Projection stack underflow."); if (mat_p_stack_top <= 0) return; mat_p_stack_top--; memcpy_sh4(trans_mats + matrix_mode, mat_p_stack + mat_p_stack_top, sizeof(matrix_t)); break; default: assert_msg( 0, "Invalid matrix type" ); } } void plx_mat3d_peek() { switch(matrix_mode) { case PLX_MAT_MODELVIEW: assert_msg(mat_mv_stack_top > 0, "Modelview stack underflow."); if (mat_mv_stack_top <= 0) return; memcpy_sh4(trans_mats + matrix_mode, mat_mv_stack + mat_mv_stack_top - 1, sizeof(matrix_t)); break; case PLX_MAT_PROJECTION: assert_msg(mat_p_stack_top > 0, "Projection stack underflow."); if (mat_p_stack_top <= 0) return; memcpy_sh4(trans_mats + matrix_mode, mat_p_stack + mat_p_stack_top - 1, sizeof(matrix_t)); break; default: assert_msg( 0, "Invalid matrix type" ); } } static matrix_t mr __attribute__((aligned(32))) = { { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }; void plx_mat3d_rotate(float angle, float x, float y, float z) { float rcos = fcos(angle * DEG2RAD); float rsin = fsin(angle * DEG2RAD); float invrcos = (1.0f - rcos); float mag = fsqrt(x*x + y*y + z*z); float xx, yy, zz, xy, yz, zx; if (mag < 1.0e-6) { /* Rotation vector is too small to be significant */ return; } /* Normalize the rotation vector */ x /= mag; y /= mag; z /= mag; xx = x * x; yy = y * y; zz = z * z; xy = (x * y * invrcos); yz = (y * z * invrcos); zx = (z * x * invrcos); /* Generate the rotation matrix */ mr[0][0] = xx + rcos * (1.0f - xx); mr[2][1] = yz - x * rsin; mr[1][2] = yz + x * rsin; mr[1][1] = yy + rcos * (1.0f - yy); mr[2][0] = zx + y * rsin; mr[0][2] = zx - y * rsin; mr[2][2] = zz + rcos * (1.0f - zz); mr[1][0] = xy - z * rsin; mr[0][1] = xy + z * rsin; mat_load(trans_mats + matrix_mode); mat_apply(&mr); mat_store(trans_mats + matrix_mode); } static matrix_t ms __attribute__((aligned(32))) = { { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }; void plx_mat3d_scale(float x, float y, float z) { ms[0][0] = x; ms[1][1] = y; ms[2][2] = z; mat_load(trans_mats + matrix_mode); mat_apply(&ms); mat_store(trans_mats + matrix_mode); } static matrix_t mt __attribute__((aligned(32))) = { { 1.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }; void plx_mat3d_translate(float x, float y, float z) { mt[3][0] = x; mt[3][1] = y; mt[3][2] = z; mat_load(trans_mats + matrix_mode); mat_apply(&mt); mat_store(trans_mats + matrix_mode); } static void normalize(vector_t * p) { float r; r = fsqrt( p->x*p->x + p->y*p->y + p->z*p->z ); if (r == 0.0) return; p->x /= r; p->y /= r; p->z /= r; } static void cross(const vector_t * v1, const vector_t * v2, vector_t * r) { r->x = v1->y*v2->z - v1->z*v2->y; r->y = v1->z*v2->x - v1->x*v2->z; r->z = v1->x*v2->y - v1->y*v2->x; } static matrix_t ml __attribute__((aligned(32))) = { { 1.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }; void plx_mat3d_lookat(const point_t * eye, const point_t * center, const vector_t * upi) { point_t forward, side, up; forward.x = center->x - eye->x; forward.y = center->y - eye->y; forward.z = center->z - eye->z; up.x = upi->x; up.y = upi->y; up.z = upi->z; normalize(&forward); /* Side = forward x up */ cross(&forward, &up, &side); normalize(&side); /* Recompute up as: up = side x forward */ cross(&side, &forward, &up); ml[0][0] = side.x; ml[1][0] = side.y; ml[2][0] = side.z; ml[0][1] = up.x; ml[1][1] = up.y; ml[2][1] = up.z; ml[0][2] = -forward.x; ml[1][2] = -forward.y; ml[2][2] = -forward.z; mat_load(trans_mats + matrix_mode); mat_apply(&ml); mat_translate(-eye->x, -eye->y, -eye->z); mat_store(trans_mats + matrix_mode); } static matrix_t msv __attribute__((aligned(32))) = { { 1.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }; /* Apply a matrix */ void plx_mat3d_apply(int mode) { if (mode != PLX_MAT_SCREENVIEW) { mat_apply(trans_mats + mode); } else { msv[0][0] = vp_scale.x; msv[1][1] = -vp_scale.y; msv[3][0] = vp_offset.x; msv[3][1] = vp_size.y - vp_offset.y; mat_apply(&msv); } } static matrix_t mam __attribute__((aligned(32))) = { { 1.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }; void plx_mat3d_apply_mat(matrix_t * mat) { memcpy_sh4(&mam, mat, sizeof(matrix_t)); mat_load(trans_mats + matrix_mode); mat_apply(&mam); mat_store(trans_mats + matrix_mode); } void plx_mat3d_apply_all() { mat_identity(); msv[0][0] = vp_scale.x; msv[1][1] = -vp_scale.y; msv[3][0] = vp_offset.x; msv[3][1] = vp_size.y - vp_offset.y; mat_apply(&msv); mat_apply(trans_mats + PLX_MAT_PROJECTION); mat_apply(trans_mats + PLX_MAT_WORLDVIEW); mat_apply(trans_mats + PLX_MAT_MODELVIEW); } /* Init */ void plx_mat3d_init() { int i; /* Setup all the matrices */ mat_identity(); for (i=0; i<PLX_MAT_COUNT; i++) mat_store(trans_mats + i); matrix_mode = PLX_MAT_PROJECTION; mat_mv_stack_top = 0; mat_p_stack_top = 0; /* Setup screen w&h */ plx_mat3d_depthrange(0.0f, 1.0f); plx_mat3d_viewport(0, 0, vid_mode->width, vid_mode->height); vp_z_fudge = 0.0f; } <file_sep>/modules/luaTask/src/ltask.c /* ** $Id: ltask.c 22 2007-11-24 17:29:24Z danielq $ ** "Multitasking" support ( see README ) ** SoongSoft, Argentina ** http://www.soongsoft.com mailto:<EMAIL> ** Copyright (C) 2003-2007 <NAME>. All rights reserved. */ #include <lauxlib.h> #include <lua.h> #include "lualib.h" #ifdef _WIN32 # include <windows.h> # include <process.h> # include <stddef.h> #ifndef NATV_WIN32 #include <pthread.h> #endif #else # define _strdup strdup # define _strnicmp strncasecmp # include <stdio.h> # include <stdlib.h> # include <string.h> //# include <poll.h> # include <sys/types.h> # include <string.h> # include <pthread.h> #endif #define LT_NAMESPACE "task" #include <time.h> #include <signal.h> #include <poll.h> #include "syncos.h" #include "queue.h" #ifdef _WIN32 static long ( __stdcall *LRT_LIB_OVERRIDE)( lua_State *L) = NULL; static long ( __stdcall *LRT_DOFILE_OVERRIDE)( lua_State *L, const char *filename) = NULL; #else long ( *LRT_LIB_OVERRIDE)( lua_State *L) = NULL; long ( *LRT_DOFILE_OVERRIDE)( lua_State *L, const char *filename) = NULL; #endif #define TASK_SLOTS_STEP 256 typedef struct S_TASK_ENTRY { QUEUE queue; char *fname; long flon; lua_State *L; OS_THREAD_T th; long running; char *id; long slot; } TASK_ENTRY; typedef struct S_MSG_ENTRY { long len; long flags; char data[1]; } MSG_ENTRY; typedef struct S_LOPN_LIB { char *name; unsigned long value; int (*fnc)(lua_State *); } LOPN_LIB; static void * tlMutex = NULL; static TASK_ENTRY * * volatile aTask; static long countTask = 0; static long threadDataKey; /* Internal functions */ static OS_THREAD_FUNC taskthread( void *vp); static int traceback (lua_State *L) { lua_getfield(L, LUA_GLOBALSINDEX, "debug"); if (!lua_istable(L, -1)) { lua_pop(L, 1); return 1; } lua_getfield(L, -1, "traceback"); if (!lua_isfunction(L, -1)) { lua_pop(L, 2); return 1; } lua_pushvalue(L, 1); /* pass error message */ lua_pushinteger(L, 2); /* skip this function and traceback */ lua_call(L, 2, 1); /* call debug.traceback */ return 1; } static int docall (lua_State *L, int narg, int clear) { int status; int base = lua_gettop(L) - narg; /* function index */ lua_pushcfunction(L, traceback); /* push traceback function */ lua_insert(L, base); /* put it under chunk and args */ status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base); lua_remove(L, base); /* remove traceback function */ /* force a complete garbage collection in case of errors */ if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0); return status; } static int dofile (lua_State *L, const char *name) { int status = luaL_loadfile(L, name) || docall(L, 0, 1); return status; } static int dostring (lua_State *L, const char *s, long l, const char *name) { int status = luaL_loadbuffer(L, s, l, name) || docall(L, 0, 1); return status; } static void taskCleanup( void *vp) { TASK_ENTRY *te = ( TASK_ENTRY *) vp; lua_close( te->L); te->L = NULL; free( te->fname); if( te->id != NULL) free( te->id); QueDestroy( &( te->queue)); te->running = 0; } static long int_taskcreate( const char *fname, long flon, lua_State *TL) { if( tlMutex != NULL) { long i; OsLockMutex( tlMutex, INFINITE); for( i = 0; i < countTask; i++) if( !( aTask[i]->running)) break; if( i == countTask) { TASK_ENTRY **te; long j; te = ( TASK_ENTRY * *) realloc( aTask, sizeof( TASK_ENTRY *) * ( countTask + TASK_SLOTS_STEP)); if( te == NULL) { OsUnlockMutex( tlMutex); return( -1); } aTask = te; aTask[i] = ( TASK_ENTRY *) malloc( sizeof( TASK_ENTRY) * ( TASK_SLOTS_STEP)); if( aTask[i] == NULL) { OsUnlockMutex( tlMutex); return( -1); } countTask += TASK_SLOTS_STEP; for( j = i; j < countTask; j++) { aTask[j] = ( TASK_ENTRY *) ( ( ( char * ) aTask[i] ) + ( sizeof( TASK_ENTRY) * ( j - i ) ) ); aTask[j]->running = 0; #ifdef NATV_WIN32 aTask[j]->th = 0; #endif aTask[j]->slot = j; } } #ifdef NATV_WIN32 if( aTask[i]->th) CloseHandle( ( HANDLE) aTask[i]->th); #endif if( ( aTask[i]->fname = calloc( flon + 1, 1 ) ) == NULL) { OsUnlockMutex( tlMutex); return( -2); } else { memcpy( aTask[i]->fname, fname, flon ); aTask[i]->flon = flon; if( QueCreate( &( aTask[i]->queue), QUE_NO_LIMIT)) { free( aTask[i]->fname); OsUnlockMutex( tlMutex); return( -3); } } aTask[i]->id = NULL; aTask[i]->L = TL; if( OsCreateThread( &( aTask[i]->th), taskthread, ( void *) ( aTask[i] ))) { free( aTask[i]->fname); QueDestroy( &( aTask[i]->queue)); OsUnlockMutex( tlMutex); return( -4); } aTask[i]->running = 1; OsUnlockMutex( tlMutex); return( i + 1); } return( -11); } static long int_taskregister( const char *id ) { long lrc = -1; TASK_ENTRY * te = ( TASK_ENTRY * ) OsGetThreadData( threadDataKey ); if( te != NULL ) { OsLockMutex( tlMutex, INFINITE); if( te->id != NULL ) free( te->id); te->id = _strdup( id ); lrc = 0; OsUnlockMutex( tlMutex ); } return( lrc); } static void int_tasklibinit(lua_State *L) { if( tlMutex == NULL) { threadDataKey = OsCreateThreadDataKey(); aTask = ( TASK_ENTRY * *) malloc( sizeof( TASK_ENTRY *) * TASK_SLOTS_STEP); if( aTask != NULL) { long i; aTask[0] = ( TASK_ENTRY *) malloc( sizeof( TASK_ENTRY) * TASK_SLOTS_STEP); if( aTask[0] != NULL) { countTask = TASK_SLOTS_STEP; for( i = 0; i < TASK_SLOTS_STEP; i++) { aTask[i] = ( TASK_ENTRY *) ( ( ( char * ) aTask[0] ) + ( sizeof( TASK_ENTRY) * i ) ); aTask[i]->running = 0; #ifdef NATV_WIN32 aTask[i]->th = 0; #endif aTask[i]->slot = i; } tlMutex = OsCreateMutex( NULL); QueCreate( &( aTask[0]->queue), QUE_NO_LIMIT); aTask[0]->L = L; aTask[0]->running = 1; aTask[0]->id = NULL; aTask[0]->fname = "_main_"; aTask[0]->flon = 7; aTask[0]->slot = 0; OsSetThreadData( threadDataKey, aTask[0] ); } } #ifdef _WIN32 LRT_LIB_OVERRIDE = ( long ( __stdcall *)( lua_State *L)) GetProcAddress( GetModuleHandle( NULL), "_LRT_LIB_OVERRIDE@4"); LRT_DOFILE_OVERRIDE = ( long ( __stdcall *)( lua_State *L, const char *filename)) GetProcAddress( GetModuleHandle( NULL), "_LRT_DOFILE_OVERRIDE@8"); #endif } } /* Registered functions */ static int reg_taskcreate(lua_State *L) { long lrc; long ti = 0; size_t flon; const char *fname = luaL_checklstring(L, 1, &flon); lua_State *TL = lua_open(); lua_newtable(TL); lua_pushnumber(TL, 0); lua_pushlstring(TL, fname, flon); lua_settable( TL, -3); if( lua_istable(L, 2)) { lua_pushnil(L); while( lua_next(L, 2) != 0) { if( lua_isnumber(L, -1)) { lua_pushnumber( TL, ++ti); lua_pushnumber( TL, lua_tonumber( L, -1)); lua_settable( TL, -3); } else if( lua_isstring(L, -1)) { lua_pushnumber( TL, ++ti); lua_pushstring( TL, lua_tostring( L, -1)); lua_settable( TL, -3); } else { lua_pop(L, 1); break; } lua_pop(L, 1); } } lua_setglobal(TL, "arg"); lrc = int_taskcreate( fname, flon, TL); if( lrc < 0) lua_close( TL); lua_pushnumber( L, lrc); return 1; } static int reg_taskregister( lua_State *L) { long lrc; const char *id = luaL_checkstring(L, 1); lrc = int_taskregister( id); lua_pushnumber( L, lrc); return( 1); } static int reg_taskfind( lua_State *L) { long i; long lrc = -1; const char *id = luaL_checkstring(L, 1); OsLockMutex( tlMutex, INFINITE); for( i = 0; i < countTask; i++) if( aTask[i]->id != NULL) if( !strcmp( aTask[i]->id, id)) { lrc = i + 1; break; } OsUnlockMutex( tlMutex); lua_pushnumber( L, lrc); return( 1); } static int reg_taskunregister(lua_State *L) { long lrc; lrc = int_taskregister( ""); lua_pushnumber( L, lrc); return( 1); } static int reg_taskpost(lua_State *L) { const char *buffer; MSG_ENTRY *me; TASK_ENTRY * volatile te; size_t len; long idx = ( long) luaL_checknumber(L, 1); long flags = ( long) luaL_optinteger(L, 3, 0); long lrc = -1; buffer = luaL_checklstring(L, 2, &len); idx--; if( ( idx > -1) && ( idx < countTask)) { me = malloc( sizeof( MSG_ENTRY) + len - 1); if( me == NULL) { lrc = -2; } else { me->len = len; me->flags = flags; memcpy( me->data, buffer, len); OsLockMutex( tlMutex, INFINITE); te = aTask[idx]; OsUnlockMutex( tlMutex); QuePut( &( te->queue), me); lrc = 0; } } lua_pushnumber( L, lrc); return 1; } static int reg_tasklist(lua_State *L) { long i; lua_newtable( L); OsLockMutex( tlMutex, INFINITE); for( i = 0; i < countTask; i++) if( aTask[i]->running == 1 ) { lua_pushnumber( L, i + 1); lua_newtable( L); lua_pushstring( L, "script"); if( aTask[i]->fname[0] == '=' ) lua_pushstring( L, "STRING_TASK"); else lua_pushlstring( L, aTask[i]->fname, aTask[i]->flon); lua_settable( L, -3); lua_pushstring( L, "msgcount"); lua_pushnumber( L, aTask[i]->queue.msgcount); lua_settable( L, -3); if( aTask[i]->id != NULL) { lua_pushstring( L, "id"); lua_pushstring( L, aTask[i]->id); lua_settable( L, -3); } lua_settable( L, -3); } OsUnlockMutex( tlMutex); return 1; } static int reg_taskreceive(lua_State *L) { MSG_ENTRY *me; TASK_ENTRY *te = ( TASK_ENTRY * ) OsGetThreadData( threadDataKey ); long lrc = -1; long tout = ( long) luaL_optinteger(L, 1, INFINITE); if( te != NULL ) { #ifdef _WIN32 HANDLE qwh = ( HANDLE) GetQueNotEmptyHandle( &( te->queue)); DWORD dwWait = WaitForSingleObjectEx( qwh, tout, TRUE); if( ( te->running == 1) && ( dwWait == WAIT_OBJECT_0)) { #else int psw; struct pollfd pfd; pfd.fd = GetQueNotEmptyHandle( &( te->queue)); pfd.events = POLLIN; psw = poll( &pfd, 1, tout); if( ( te->running == 1) && ( psw == 1)) { #endif _QueGet( &( te->queue), ( void **) &me); lua_pushlstring( L, me->data, me->len); lua_pushnumber( L, me->flags); free( me); lrc = 0; } else { lua_pushnil( L); lua_pushnil( L); lrc = -2; } } else { lua_pushnil( L); lua_pushnil( L); } lua_pushnumber( L, lrc); return 3; } static int reg_taskid( lua_State *L) { TASK_ENTRY * te = ( TASK_ENTRY * ) OsGetThreadData( threadDataKey ); if(te != NULL ) lua_pushnumber( L, te->slot + 1); else lua_pushnumber( L, -1); return( 1); } static int reg_getqhandle( lua_State *L) { long qwh = 0; TASK_ENTRY * te = ( TASK_ENTRY * ) OsGetThreadData( threadDataKey); if(te != NULL ) { qwh = GetQueNotEmptyHandle( &( te->queue)); } lua_pushnumber( L, ( long) qwh); return( 1); } static int reg_cancel( lua_State *L) { long running; TASK_ENTRY * te = ( TASK_ENTRY * ) OsGetThreadData( threadDataKey); long lrc = -1; long i = ( long) luaL_checknumber(L, 1); OsLockMutex( tlMutex, INFINITE); if( ( i > 1) && ( i <= countTask)) if( --i != te->slot ) { lrc = 0; running = aTask[i]->running; if( running == 1) { aTask[i]->running = 2; lrc = OsCancelThread( aTask[i]->th); #ifdef NATV_WIN32 if( aTask[i]->running == 2) aTask[i]->running = 0; #endif } } OsUnlockMutex( tlMutex); lua_pushnumber( L, lrc); return( 1); } static int reg_isrunning( lua_State *L) { long running = 0; long i = ( long) luaL_checknumber(L, 1); OsLockMutex( tlMutex, INFINITE); if( ( i > 1) && ( i <= countTask)) running = aTask[--i]->running == 1 ? 1 : 0; OsUnlockMutex( tlMutex); lua_pushboolean( L, running); return( 1); } static int reg_sleep( lua_State *L) { long t = ( long) luaL_checknumber(L, 1); OsSleep( t); return( 0); } /* Module exported function */ static const struct luaL_reg lt_lib[] = { { "create", reg_taskcreate}, { "register", reg_taskregister}, { "find", reg_taskfind}, { "receive", reg_taskreceive}, { "post", reg_taskpost}, { "unregister", reg_taskunregister}, { "list", reg_tasklist}, { "id", reg_taskid}, { "getqhandle", reg_getqhandle}, { "cancel", reg_cancel}, { "isrunning", reg_isrunning}, { "sleep", reg_sleep}, { NULL, NULL} }; int luaopen_task(lua_State *L) { int_tasklibinit(L); luaL_openlib (L, LT_NAMESPACE, lt_lib, 0); lua_pop (L, 1); return 0; } static OS_THREAD_FUNC taskthread( void *vp) { TASK_ENTRY *te; int status = 0; #if (_MSC_VER >= 1400) size_t l_init; char *init; _dupenv_s(&init,&l_init,"LUA_INIT"); #else const char *init = getenv("LUA_INIT"); #endif OsLockMutex( tlMutex, INFINITE); OsSetThreadData( threadDataKey, vp ); te = ( TASK_ENTRY * ) vp; #ifndef NATV_WIN32 pthread_setcanceltype( PTHREAD_CANCEL_ASYNCHRONOUS, NULL); pthread_cleanup_push( taskCleanup, te); #endif lua_gc(te->L, LUA_GCSTOP, 0); /* stop collector during initialization */ luaL_openlibs(te->L); /* open libraries */ luaopen_task(te->L); lua_gc(te->L, LUA_GCRESTART, 0); if( LRT_LIB_OVERRIDE != NULL) LRT_LIB_OVERRIDE( te->L); OsUnlockMutex( tlMutex); if (init != NULL) { if (init[0] == '@') status = dofile( te->L, init+1); else status = dostring( te->L, init, strlen( init), "=LUA_INIT"); #if (_MSC_VER >= 1400) free(init); #endif } if (status == 0) { if( te->fname[0] == '=' ) dostring( te->L, te->fname + 1, te->flon - 1, "=STRING_TASK"); else { if( LRT_DOFILE_OVERRIDE != NULL) LRT_DOFILE_OVERRIDE( te->L, te->fname); else dofile( te->L, te->fname); } } OsLockMutex( tlMutex, INFINITE); #ifndef NATV_WIN32 pthread_cleanup_pop( 0); #endif taskCleanup( te); OsUnlockMutex( tlMutex); return( 0); } <file_sep>/applications/Makefile # # DreamShell applications Makefile # Copyright (C) 2009-2016 SWAT # http://www.dc-swat.ru # _SUBDIRS = main filemanager region_changer iso_loader \ bios_flasher gd_ripper speedtest vmu_manager \ settings gdplay all: $(patsubst %, _dir_%, $(_SUBDIRS)) $(patsubst %, _dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _dir_%, %, $@) clean: $(patsubst %, _clean_dir_%, $(_SUBDIRS)) $(patsubst %, _clean_dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _clean_dir_%, %, $@) clean install: $(patsubst %, _install_dir_%, $(_SUBDIRS)) $(patsubst %, _install_dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _install_dir_%, %, $@) install <file_sep>/lib/SDL_gui/VBoxLayout.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_VBoxLayout::GUI_VBoxLayout(const char *aname) : GUI_Layout(aname) { } GUI_VBoxLayout::~GUI_VBoxLayout(void) { } void GUI_VBoxLayout::Layout(GUI_Container *container) { SDL_Rect container_area = container->GetArea(); int n = container->GetWidgetCount(); int y, i; /* sum the heights of all children, and center it */ y = container_area.h; for (i=0; i<n; i++) { GUI_Widget *temp = container->GetWidget(i); y -= temp->GetArea().h; } y /= 2; /* position the children */ for (i=0; i<n; i++) { GUI_Widget *temp = container->GetWidget(i); SDL_Rect r = temp->GetArea(); int x = (container_area.w - r.w) / 2; temp->SetPosition(x, y); y = y + r.h; } } extern "C" GUI_Layout *GUI_VBoxLayoutCreate(void) { return new GUI_VBoxLayout("vbox"); } <file_sep>/src/gui/gui.c /**************************** * DreamShell ##version## * * gui.c * * DreamShell GUI * * (c)2006-2023 SWAT * ****************************/ #include "ds.h" #include "gui.h" #include "console.h" typedef struct TrashItem { /* Точка входа SLIST, только для внутреннего использования. */ SLIST_ENTRY(TrashItem) list; /* Ссылка на объект */ GUI_Object *object; } TrashItem_t; /* * Определение типа для списка, используется SLIST из библиотеки newlib */ typedef SLIST_HEAD(TrashItemList, TrashItem) TrashItem_list_t; static MouseCursor_t *cur_mouse = NULL; static mutex_t gui_mutex = MUTEX_INITIALIZER; static TrashItem_list_t *trash_list; static Event_t *gui_input_event; static Event_t *gui_video_event; static void GUI_DrawHandler(void *ds_event, void *param, int action) { switch(action) { case EVENT_ACTION_RENDER: DrawActiveMouseCursor(); break; case EVENT_ACTION_UPDATE: { App_t *app = GetCurApp(); // TODO optimize update area if(app != NULL && app->body != NULL) { //GUI_WidgetErase(app->body, (SDL_Rect *)param); GUI_WidgetMarkChanged(app->body); } else { //GUI_ScreenErase(GUI_GetScreen(), (SDL_Rect *)param); GUI_ScreenDoUpdate(GUI_GetScreen(), 1); } UpdateActiveMouseCursor(); break; } default: break; } } static uint64_t last_saved_time = 0; static uint8_t last_joy_state = 0; static void screenshot_callback(void) { char path[NAME_MAX]; char *home_dir = getenv("PATH"); int i; uint64 cur_time = timer_ms_gettime64(); if(!strncmp(home_dir, "/cd", 3) || ((cur_time - last_saved_time) < 5000)) { return; } last_saved_time = cur_time; for(i=0;;i++) { snprintf(path, NAME_MAX, "%s/screenshot/ds_scr_%03d.png", home_dir, i); if(!FileExists(path)) break; if(i == 999) return; } char *arg[3] = {"screenshot", path, "png"}; LockVideo(); CallCmd(3, arg); UnlockVideo(); } static void GUI_EventHandler(void *ds_event, void *param, int action) { SDL_Event *event = (SDL_Event *) param; GUI_ScreenEvent(GUI_GetScreen(), event, 0, 0); switch(event->type) { case SDL_JOYBUTTONDOWN: switch(event->jbutton.button) { case 6: // X button last_joy_state |= 1; break; } break; case SDL_JOYAXISMOTION: switch(event->jaxis.axis) { case 2: // rtrig if(event->jaxis.value) last_joy_state |= 2; break; case 3: // ltrig if(event->jaxis.value) last_joy_state |= 4; break; } break; default: last_joy_state = 0; break; } if(last_joy_state == 7) screenshot_callback(); /* switch(event->type) { case SDL_KEYDOWN: UpdateActiveMouseCursor(); break; case SDL_MOUSEMOTION: case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: UpdateActiveMouseCursor(); break; default: break; } */ } int InitGUI() { trash_list = (TrashItem_list_t *) calloc(1, sizeof(TrashItem_list_t)); if(trash_list == NULL) return 0; SLIST_INIT(trash_list); LockVideo(); GUI_Screen *gui = GUI_RealScreenCreate("screen", GetScreen()); if(gui == NULL) { ds_printf("DS_ERROR: GUI init RealScreen error\n"); UnlockVideo(); return 0; } else { GUI_SetScreen(gui); } UnlockVideo(); gui_input_event = AddEvent("GUI_Input", EVENT_TYPE_INPUT, GUI_EventHandler, NULL); gui_video_event = AddEvent("GUI_Video", EVENT_TYPE_VIDEO, GUI_DrawHandler, NULL); return 1; } void GUI_ClearTrash() { TrashItem_t *c, *n; c = SLIST_FIRST(trash_list); while(c) { n = SLIST_NEXT(c, list); EXPT_GUARD_BEGIN; GUI_ObjectDecRef(c->object); EXPT_GUARD_CATCH; ds_printf("DS_ERROR: Can't delete object %p from trash\n", c->object); EXPT_GUARD_END; free(c); c = n; } SLIST_INIT(trash_list); } void ShutdownGUI() { GUI_ClearTrash(); free(trash_list); RemoveEvent(gui_input_event); RemoveEvent(gui_video_event); LockVideo(); GUI_ObjectDecRef((GUI_Object *) GUI_GetScreen()); UnlockVideo(); mutex_destroy(&gui_mutex); return; } int GUI_Object2Trash(GUI_Object *object) { TrashItem_t *i = (TrashItem_t *) calloc(1, sizeof(TrashItem_t)); if(i == NULL) return 0; i->object = object; ds_printf("DS_WARNING: Added GUI object to trash: %s at %p\n", GUI_ObjectGetName(object), object); SLIST_INSERT_HEAD(trash_list, i, list); return 1; } MouseCursor_t *CreateMouseCursor(const char *fn, SDL_Surface *surface) { MouseCursor_t *c; c = (MouseCursor_t*) calloc(1, sizeof(MouseCursor_t)); if(c == NULL) { ds_printf("DS_ERROR: Malloc error\n"); return NULL; } c->cursor = surface ? surface : IMG_Load(fn); c->draw = 0; if(c->cursor == NULL) { free(c); ds_printf("DS_ERROR: Can't create surface\n"); return NULL; } c->bg = SDL_CreateRGBSurface(c->cursor->flags, c->cursor->w, c->cursor->h, c->cursor->format->BitsPerPixel, c->cursor->format->Rmask, c->cursor->format->Gmask, c->cursor->format->Bmask, c->cursor->format->Amask); if(c->bg == NULL) { SDL_FreeSurface(c->cursor); free(c); ds_printf("DS_ERROR: Can't create background for mouse cursor\n"); return NULL; } return c; } void DestroyMouseCursor(MouseCursor_t *c) { SDL_FreeSurface(c->bg); SDL_FreeSurface(c->cursor); free(c); } static int old_x = 0, old_y = 0; void DrawMouseCursor(MouseCursor_t *c/*, SDL_Event *event*/) { SDL_Rect src, dst; SDL_Surface *scr = NULL; int x = 0;//c->x;//event->motion.x; int y = 0;//c->y;//event->motion.y; SDL_GetMouseState(&x, &y); if(c->draw || (old_x != x || old_y != y)) { if(!c->draw) { c->draw++; } old_x = x; old_y = y; scr = GetScreen(); src.x = 0; src.y = 0; src.w = c->cursor->w; src.h = c->cursor->h; if (x + c->cursor->w <= scr->w) { src.w = c->cursor->w; } else { src.w = scr->w - x - 1; } if (y + c->cursor->h <= scr->h) { src.h = c->cursor->h; } else { src.h = scr->h - y - 1; } dst.x = x; dst.y = y; dst.w = src.w; dst.h = src.h; if(c->bg) { SDL_BlitSurface(c->bg, &c->src, scr, &c->dst); } } GUI_ScreenDoUpdate(GUI_GetScreen(), 0); if(c->draw) { SDL_BlitSurface(scr, &dst, c->bg, &src); SDL_BlitSurface(c->cursor, &src, scr, &dst); ScreenChanged(); c->src = src; c->dst = dst; if (c->draw > 15) { c->draw = 15; } c->draw--; } } void DrawActiveMouseCursor() { if (cur_mouse) { DrawMouseCursor(cur_mouse); } else { GUI_ScreenDoUpdate(GUI_GetScreen(), 0); } } void SetActiveMouseCursor(MouseCursor_t *c) { if(VideoMustLock()) LockVideo(); cur_mouse = c; if(VideoMustLock()) UnlockVideo(); } MouseCursor_t *GetActiveMouseCursor() { return cur_mouse; } void WaitDrawActiveMouseCursor() { while(cur_mouse->draw) thd_pass(); } void UpdateActiveMouseCursor() { cur_mouse->draw++; } Uint32 colorHexToRGB(char *color, SDL_Color *clr) { unsigned int r = 0, g = 0, b = 0; sscanf(color, "#%02x%02x%02x", &r, &g, &b); if(clr) { clr->r = r; clr->g = g; clr->b = b; } return (r << 16) | (g << 8) | b; } Uint32 MapHexColor(char *color, SDL_PixelFormat *format) { SDL_PixelFormat *f; unsigned int r = 0, g = 0, b = 0, a = 0; if(format == NULL) f = GetScreen()->format; else f = format; if(strlen(color) >= 8) { sscanf(color, "#%02x%02x%02x%02x", &a, &r, &g, &b); return SDL_MapRGBA(f, r, g, b, a); } else { sscanf(color, "#%02x%02x%02x", &r, &g, &b); return SDL_MapRGB(f, r, g, b); } } SDL_Color Uint32ToColor(Uint32 c) { SDL_Color clr; clr.r = c >> 16; clr.g = c >> 8; clr.b = c; return clr; } Uint32 ColorToUint32(SDL_Color c) { return (c.r << 16) | (c.g << 8) | c.b; } SDL_Surface *SDL_ImageLoad(const char *filename, SDL_Rect *selection) { SDL_Surface *surface = NULL, *img = NULL; SDL_Surface *screen = GetScreen(); img = IMG_Load(filename); if(img != NULL) { if(selection && selection->w > 0 && selection->h > 0) { surface = SDL_CreateRGBSurface(screen->flags | SDL_SRCALPHA, selection->w, selection->h, screen->format->BitsPerPixel, screen->format->Rmask, screen->format->Gmask, screen->format->Bmask, screen->format->Amask); //SDL_SetAlpha(surface, SDL_SRCALPHA, 0); SDL_Surface *tmp = SDL_DisplayFormat(surface); SDL_FreeSurface(surface); surface = tmp; //SDL_FillRect(surface, NULL, SDL_MapRGBA(screen->format, 255, 255, 255, 255)); SDL_BlitSurface(img, selection, surface, NULL); SDL_FreeSurface(img); } else { surface = img; } } return surface; } <file_sep>/include/exports_fix.h /** * \file exports_fix.h * \brief DreamShell exports fix * \date 2023 * \author SWAT www.dc-swat.ru */ #include <stdio.h> #include <stdlib.h> #include <kos.h> #include <kos/net.h> extern uint32 _arch_old_sr, _arch_old_vbr, _arch_old_stack, _arch_old_fpscr, start; extern volatile uint32 jiffies; extern void _fini(void); int asprintf(char **restrict strp, const char *restrict fmt, ...); int vasprintf(char **restrict strp, const char *restrict fmt, va_list ap); char *index(const char *string, int c); char *rindex(const char *string, int c); void bcopy(const void *s1, void *s2, size_t n); void bzero(void *s, size_t n); int usleep(useconds_t usec); int putenv(char *string); char *mktemp(char *template); int getw(FILE *fp); int putw(int c, FILE *fp); /* Need for libppp */ #define packed __attribute__((packed)) typedef struct { uint8 dest[6]; uint8 src[6]; uint8 type[2]; } packed eth_hdr_t; int net_ipv4_input(netif_t *src, const uint8 *pkt, size_t pktsize, const eth_hdr_t *eth); /* GCC exports */ extern uint32 __floatdidf; extern uint32 __divdf3; extern uint32 __ledf2; extern uint32 __moddi3; extern uint32 __udivsi3_i4i; extern uint32 __sdivsi3_i4i; extern uint32 __udivdi3; extern uint32 __divdi3; extern uint32 __fixsfdi; extern uint32 __floatdisf; extern uint32 __fixunssfdi; extern uint32 __floatundisf; extern uint32 __movmem_i4_even; extern uint32 __movmem_i4_odd; extern uint32 __movmemSI12_i4; extern uint32 __ctzsi2; extern uint32 __clzsi2; extern uint32 __umoddi3; extern uint32 __extendsfdf2; extern uint32 __muldf3; extern uint32 __floatunsidf; extern uint32 __truncdfsf2; extern uint32 __gtdf2; extern uint32 __fixdfsi; extern uint32 __floatsidf; extern uint32 __subdf3; extern uint32 __ltdf2; extern uint32 __adddf3; extern uint32 __gedf2; extern uint32 __eqdf2; extern uint32 __ashldi3; extern uint32 __unordsf2; extern uint32 __lshrdi3; extern uint32 _Unwind_Resume; extern uint32 _Unwind_DeleteException; extern uint32 _Unwind_GetRegionStart; extern uint32 _Unwind_GetLanguageSpecificData; extern uint32 _Unwind_GetIPInfo; extern uint32 _Unwind_SetGR; extern uint32 _Unwind_SetIP; extern uint32 _Unwind_RaiseException; extern uint32 _Unwind_GetTextRelBase; extern uint32 _Unwind_Resume_or_Rethrow; <file_sep>/modules/isofs/module.c /* DreamShell ##version## module.c - isofs module Copyright (C)2009-2016 SWAT */ #include "ds.h" #include "isofs/isofs.h" #include "isofs/ciso.h" DEFAULT_MODULE_HEADER(isofs); int builtin_isofs_cmd(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s options args\n" "Options: \n" " -m, --mount -Mounting CD image as filesystem\n" " -u, --unmount -Unmounting CD image\n\n" "Arguments: \n" " -f, --file -CD image file\n" " -d, --dir -VFS Directory for access to files of CD image\n\n" "Example: %s -m -f /sd/image.iso -d /iso\n\n", argv[0], argv[0]); return CMD_NO_ARG; } int mount = 0, unmount = 0; char *file, *dir; struct cfg_option options[] = { {"mount", 'm', NULL, CFG_BOOL, (void *) &mount, 0}, {"unmount", 'u', NULL, CFG_BOOL, (void *) &unmount, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, {"dir", 'd', NULL, CFG_STR, (void *) &dir, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(dir == NULL) { ds_printf("DS_ERROR: Too few arguments (fs directory) \n"); return CMD_ERROR; } if(mount) { if(file == NULL || dir == NULL) { ds_printf("DS_ERROR: Too few arguments (file and VFS path)\n"); return CMD_NO_ARG; } if(fs_iso_mount(dir, file) < 0) { ds_printf("DS_ERROR: Can't mount %s\n", file); return CMD_ERROR; } ds_printf("DS_OK: Mounted %s to %s\n", file, dir); } else if(unmount) { if(dir == NULL) { ds_printf("DS_ERROR: Too few arguments (VFS path)\n"); return CMD_NO_ARG; } if(fs_iso_unmount(dir) < 0) { ds_printf("DS_ERROR: Can't unmount %s\n", dir); return CMD_ERROR; } ds_printf("DS_OK: Unmounted %s\n", dir); } else { ds_printf("DS_ERROR: Too few arguments (mount or unmount)\n"); return CMD_NO_ARG; } return CMD_OK; } int lib_open(klibrary_t *lib) { fs_iso_init(); AddCmd(lib_get_name(), "Mount/unmount CD image file as filesystem", (CmdHandler *) builtin_isofs_cmd); return nmmgr_handler_add(&ds_isofs_hnd.nmmgr); } int lib_close(klibrary_t *lib) { RemoveCmd( GetCmdByName( lib_get_name() ) ); fs_iso_shutdown(); return nmmgr_handler_remove(&ds_isofs_hnd.nmmgr); } int read_sectors_data(file_t fd, uint32 sector_count, uint16 sector_size, uint8 *buff) { #ifdef DEBUG dbglog(DBG_DEBUG, "%s: %ld at %ld mode %d\n", __func__, sector_count, fs_tell(fd), sector_size); #endif const uint16 sec_size = 2048; size_t tmps = sec_size * sector_count; /* Reading sectors bigger than 2048 */ if(sector_size > sec_size) { uint16 b_seek, a_seek; uint8 *tmpb; switch(sector_size) { case 2324: /* MODE2_FORM2 */ b_seek = 16; a_seek = 260; break; case 2336: /* SEMIRAW_MODE2 */ b_seek = 8; a_seek = 280; break; case 2352: /* RAW_XA */ b_seek = 16; a_seek = 288; break; default: return -1; } while(sector_count > 2) { tmpb = buff; tmps = (tmps / sector_size); if(fs_read(fd, tmpb, tmps * sector_size) != tmps * sector_size) { return -1; } #ifdef DEBUG dbglog(DBG_DEBUG, "%s: tmps=%d b_seek=%d a_seek=%d\n", __func__, tmps, b_seek, a_seek); #endif while(tmps--) { memmove_sh4(buff, tmpb + b_seek, sec_size); tmpb += sector_size; buff += sec_size; sector_count--; } tmps = sec_size * sector_count; } while(sector_count--) { fs_seek(fd, b_seek, SEEK_CUR); if(fs_read(fd, buff, sec_size) != sec_size) { return -1; } fs_seek(fd, a_seek, SEEK_CUR); buff += sec_size; } /* Reading normal data sectors (2048) */ } else { if(fs_read(fd, buff, tmps) != tmps) { return -1; } } return 0; } file_t fs_iso_first_file(const char *mountpoint) { file_t fd; dirent_t *ent; char fn[NAME_MAX]; fd = fs_open(mountpoint, O_DIR | O_RDONLY); if(fd == FILEHND_INVALID) { return fd; } do { ent = fs_readdir(fd); } while(ent && ent->attr != 0); if(ent != NULL) { snprintf(fn, NAME_MAX, "%s/%s", mountpoint, ent->name); fs_close(fd); fd = fs_open(fn, O_RDONLY); } else { fs_close(fd); fd = FILEHND_INVALID; } return fd; } /** * Spoof TOC for GD session 1 */ void spoof_toc_3track_gd_session_1(CDROM_TOC *toc) { /** * Track 1 * CTRL = 4, ADR = 1, FAD = 0x0096 (FAD 150, so LBA 0) * MSF = 00:02:00 */ toc->entry[0] = 0x41000096; /** * Track 2 * CTRL = 0, ADR = 1, FAD = 0x02EE (FAD 750, so LBA 600) * MSF = 00:10:00 */ toc->entry[1] = 0x010002EE; /** * Ununsed / empty entries */ for(int i = 2; i < 99; i++) toc->entry[i] = (uint32)-1; /** * First track 1 Data */ toc->first = 0x41010000; /** * Last track 2 Audio */ toc->last = 0x01020000; /** * Leadout Audio * FAD = 0x1A2C (FAD 6700, so LBA 6850 decimal) * MSF = 01:29:00, 25 frames per second */ toc->leadout_sector = 0x01001A2C; } /** * Spoof TOC for GD session 2 */ void spoof_toc_3track_gd_session_2(CDROM_TOC *toc) { /** * Track 1 and 2 is empty. * This is a low-density track, unused in GD session. */ toc->entry[0] = -1; toc->entry[1] = -1; /** * Track 3 Data * CTRL = 4, ADR = 1, FAD = 0xB05E (FAD 45150, so LBA 45000) * MSF = 10:02:00 */ toc->entry[2] = 0x4100B05E; /** * Ununsed / empty entries */ for(int i = 3; i < 99; i++) { toc->entry[i] = (uint32)-1; } /** * Track 3 Data */ toc->first = 0x41030000; toc->last = 0x41030000; /** * Data * FAD = 0x0861B4 (FAD 549300, so LBA 549150 decimal) * MSF = 122:04:00 */ toc->leadout_sector = 0x410861B4; } void spoof_multi_toc_3track_gd(CDROM_TOC *toc) { spoof_toc_3track_gd_session_2(toc); toc->entry[0] = 0x41000096; toc->entry[1] = 0x010002EE; /* Need change before use */ // toc->first = 0x41010000; // toc->last = 0x01020000; // toc->leadout_sector = 0x01001A2C; } void spoof_multi_toc_iso(CDROM_TOC *toc, file_t fd, uint32 lba) { /** * Track 1 Data * CTRL = 4, ADR = 1, LBA = ??? */ toc->entry[0] = 0x41000000 | lba; /** * Ununsed / empty entries */ for(int i = 1; i < 99; i++) toc->entry[i] = (uint32)-1; /** * First and last is track 1 */ toc->first = 0x41010000; toc->last = 0x01010000; /** * Leadout sector */ toc->leadout_sector = (fs_total(fd) / 2048) + lba; } void spoof_multi_toc_cso(CDROM_TOC *toc, CISO_header_t *hdr, uint32 lba) { /** * Track 1 Data * CTRL = 4, ADR = 1, LBA = ??? */ toc->entry[0] = 0x41000000 | lba; /** * Ununsed / empty entries */ for(int i = 1; i < 99; i++) toc->entry[i] = (uint32)-1; /** * First and last is track 1 */ toc->first = 0x41010000; toc->last = 0x01010000; /** * Leadout sector */ toc->leadout_sector = (hdr->total_bytes / hdr->block_size) + lba; } <file_sep>/modules/ftpd/lftpd/private/lftpd_status.h #pragma once #define STATUS_110 "Restart marker reply." #define STATUS_120 "Service ready in %d minutes." #define STATUS_125 "Data connection already open; transfer starting." #define STATUS_150 "File status okay; about to open data connection." #define STATUS_200 "Command okay." #define STATUS_202 "Command not implemented, superfluous at this site." #define STATUS_211 "System status, or system help reply." #define STATUS_212 "Directory status." #define STATUS_213 "File status." #define STATUS_214 "Help message." #define STATUS_215 "%s system type." #define STATUS_220 "Service ready for new user." #define STATUS_221 "Service closing control connection." #define STATUS_225 "Data connection open; no transfer in progress." #define STATUS_226 "Closing data connection." #define STATUS_227 "Entering Passive Mode (%d,%d,%d,%d,%d,%d)." #define STATUS_229 "Entering Extended Passive Mode (|||%d|)." #define STATUS_230 "User logged in, proceed." #define STATUS_250 "Requested file action okay, completed." #define STATUS_257 "\"%s\" created." #define STATUS_331 "User name okay, need password." #define STATUS_332 "Need account for login." #define STATUS_350 "Requested file action pending further information." #define STATUS_421 "Service not available, closing control connection." #define STATUS_425 "Can't open data connection." #define STATUS_426 "Connection closed; transfer aborted." #define STATUS_450 "Requested file action not taken. File unavailable (e.g., file busy)." #define STATUS_451 "Requested action aborted: local error in processing." #define STATUS_452 "Requested action not taken. Insufficient storage space in system." #define STATUS_500 "Syntax error, command unrecognized. This may include errors such as command line too long." #define STATUS_501 "Syntax error in parameters or arguments." #define STATUS_502 "Command not implemented." #define STATUS_503 "Bad sequence of commands." #define STATUS_504 "Command not implemented for that parameter." #define STATUS_530 "Not logged in." #define STATUS_532 "Need account for storing files." #define STATUS_550 "Requested action not taken. File unavailable (e.g., file not found, no access)." #define STATUS_551 "Requested action aborted: page type unknown." #define STATUS_552 "Requested file action aborted. Exceeded storage allocation (for current directory or dataset)." #define STATUS_553 "Requested action not taken. File name not allowed." <file_sep>/modules/mp3/libmp3/xingmp3/mdct.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** mdct.c *************************************************** Layer III cos transform for n=18, n=6 computes c[k] = Sum( cos((pi/4*n)*(2*k+1)*(2*p+1))*f[p] ) k = 0, ...n-1, p = 0...n-1 inplace ok. ******************************************************************/ #include <float.h> #include <math.h> #ifdef ASM_X86 extern void imdct18_asm(float f[18]); extern void imdct6_3_asm(float f[]); #endif /* ASM_X86 */ /*------ 18 point xform -------*/ float mdct18w[18]; float mdct18w2[9]; float coef[9][4]; float mdct6_3v[6]; float mdct6_3v2[3]; float coef87; typedef struct { float *w; float *w2; void *coef; } IMDCT_INIT_BLOCK; static IMDCT_INIT_BLOCK imdct_info_18 = {mdct18w, mdct18w2, coef}; static IMDCT_INIT_BLOCK imdct_info_6 = {mdct6_3v, mdct6_3v2, &coef87}; /*====================================================================*/ IMDCT_INIT_BLOCK *imdct_init_addr_18() { return &imdct_info_18; } IMDCT_INIT_BLOCK *imdct_init_addr_6() { return &imdct_info_6; } /*--------------------------------------------------------------------*/ void imdct18(float f[18]) /* 18 point */ { #ifdef ASM_X86 imdct18_asm(f); #else int p; float a[9], b[9]; float ap, bp, a8p, b8p; float g1, g2; for (p = 0; p < 4; p++) { g1 = mdct18w[p] * f[p]; g2 = mdct18w[17 - p] * f[17 - p]; ap = g1 + g2; // a[p] bp = mdct18w2[p] * (g1 - g2); // b[p] g1 = mdct18w[8 - p] * f[8 - p]; g2 = mdct18w[9 + p] * f[9 + p]; a8p = g1 + g2; // a[8-p] b8p = mdct18w2[8 - p] * (g1 - g2); // b[8-p] a[p] = ap + a8p; a[5 + p] = ap - a8p; b[p] = bp + b8p; b[5 + p] = bp - b8p; } g1 = mdct18w[p] * f[p]; g2 = mdct18w[17 - p] * f[17 - p]; a[p] = g1 + g2; b[p] = mdct18w2[p] * (g1 - g2); f[0] = 0.5f * (a[0] + a[1] + a[2] + a[3] + a[4]); f[1] = 0.5f * (b[0] + b[1] + b[2] + b[3] + b[4]); f[2] = coef[1][0] * a[5] + coef[1][1] * a[6] + coef[1][2] * a[7] + coef[1][3] * a[8]; f[3] = coef[1][0] * b[5] + coef[1][1] * b[6] + coef[1][2] * b[7] + coef[1][3] * b[8] - f[1]; f[1] = f[1] - f[0]; f[2] = f[2] - f[1]; f[4] = coef[2][0] * a[0] + coef[2][1] * a[1] + coef[2][2] * a[2] + coef[2][3] * a[3] - a[4]; f[5] = coef[2][0] * b[0] + coef[2][1] * b[1] + coef[2][2] * b[2] + coef[2][3] * b[3] - b[4] - f[3]; f[3] = f[3] - f[2]; f[4] = f[4] - f[3]; f[6] = coef[3][0] * (a[5] - a[7] - a[8]); f[7] = coef[3][0] * (b[5] - b[7] - b[8]) - f[5]; f[5] = f[5] - f[4]; f[6] = f[6] - f[5]; f[8] = coef[4][0] * a[0] + coef[4][1] * a[1] + coef[4][2] * a[2] + coef[4][3] * a[3] + a[4]; f[9] = coef[4][0] * b[0] + coef[4][1] * b[1] + coef[4][2] * b[2] + coef[4][3] * b[3] + b[4] - f[7]; f[7] = f[7] - f[6]; f[8] = f[8] - f[7]; f[10] = coef[5][0] * a[5] + coef[5][1] * a[6] + coef[5][2] * a[7] + coef[5][3] * a[8]; f[11] = coef[5][0] * b[5] + coef[5][1] * b[6] + coef[5][2] * b[7] + coef[5][3] * b[8] - f[9]; f[9] = f[9] - f[8]; f[10] = f[10] - f[9]; f[12] = 0.5f * (a[0] + a[2] + a[3]) - a[1] - a[4]; f[13] = 0.5f * (b[0] + b[2] + b[3]) - b[1] - b[4] - f[11]; f[11] = f[11] - f[10]; f[12] = f[12] - f[11]; f[14] = coef[7][0] * a[5] + coef[7][1] * a[6] + coef[7][2] * a[7] + coef[7][3] * a[8]; f[15] = coef[7][0] * b[5] + coef[7][1] * b[6] + coef[7][2] * b[7] + coef[7][3] * b[8] - f[13]; f[13] = f[13] - f[12]; f[14] = f[14] - f[13]; f[16] = coef[8][0] * a[0] + coef[8][1] * a[1] + coef[8][2] * a[2] + coef[8][3] * a[3] + a[4]; f[17] = coef[8][0] * b[0] + coef[8][1] * b[1] + coef[8][2] * b[2] + coef[8][3] * b[3] + b[4] - f[15]; f[15] = f[15] - f[14]; f[16] = f[16] - f[15]; f[17] = f[17] - f[16]; return; #endif } /*--------------------------------------------------------------------*/ /* does 3, 6 pt dct. changes order from f[i][window] c[window][i] */ void imdct6_3(float f[]) /* 6 point */ { #ifdef ASM_X86 imdct6_3_asm(f); #else int w; float buf[18]; float *a, *c; // b[i] = a[3+i] float g1, g2; float a02, b02; c = f; a = buf; for (w = 0; w < 3; w++) { g1 = mdct6_3v[0] * f[3 * 0]; g2 = mdct6_3v[5] * f[3 * 5]; a[0] = g1 + g2; a[3 + 0] = mdct6_3v2[0] * (g1 - g2); g1 = mdct6_3v[1] * f[3 * 1]; g2 = mdct6_3v[4] * f[3 * 4]; a[1] = g1 + g2; a[3 + 1] = mdct6_3v2[1] * (g1 - g2); g1 = mdct6_3v[2] * f[3 * 2]; g2 = mdct6_3v[3] * f[3 * 3]; a[2] = g1 + g2; a[3 + 2] = mdct6_3v2[2] * (g1 - g2); a += 6; f++; } a = buf; for (w = 0; w < 3; w++) { a02 = (a[0] + a[2]); b02 = (a[3 + 0] + a[3 + 2]); c[0] = a02 + a[1]; c[1] = b02 + a[3 + 1]; c[2] = coef87 * (a[0] - a[2]); c[3] = coef87 * (a[3 + 0] - a[3 + 2]) - c[1]; c[1] = c[1] - c[0]; c[2] = c[2] - c[1]; c[4] = a02 - a[1] - a[1]; c[5] = b02 - a[3 + 1] - a[3 + 1] - c[3]; c[3] = c[3] - c[2]; c[4] = c[4] - c[3]; c[5] = c[5] - c[4]; a += 6; c += 6; } return; #endif } /*--------------------------------------------------------------------*/ <file_sep>/firmware/isoldr/loader/kos/src/broadband_adapter.c /* KallistiOS ##version## net/broadband_adapter.c Copyright (C)2001,2003 <NAME> */ #include <stdio.h> #include <string.h> #include <dc/net/broadband_adapter.h> //#include <dc/asic.h> #include <dc/g2bus.h> #include <arch/irq.h> #include <net/net.h> #include <arch/timer.h> #include "main.h" //CVSID("$Id: broadband_adapter.c,v 1.3 2003/07/22 03:31:58 bardtx Exp $"); /* Contains a low-level ethernet driver for the "Broadband Adapter", which is principally a RealTek 8193C chip attached to the G2 external bus using a PCI bridge chip called "GAPS PCI". GAPS PCI might ought to be in its own module, but AFAIK this is the only peripheral to use this chip, and quite possibly will be the only peripheral to ever use it. Thanks to <NAME> for finishing the driver info for the rtl8193c (mainly the transmit code, and lots of help with the error correction). Also thanks to the NetBSD sources for some info on register names. This driver has basically been rewritten since KOS 1.0.x. */ /****************************************************************************/ /* GAPS PCI stuff probably ought to be moved to another file... */ /* Detect a GAPS PCI bridge */ static int gaps_detect() { char str[16]; g2_read_block_8((uint8*)str, 0xa1001400, 16); if (!memcmp(str, "GAPSPCI_BRIDGE_2", 16)) return 0; else return -1; } /* Initialize GAPS PCI bridge */ #define GAPS_BASE 0xa1000000 static int gaps_init() { int i; /* Make sure we have one */ if (gaps_detect() < 0) { DBG("bba: no ethernet card found"); return -1; } /* Initialize the "GAPS" PCI glue controller. It ain't pretty but it works. */ g2_write_32(GAPS_BASE + 0x1418, 0x5a14a501); /* M */ i = 10000; while (!(g2_read_32(GAPS_BASE + 0x1418) & 1) && i > 0) i--; if (!(g2_read_32(GAPS_BASE + 0x1418) & 1)) { DBG("bba: GAPS PCI controller not responding; giving up!"); return -1; } g2_write_32(GAPS_BASE + 0x1420, 0x01000000); g2_write_32(GAPS_BASE + 0x1424, 0x01000000); g2_write_32(GAPS_BASE + 0x1428, 0x01840000); /* DMA Base */ g2_write_32(GAPS_BASE + 0x142c, 0x01840000 + 32*1024); /* DMA End */ g2_write_32(GAPS_BASE + 0x1414, 0x00000001); /* Interrupt enable */ g2_write_32(GAPS_BASE + 0x1434, 0x00000001); /* Configure PCI bridge (very very hacky). If we wanted to be proper, we ought to implement a full PCI subsystem. In this case that is ridiculous for accessing a single card that will probably never change. Considering that the DC is now out of production officially, there is a VERY good chance it will never change. */ g2_write_16(GAPS_BASE + 0x1606, 0xf900); g2_write_32(GAPS_BASE + 0x1630, 0x00000000); g2_write_8(GAPS_BASE + 0x163c, 0x00); g2_write_8(GAPS_BASE + 0x160d, 0xf0); g2_read_16(GAPS_BASE + 0x0004); g2_write_16(GAPS_BASE + 0x1604, 0x0006); g2_write_32(GAPS_BASE + 0x1614, 0x01000000); g2_read_8(GAPS_BASE + 0x1650); return 0; } /****************************************************************************/ /* RTL8193C stuff */ /* Configuration definitions */ #define RX_BUFFER_LEN 16384 /* RTL8139C Config/Status info */ struct { uint16 cur_rx; /* Current Rx read ptr */ uint16 cur_tx; /* Current available Tx slot */ uint8 mac[6]; /* Mac address */ } rtl; /* 8, 16, and 32 bit access to the PCI I/O space (configured by GAPS) */ #define NIC(ADDR) (0xa1001700 + (ADDR)) /* 8 and 32 bit access to the PCI MEMMAP space (configured by GAPS) */ static uint32 const rtl_mem = 0xa1840000; /* TX buffer pointers */ static uint32 const txdesc[4] = { 0xa1846000, 0xa1846800, 0xa1847000, 0xa1847800 }; /* Is the link stabilized? */ static volatile int link_stable, link_initial; /* Forward-declaration for IRQ handler */ static void bba_irq_hnd(uint32 code); /* Reads the MAC address of the BBA into the specified array */ void bba_get_mac(uint8 *arr) { memcpy(arr, rtl.mac, 6); } /* Initializes the BBA Returns 0 for success or -1 for failure. */ static int bba_hw_init() { int i; uint32 tmp; link_stable = 0; link_initial = 0; /* Initialize GAPS */ if (gaps_init() < 0) return -1; /* Soft-reset the chip */ g2_write_8(NIC(RT_CHIPCMD), RT_CMD_RESET); /* Wait for it to come back */ i = 100; while ((g2_read_8(NIC(RT_CHIPCMD)) & RT_CMD_RESET) && i > 0) { i--; timer_spin_sleep(10); } if (g2_read_8(NIC(RT_CHIPCMD)) & RT_CMD_RESET) { DBG("bba: timed out on reset #1"); return -1; } /* Reset CONFIG1 */ g2_write_8(NIC(RT_CONFIG1), 0); /* Enable auto-negotiation and restart that process */ /* NIC16(RT_MII_BMCR) = 0x1200; */ g2_write_16(NIC(RT_MII_BMCR), 0x9200); /* Do another reset */ g2_write_8(NIC(RT_CHIPCMD), RT_CMD_RESET); /* Wait for it to come back */ i = 100; while ((g2_read_8(NIC(RT_CHIPCMD)) & RT_CMD_RESET) && i > 0) { i--; timer_spin_sleep(10); } if (g2_read_8(NIC(RT_CHIPCMD)) & RT_CMD_RESET) { DBG("bba: timed out on reset #2"); return -1; } /* Enable writing to the config registers */ g2_write_8(NIC(RT_CFG9346), 0xc0); /* Read MAC address */ tmp = g2_read_32(NIC(RT_IDR0)); rtl.mac[0] = tmp & 0xff; rtl.mac[1] = (tmp >> 8) & 0xff; rtl.mac[2] = (tmp >> 16) & 0xff; rtl.mac[3] = (tmp >> 24) & 0xff; tmp = g2_read_32(NIC(RT_IDR0+4)); rtl.mac[4] = tmp & 0xff; rtl.mac[5] = (tmp >> 8) & 0xff; DBG("bba: MAC Address is %02x:%02x:%02x:%02x:%02x:%02x", rtl.mac[0], rtl.mac[1], rtl.mac[2], rtl.mac[3], rtl.mac[4], rtl.mac[5]); /* Enable receive and transmit functions */ g2_write_8(NIC(RT_CHIPCMD), RT_CMD_RX_ENABLE | RT_CMD_TX_ENABLE); /* Set Rx FIFO threashold to 1K, Rx size to 16k+16, 1024 byte DMA burst */ /* nic32[RT_RXCONFIG/4] = 0x0000c600; */ /* Set Rx FIFO threashold to 1K, Rx size to 8k, 1024 byte DMA burst */ g2_write_32(NIC(RT_RXCONFIG), 0x00000e00); /* Set Tx 1024 byte DMA burst */ g2_write_32(NIC(RT_TXCONFIG), 0x00000600); /* Turn off lan-wake and set the driver-loaded bit */ g2_write_8(NIC(RT_CONFIG1), (g2_read_8(NIC(RT_CONFIG1)) & ~0x30) | 0x20); /* Enable FIFO auto-clear */ g2_write_8(NIC(RT_CONFIG4), g2_read_8(NIC(RT_CONFIG4)) | 0x80); /* Switch back to normal operation mode */ g2_write_8(NIC(RT_CFG9346), 0); /* Setup RX/TX buffers */ g2_write_32(NIC(RT_RXBUF), 0x01840000); g2_write_32(NIC(RT_TXADDR0 + 0), 0x01846000); g2_write_32(NIC(RT_TXADDR0 + 4), 0x01846800); g2_write_32(NIC(RT_TXADDR0 + 8), 0x01847000); g2_write_32(NIC(RT_TXADDR0 + 12), 0x01847800); /* Reset RXMISSED counter */ g2_write_32(NIC(RT_RXMISSED), 0); /* Enable receiving broadcast and physical match packets */ g2_write_32(NIC(RT_RXCONFIG), g2_read_32(NIC(RT_RXCONFIG)) | 0x0000000a); /* Filter out all multicast packets */ g2_write_32(NIC(RT_MAR0 + 0), 0); g2_write_32(NIC(RT_MAR0 + 4), 0); /* Disable all multi-interrupts */ g2_write_16(NIC(RT_MULTIINTR), 0); /* Enable G2 interrupts */ // XXX /* asic_evt_set_handler(ASIC_EVT_EXP_PCI, bba_irq_hnd); asic_evt_enable(ASIC_EVT_EXP_PCI, ASIC_IRQB); */ /* Enable receive interrupts */ /* XXX need to handle more! */ g2_write_16(NIC(RT_INTRSTATUS), 0xffff); g2_write_16(NIC(RT_INTRMASK), RT_INT_PCIERR | RT_INT_TIMEOUT | RT_INT_RXFIFO_OVERFLOW | RT_INT_RXFIFO_UNDERRUN | // +link change RT_INT_RXBUF_OVERFLOW | RT_INT_TX_ERR | RT_INT_TX_OK | RT_INT_RX_ERR | RT_INT_RX_OK); /* Enable RX/TX once more */ g2_write_8(NIC(RT_CHIPCMD), RT_CMD_RX_ENABLE | RT_CMD_TX_ENABLE); /* Initialize status vars */ rtl.cur_tx = 0; rtl.cur_rx = 0; return 0; } static void rx_reset() { rtl.cur_rx = g2_read_16(NIC(RT_RXBUFHEAD)); g2_write_16(NIC(RT_RXBUFTAIL), rtl.cur_rx - 16); rtl.cur_rx = 0; g2_write_8(NIC(RT_CHIPCMD), RT_CMD_TX_ENABLE); g2_write_32(NIC(RT_RXCONFIG), 0x00000e0a); while (!(g2_read_8(NIC(RT_CHIPCMD)) & RT_CMD_RX_ENABLE)) g2_write_8(NIC(RT_CHIPCMD), RT_CMD_TX_ENABLE | RT_CMD_RX_ENABLE); g2_write_32(NIC(RT_RXCONFIG), 0x00000e0a); g2_write_16(NIC(RT_INTRSTATUS), 0xffff); } static void bba_hw_shutdown() { /* Disable receiver */ g2_write_32(NIC(RT_RXCONFIG), 0); /* Disable G2 interrupts */ // XXX /* asic_evt_disable(ASIC_EVT_EXP_PCI, ASIC_IRQB); asic_evt_set_handler(ASIC_EVT_EXP_PCI, NULL); */ } #if 0 /* Utility function to copy out a packet from the ring buffer into an SH-4 buffer. This is done to make sure the buffers don't overflow. */ /* XXX Could probably use a memcpy8 here, even */ static void bba_copy_packet(uint8 *dst, uint32 src, int len) { if ( (src+len) < RX_BUFFER_LEN ) { /* Straight copy is ok */ g2_read_block_8(dst, rtl_mem+src, len); } else { /* Have to copy around the ring end */ g2_read_block_8(dst, rtl_mem+src, RX_BUFFER_LEN - src); g2_read_block_8(dst+(RX_BUFFER_LEN - src), rtl_mem, len - (RX_BUFFER_LEN - src)); } } /* Copy one received packet out of the RX DMA space and into the RX buffer */ static void rx_enq(int ring_offset, int pkt_size) { // int i; /* Copy it out */ bba_copy_packet(net_rxbuf, ring_offset, pkt_size); /* //DBG("Received packet:\r\n"); for (i=0; i<pkt_size; i++) { //DBG("%02x ", net_rxbuf[i]); if (i && !(i % 16)) //DBG("\r\n"); } //DBG("\r\n"); */ /* Call the callback to process it */ net_input(&bba_if, pkt_size); } /* "Receive" any available packets and send them through the callback. */ static int bba_rx() { int processed; uint32 rx_status; int rx_size, pkt_size, ring_offset, intr; processed = 0; DBG("bba_rx"); /* While we have frames left to process... */ while (!(g2_read_8(NIC(RT_CHIPCMD)) & 1)) { /* Get frame size and status */ ring_offset = rtl.cur_rx % RX_BUFFER_LEN; rx_status = g2_read_32(rtl_mem + ring_offset); rx_size = (rx_status >> 16) & 0xffff; pkt_size = rx_size - 4; if (rx_size == 0xfff0) { DBG("bba: early receive triggered"); break; } if (!(rx_status & 1)) { DBG("bba: frame receive error, status is %08lx; skipping", rx_status); rx_reset(); break; } if ((rx_status & 1) && (pkt_size <= 1514)) { /* Add it to the rx queue */ rx_enq(ring_offset + 4, pkt_size); } else { DBG("bba: bogus packet receive detected; skipping packet"); rx_reset(); break; } /* Tell the chip where we are for overflow checking */ rtl.cur_rx = (rtl.cur_rx + rx_size + 4 + 3) & ~3; g2_write_16(NIC(RT_RXBUFTAIL), rtl.cur_rx - 16); /* If the chip is expecting an ACK, give it an ACK */ intr = g2_read_16(NIC(RT_INTRSTATUS)); if (intr & RT_INT_RX_ACK) g2_write_16(NIC(RT_INTRSTATUS), RT_INT_RX_ACK); /* Increase our "processed" count */ processed++; } return processed; } #endif /* Transmit a single packet */ int bba_tx(const uint8 *pkt, int len) { /* int i; //DBG("Transmitting packet:\r\n"); for (i=0; i<len; i++) { //DBG("%02x ", pkt[i]); if (i && !(i % 16)) //DBG("\r\n"); } //DBG("\r\n"); */ if (!link_stable) { while (!link_stable) { bba_irq_hnd(0); } } /* Wait till it's clear to transmit */ while ( !(g2_read_32(NIC(RT_TXSTATUS0 + 4*rtl.cur_tx)) & 0x2000) ) { if (g2_read_32(NIC(RT_TXSTATUS0 + 4*rtl.cur_tx)) & 0x40000000) g2_write_32(NIC(RT_TXSTATUS0 + 4*rtl.cur_tx), g2_read_32(NIC(RT_TXSTATUS0 + 4*rtl.cur_tx)) | 1); } /* Copy the packet out to RTL memory */ /* XXX could use store queues or memcpy8 here */ /*if (len & 3) len = (len + 3) & ~3; */ g2_write_block_8(pkt, txdesc[rtl.cur_tx], len); /* All packets must be at least 60 bytes */ if (len < 60) len = 60; /* Transmit from the current TX buffer */ g2_write_32(NIC(RT_TXSTATUS0 + 4*rtl.cur_tx), len); /* Go to the next TX buffer */ rtl.cur_tx = (rtl.cur_tx + 1) % 4; return 0; } /* Ethernet IRQ handler */ static void bba_irq_hnd(uint32 code) { int intr;//, hnd; (void)code; /* Acknowledge 8193 interrupt, except RX ACK bits. We'll handle those in the RX int handler. */ intr = g2_read_16(NIC(RT_INTRSTATUS)); g2_write_16(NIC(RT_INTRSTATUS), intr & ~RT_INT_RX_ACK); /* Do processing */ // hnd = 0; if (intr & RT_INT_RX_ACK) { // bba_rx(); hnd = 1; } // if (intr & RT_INT_TX_OK) { // hnd = 1; // } if (intr & RT_INT_LINK_CHANGE) { // Get the MII media status reg. uint32 bmsr = g2_read_16(NIC(RT_MII_BMSR)); // If this is the first time, force a renegotiation. if (!link_initial) { bmsr &= ~(RT_MII_LINK | RT_MII_AN_COMPLETE); DBG("bba: initial link change, redoing auto-neg"); } // This should really be a bit more complete, but this // should be sufficient. // Is our link there? if (bmsr & RT_MII_LINK) { // We must have just finished an auto-negotiation. DBG("bba: link stable"); // The link is back. link_stable = 1; } else { if (link_initial) DBG("bba: link lost"); // Do an auto-negotiation. g2_write_16(NIC(RT_MII_BMCR), RT_MII_RESET | RT_MII_AN_ENABLE | RT_MII_AN_START); // The link is gone. link_stable = 0; } // We've done our initial link interrupt now. link_initial = 1; // hnd = 1; } if (intr & RT_INT_RXBUF_OVERFLOW) { DBG("bba: RX overrun\n"); rx_reset(); // hnd = 1; } /* if (!hnd) { DBG("bba: spurious interrupt, status is %04x\n", intr); }*/ } /****************************************************************************/ /* Netcore interface */ netif_t bba_if; /* They only ever made one GAPS peripheral, so this should suffice */ static int bba_if_detect(netif_t *self) { (void)self; if (bba_if.flags & NETIF_DETECTED) return 0; if (gaps_detect() < 0) return -1; bba_if.flags |= NETIF_DETECTED; return 0; } static int bba_if_init(netif_t *self) { (void)self; if (bba_if.flags & NETIF_INITIALIZED) return 0; if (bba_hw_init() < 0) return -1; memcpy(bba_if.mac_addr, rtl.mac, 6); bba_if.flags |= NETIF_INITIALIZED; return 0; } static int bba_if_shutdown(netif_t *self) { (void)self; if (!(bba_if.flags & NETIF_INITIALIZED)) return 0; bba_hw_shutdown(); bba_if.flags &= ~(NETIF_INITIALIZED | NETIF_RUNNING); return 0; } static int bba_if_start(netif_t *self) { int i; (void)self; if (!(bba_if.flags & NETIF_INITIALIZED)) return -1; /* We need something like this to get DHCP to work (since it doesn't know anything about an activated and yet not-yet-receiving network adapter =) */ /* Spin until the link is stabilized */ i = 1000; while (!link_stable && i>0) { bba_irq_hnd(0); i--; timer_spin_sleep(10); } if (!link_stable) { DBG("bba: timed out waiting for link to stabilize"); return -1; } bba_if.flags |= NETIF_RUNNING; return 0; } static int bba_if_stop(netif_t *self) { (void)self; if (!(bba_if.flags & NETIF_RUNNING)) return -1; bba_if.flags &= ~NETIF_RUNNING; return 0; } static int bba_if_tx(netif_t *self, const uint8 *data, int len) { (void)self; if (!(bba_if.flags & NETIF_RUNNING)) return -1; //DBG("bba_if_tx"); if (bba_tx(data, len) != 0) return -1; return 0; } /* All RX is done via the interrupt */ static int bba_if_rx_poll(netif_t *self) { (void)self; bba_irq_hnd(0); //DBG("bba_if_rx_poll"); return 0; } /* Don't need to hook anything here yet */ static int bba_if_set_flags(netif_t *self, uint32 flags_and, uint32 flags_or) { (void)self; bba_if.flags = (bba_if.flags & flags_and) | flags_or; return 0; } /* Initialize */ int bba_init() { /* Setup the structure */ bba_if.descr = "Broadband Adapter (HIT-0400)"; bba_if.flags = NETIF_NO_FLAGS; bba_get_mac(bba_if.mac_addr); memset(bba_if.ip_addr, 0, sizeof(bba_if.ip_addr)); bba_if.if_detect = bba_if_detect; bba_if.if_init = bba_if_init; bba_if.if_shutdown = bba_if_shutdown; bba_if.if_start = bba_if_start; bba_if.if_stop = bba_if_stop; bba_if.if_tx = bba_if_tx; bba_if.if_rx_poll = bba_if_rx_poll; bba_if.if_set_flags = bba_if_set_flags; return 0; } /* Shutdown */ int bba_shutdown() { /* Shutdown hardware */ bba_if.if_stop(&bba_if); bba_if.if_shutdown(&bba_if); return 0; } <file_sep>/firmware/isoldr/syscalls/log.c /** * This file is part of DreamShell ISO Loader * Copyright (C)2011-2022 SWAT * Copyright (C)2019 megavolt85 * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifdef LOG #include "arch/types.h" #include "string.h" #include "stdio.h" #include "stdarg.h" /* SCIF registers */ #define SCIFREG08(x) *((volatile uint8 *)(x)) #define SCIFREG16(x) *((volatile uint16 *)(x)) #define SCSMR2 SCIFREG16(0xffeb0000) #define SCBRR2 SCIFREG08(0xffe80004) #define SCSCR2 SCIFREG16(0xffe80008) #define SCFTDR2 SCIFREG08(0xffe8000C) #define SCFSR2 SCIFREG16(0xffe80010) #define SCFRDR2 SCIFREG08(0xffe80014) #define SCFCR2 SCIFREG16(0xffe80018) #define SCFDR2 SCIFREG16(0xffe8001C) #define SCSPTR2 SCIFREG16(0xffe80020) #define SCLSR2 SCIFREG16(0xffe80024) /* Initialize the SCIF port; baud_rate must be at least 9600 and no more than 57600. 115200 does NOT work for most PCs. */ // recv trigger to 1 byte int scif_init() { int i; /* int fifo = 1; */ /* Disable interrupts, transmit/receive, and use internal clock */ SCSCR2 = 0; /* Enter reset mode */ SCFCR2 = 0x06; /* 8N1, use P0 clock */ SCSMR2 = 0; /* If baudrate unset, set baudrate, N = P0/(32*B)-1 */ // if (SCBRR2 == 0xff) SCBRR2 = (uint8)(50000000 / (32 * 115200)) - 1; /* Wait a bit for it to stabilize */ for (i=0; i<10000; i++) __asm__("nop"); /* Unreset, enable hardware flow control, triggers on 8 bytes */ SCFCR2 = 0x48; /* Disable manual pin control */ SCSPTR2 = 0; /* Disable SD */ // SCSPTR2 = PTR2_RTSIO | PTR2_RTSDT; /* Clear status */ (void)SCFSR2; SCFSR2 = 0x60; (void)SCLSR2; SCLSR2 = 0; /* Enable transmit/receive */ SCSCR2 = 0x30; /* Wait a bit for it to stabilize */ for (i=0; i<10000; i++) __asm__("nop"); return 0; } /* Read one char from the serial port (-1 if nothing to read) */ int scif_read() { int c; if (!(SCFDR2 & 0x1f)) return -1; // Get the input char c = SCFRDR2; // Ack SCFSR2 &= ~0x92; return c; } /* Write one char to the serial port (call serial_flush()!) */ int scif_write(int c) { int timeout = 100000; /* Wait until the transmit buffer has space. Too long of a failure is indicative of no serial cable. */ while (!(SCFSR2 & 0x20) && timeout > 0) timeout--; if (timeout <= 0) return -1; /* Send the char */ SCFTDR2 = c; /* Clear status */ SCFSR2 &= 0xff9f; return 1; } /* Flush all FIFO'd bytes out of the serial port buffer */ int scif_flush() { int timeout = 100000; SCFSR2 &= 0xbf; while (!(SCFSR2 & 0x40) && timeout > 0) timeout--; if (timeout <= 0) return -1; SCFSR2 &= 0xbf; return 0; } /* Send an entire buffer */ int scif_write_buffer(const uint8 *data, int len, int xlat) { int rv, i = 0, c; while (len-- > 0) { c = *data++; if (xlat) { if (c == '\n') { if (scif_write('\r') < 0) return -1; i++; } } rv = scif_write(c); if (rv < 0) return -1; i += rv; } if (scif_flush() < 0) return -1; return i; } #define do_div(n, base) ({ int32 __res; __res = ((unsigned long) n) % (unsigned) base; n = ((unsigned long) n) / (unsigned) base; __res; }) int check_digit (char c) { if((c>='0') && (c<='9')) { return 1; } return 0; } static int32 skip_atoi (const char **s) { int32 i; i = 0; while (check_digit (**s)) i = i*10 + *((*s)++) - '0'; return i; } char* printf_number (char *str, long num, int32 base, int32 size, int32 precision, int32 type) { int32 i; char c; char sign; char tmp[66]; const char *digits = "0123456789abcdefghijklmnopqrstuvwxyz"; if (type & N_LARGE) digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; if (type & N_LEFT) type &= ~N_ZEROPAD; if (base < 2 || base > 36) return 0; c = (type & N_ZEROPAD) ? '0' : ' '; sign = 0; if (type & N_SIGN) { if (num < 0) { sign = '-'; num = -num; size--; } else if (type & N_PLUS) { sign = '+'; size--; } else if (type & N_SPACE) { sign = ' '; size--; } } if (type & N_SPECIAL) { if (base == 16) size -= 2; else if (base == 8) size--; } i = 0; if (num == 0) tmp[i++] = '0'; else while (num != 0) tmp[i++] = digits[do_div (num,base)]; if (i > precision) precision = i; size -= precision; if (!(type & (N_ZEROPAD + N_LEFT))) { while (size-- > 0) *str++ = ' '; } if (sign) *str++ = sign; if (type & N_SPECIAL) { if (base == 8) { *str++ = '0'; } else if (base == 16) { *str++ = '0'; *str++ = digits[33]; } } if (!(type & N_LEFT)) { while (size-- > 0) *str++ = c; } while (i < precision--) *str++ = '0'; while (i-- > 0) *str++ = tmp[i]; while (size-- > 0) *str++ = ' '; return str; } int vsnprintf (char *buf, int size, const char *fmt, va_list args) { int len; unsigned long num; int i; int base; char *str; const char *s; int flags; /* NOTE: Flags to printf_number (). */ int field_width; /* NOTE: Width of output field. */ int precision; /* NOTE: min. # of digits for integers; max number of chars for from string. */ int qualifier; /* NOTE: 'h', 'l', or 'L' for integer fields. */ for (str = buf; *fmt && ((str - buf) < (size - 1)); ++fmt) { /* STAGE: If it's not specifying an option, just pass it on through. */ if (*fmt != '%') { *str++ = *fmt; continue; } /* STAGE: Process the flags. */ flags = 0; repeat: ++fmt; /* NOTE: This also skips first '%' */ switch (*fmt) { case '-' : flags |= N_LEFT; goto repeat; case '+' : flags |= N_PLUS; goto repeat; case ' ' : flags |= N_SPACE; goto repeat; case '#' : flags |= N_SPECIAL; goto repeat; case '0' : flags |= N_ZEROPAD; goto repeat; } /* STAGE: Get field width. */ field_width = -1; if (check_digit (*fmt)) { field_width = skip_atoi (&fmt); } else if (*fmt == '*') { ++fmt; /* STAGE: Specified on the next argument. */ field_width = va_arg (args, int); if (field_width < 0) { field_width = -field_width; flags |= N_LEFT; } } /* STAGE: Get the precision. */ precision = -1; if (*fmt == '.') { ++fmt; if (check_digit (*fmt)) { precision = skip_atoi (&fmt); } else if (*fmt == '*') { ++fmt; /* STAGE: Specified on the next argument */ precision = va_arg (args, int); } /* STAGE: Paranoia on the precision value. */ if (precision < 0) precision = 0; } /* STAGE: Get the conversion qualifier. */ qualifier = -1; if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L') { qualifier = *fmt; ++fmt; } /* NOTE: The default base. */ base = 10; /* STAGE: Handle all the other formatting types. */ switch (*fmt) { /* STAGE: Character type. */ case 'c' : { if (!(flags & N_LEFT)) { while (--field_width > 0) *str++ = ' '; } *str++ = (unsigned char) va_arg (args, int); while (--field_width > 0) *str++ = ' '; continue; } /* STAGE: String type. */ case 's' : { s = va_arg (args, char *); if (!s) s = "<NULL>"; len = strnlen (s, precision); if (!(flags & N_LEFT)) { while (len < field_width--) *str++ = ' '; } for (i = 0; i < len; ++i) *str++ = *s++; while (len < field_width--) *str++ = ' '; continue; } case 'p' : { if (field_width == -1) { field_width = 2 * sizeof (void *); flags |= N_ZEROPAD; } str = printf_number (str, (unsigned long) va_arg (args, void *), 16, field_width, precision, flags); continue; } case 'n' : { if (qualifier == 'l') { long *ip; ip = va_arg (args, long *); *ip = (str - buf); } else { int *ip; ip = va_arg (args, int *); *ip = (str - buf); } continue; } /* NOTE: Integer number formats - set up the flags and "break". */ /* STAGE: Octal. */ case 'o' : base = 8; break; /* STAGE: Uppercase hexidecimal. */ case 'X' : flags |= N_LARGE; base = 16; break; /* STAGE: Lowercase hexidecimal. */ case 'x' : base = 16; break; /* STAGE: Signed decimal/integer. */ case 'd' : case 'i' : flags |= N_SIGN; /* STAGE: Unsigned decimal/integer. */ case 'u' : break; default : { if (*fmt != '%') *str++ = '%'; if (*fmt) *str++ = *fmt; else --fmt; continue; } } /* STAGE: Handle number formats with the various modifying qualifiers. */ if (qualifier == 'l') { num = va_arg (args, unsigned long); } else if (qualifier == 'h') { /* NOTE: The int16 should work, but the compiler promotes the datatype and complains if I don't handle it directly. */ if (flags & N_SIGN) { // num = va_arg (args, int16); num = va_arg (args, int32); } else { // num = va_arg (args, uint16); num = va_arg (args, uint32); } } else if (flags & N_SIGN) { num = va_arg (args, int); } else { num = va_arg (args, unsigned int); } /* STAGE: And after all that work, actually convert the integer into text. */ str = printf_number (str, num, base, field_width, precision, flags); } *str = '\0'; return str - buf; } size_t strnlen(const char *s, size_t maxlen) { const char *e; size_t n; for (e = s, n = 0; *e && n < maxlen; e++, n++) ; return n; } static int PutLog(char *buff) { int len = strnlen(buff, 128); scif_write_buffer((uint8 *)buff, len, 1); return len; } int WriteLog(const char *fmt, ...) { char buff[128]; va_list args; int i; va_start(args, fmt); i = vsnprintf(buff, sizeof(buff), fmt, args); va_end(args); PutLog(buff); return i; } int WriteLogFunc(const char *func, const char *fmt, ...) { PutLog((char *)func); if(fmt == NULL) { PutLog("\n"); return 0; } PutLog(": "); char buff[128]; va_list args; int i; va_start(args, fmt); i = vsnprintf(buff, sizeof(buff), fmt, args); va_end(args); PutLog(buff); return i; } #endif /* LOG */ <file_sep>/firmware/isoldr/loader/kos/dc/biosfont.h /* KallistiOS ##version## dc/biosfont.h Copyright (C)2000-2001,2004 <NAME> $Id: biosfont.h,v 1.3 2002/06/27 23:24:43 bardtx Exp $ */ #ifndef __DC_BIOSFONT_H #define __DC_BIOSFONT_H #include <sys/cdefs.h> __BEGIN_DECLS #include <arch/types.h> uint8 *bfont_find_char(int ch); void bfont_draw(uint16 *buffer, uint16 fg, uint16 bg, int c); void bfont_draw_str(uint16 *buffer, uint16 fg, uint16 bg, const char *str); __END_DECLS #endif /* __DC_BIOSFONT_H */ <file_sep>/modules/gumbo/Makefile # # gumbo-parser module for DreamShell # Copyright (C) 2013 SWAT # TARGET_NAME = gumbo OBJS = ./$(TARGET_NAME)/src/tag.o ./$(TARGET_NAME)/src/utf8.o \ ./$(TARGET_NAME)/src/util.o ./$(TARGET_NAME)/src/error.o \ ./$(TARGET_NAME)/src/parser.o ./$(TARGET_NAME)/src/vector.o \ ./$(TARGET_NAME)/src/char_ref.o ./$(TARGET_NAME)/src/attribute.o \ ./$(TARGET_NAME)/src/tokenizer.o ./$(TARGET_NAME)/src/string_piece.o \ ./$(TARGET_NAME)/src/string_buffer.o module.o DBG_LIBS = -lds EXPORTS_FILE = exports.txt VER_MAJOR = 1 VER_MINOR = 0 VER_MICRO = 0 KOS_CFLAGS += $(KOS_CSTD) -L./$(TARGET_NAME)/include KOS_LIB_PATHS += -L./$(TARGET_NAME)/lib all: rm-elf include ../../sdk/Makefile.loadable library: ./$(TARGET_NAME)/Makefile cd ./$(TARGET_NAME) && make clean && make install ./$(TARGET_NAME)/Makefile: cd ./$(TARGET_NAME) && \ ./configure --prefix=`pwd` --build=sh-elf --host=sh4 --disable-shared \ CC=$(KOS_CC) CXX=$(KOS_CCPLUS) LD=$(KOS_LD) CCLD=$(KOS_LD) AR=$(KOS_AR) RUNLIB=$(KOS_RANLIB) \ CFLAGS="$(KOS_CFLAGS)" LDFLAGS="$(KOS_LDFLAGS)" LIBS="$(KOS_LIBS)" rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) opkg -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/sdk/toolchain/unpack.sh #!/bin/sh # These version numbers are all that should ever have to be changed. . $PWD/versions.sh while [ "$1" != "" ]; do PARAM=`echo $1 | awk -F= '{print $1}'` case $PARAM in --no-gmp) unset GMP_VER ;; --no-mpfr) unset MPFR_VER ;; --no-mpc) unset MPC_VER ;; --no-deps) unset GMP_VER unset MPFR_VER unset MPC_VER ;; *) echo "ERROR: unknown parameter \"$PARAM\"" exit 1 ;; esac shift done # Clean up from any old builds. rm -rf binutils-$BINUTILS_VER gcc-$GCC_VER newlib-$NEWLIB_VER rm -rf gmp-$GMP_VER mpfr-$MPFR_VER mpc-$MPC_VER # Unpack everything. tar jxf binutils-$BINUTILS_VER.tar.bz2 || exit 1 tar zxf gcc-$GCC_VER.tar.gz || exit 1 tar zxf newlib-$NEWLIB_VER.tar.gz || exit 1 # Unpack the GCC dependencies and move them into their required locations. if [ -n "$GMP_VER" ]; then tar jxf gmp-$GMP_VER.tar.bz2 || exit 1 mv gmp-$GMP_VER gcc-$GCC_VER/gmp fi if [ -n "$MPFR_VER" ]; then tar jxf mpfr-$MPFR_VER.tar.bz2 || exit 1 mv mpfr-$MPFR_VER gcc-$GCC_VER/mpfr fi if [ -n "$MPC_VER" ]; then tar zxf mpc-$MPC_VER.tar.gz || exit 1 mv mpc-$MPC_VER gcc-$GCC_VER/mpc fi <file_sep>/modules/bzip2/Makefile # # Bzip2 module for DreamShell # Copyright (C) 2009-2022 SWAT # http://www.dc-swat.ru # TARGET_NAME = bzip2 OBJS = module.o \ bzip2/blocksort.o \ bzip2/huffman.o \ bzip2/crctable.o \ bzip2/randtable.o \ bzip2/compress.o \ bzip2/decompress.o \ bzip2/bzlib.o DBG_LIBS = -lds EXPORTS_FILE = exports.txt VER_MAJOR = 1 VER_MINOR = 0 VER_MICRO = 6 VER_BUILD = 0 KOS_LIB_PATHS += -L./$(TARGET_NAME) all: rm-elf install include ../../sdk/Makefile.loadable rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) ln -nsf $(DS_SDK)/lib/$(TARGET_LIB) $(DS_SDK)/lib/libbz2.a <file_sep>/modules/aicaos/module.c /* DreamShell ##version## module.c - aicaos module Copyright (C)2013-2014 SWAT */ #include "ds.h" #include "aicaos.h" #include "drivers/aica.h" DEFAULT_MODULE_EXPORTS_CMD(aicaos, "AICAOS boot manager"); int builtin_aicaos_cmd(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s options args\n" "Options: \n" " -i, --init -Load and initialize AICAOS\n" " -s, --shutdown -Shutdown AICAOS and initialize KOS driver\n" " -v, --version -Display version\n\n" "Arguments: \n" " -f, --file -Firmware file\n\n" "Example: %s -i -f aicaos.drv\n", argv[0], argv[0]); return CMD_NO_ARG; } int a_init = 0, a_shut = 0, a_ver = 0; char *file = NULL; char fn[NAME_MAX]; struct cfg_option options[] = { {"init", 'i', NULL, CFG_BOOL, (void *) &a_init, 0}, {"shutdown", 's', NULL, CFG_BOOL, (void *) &a_shut, 0}, {"version", 'v', NULL, CFG_BOOL, (void *) &a_ver, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(a_ver) { ds_printf("%s module version: %d.%d.%d build %d\n", lib_get_name(), VER_MAJOR, VER_MINOR, VER_MICRO, VER_BUILD); return CMD_OK; } if(a_shut) { ds_printf("DS_PROCESS: Initializing default KOS driver...\n"); aica_exit(); snd_init(); return CMD_OK; } if(a_init) { if(file == NULL) { sprintf(fn, "%s/firmware/aica/aicaos.drv", getenv("PATH")); file = (char*)&fn; } ds_printf("DS_PROCESS: Loading '%s' in to AICA SPU...\n", file); snd_shutdown(); a_init = aica_init(file); if(a_init) { ds_printf("DS_ERROR: Failed %i.\n", a_init); return CMD_ERROR; } return CMD_OK; } return CMD_OK; } <file_sep>/modules/http/httpfs.c /* * HTTP protocol for file system * Copyright (c) 2000-2001 <NAME> * Copyright (c) 2011-2014 SWAT * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ds.h" #include <netdb.h> #include <sys/socket.h> /* XXX: POST protocol is not completly implemented because ffmpeg use only a subset of it */ //#define DEBUG 1 /* used for protocol handling */ #define URL_SIZE 256 typedef struct { file_t hd; int line_count; int len; int tread; int bpos, bsz; int http_code; char location[URL_SIZE]; char hoststr[256]; char path[256]; int flags; } HTTPContext; static int http_connect(HTTPContext * h, const char *path, const char *hoststr, int flags, int wait); static ssize_t http_write(void *h, const void *buffer, size_t size); /** * Copy the string str to buf. If str length is bigger than buf_size - * 1 then it is clamped to buf_size - 1. * NOTE: this function does what strncpy should have done to be * useful. NEVER use strncpy. * * @param buf destination buffer * @param buf_size size of destination buffer * @param str source string */ void pstrcpy(char *buf, int buf_size, const char *str) { int c; char *q = buf; if (buf_size <= 0) return; for(;;) { c = *str++; if (c == 0 || q >= buf + buf_size - 1) break; *q++ = c; } *q = '\0'; } void _url_split(char *proto, int proto_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url) { const char *p; char *q; int port; port = -1; p = url; if (*p == '\0') { if (proto_size > 0) proto[0] = '\0'; if (hostname_size > 0) hostname[0] = '\0'; p = url; } else { p++; if (*p == '/') p++; if (*p == '/') p++; q = hostname; while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') { if ((q - hostname) < hostname_size - 1) *q++ = *p; p++; } if (hostname_size > 0) *q = '\0'; if (*p == ':') { p++; port = (unsigned long) strtol(p, (char **)&p, 10); } } if (port_ptr) *port_ptr = port; pstrcpy(path, path_size, p); } /* return zero if error */ static void *http_open(vfs_handler_t * vfs, const char *fn, int flags) { const char *path, *proxy_path; char hostname[128]; char path1[256]; int port, use_proxy, err; HTTPContext *s; file_t hd = -1; int wait = 0; if (flags & O_DIR) return NULL; //h->is_streamed = 1; s = malloc(sizeof(HTTPContext)); if (!s) { return NULL; } use_proxy = 0; /* fill the dest addr */ redo: /* needed in any case to build the host string */ _url_split(NULL, 0, hostname, sizeof(hostname), &port, path1, sizeof(path1), fn); if (port > 0) { snprintf(s->hoststr, sizeof(s->hoststr), "%s:%d", hostname, port); } else { pstrcpy(s->hoststr, sizeof(s->hoststr), hostname); } if (use_proxy) { _url_split(NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, proxy_path); path = fn; } else { if (path1[0] == '\0') path = "/"; else path = path1; } if (port < 0) port = 80; snprintf(s->location, sizeof(s->location), "/tcp/%s:%d", hostname, port); #ifdef DEBUG dbglog(DBG_DEBUG, "HTTPFS : opening '%s' '%s'\n", s->location, path); #endif redo2: hd = fs_open(s->location, O_RDWR); err = hd >= 0 ? 0:-1; if (err < 0) goto fail; s->hd = hd; strcpy(s->path, path); s->flags = flags; if (http_connect(s, path, s->hoststr, flags, wait) < 0) { if (0 && wait <= 2000) { /* try again with a sleep */ wait += 1000; fs_close(hd); hd = -1; goto redo2; } goto fail; } if ((s->http_code == 303 || s->http_code == 302) && s->location[0] != '\0') { /* url moved, get next */ fn = s->location+6; #ifdef DEBUG dbglog(DBG_DEBUG, "URL moved get next '%s'\n", fn); #endif fs_close(hd); hd = -1; goto redo; } if (s->http_code != 200) goto fail; return (void*) s; fail: if (hd >= 0) fs_close(hd); free(s); return NULL; } static int http_getc(uint32 h) { char c; int res; HTTPContext *s = (HTTPContext *)h; res = fs_read(s->hd, &c, 1); if (res < 1) return -1; return c; } static int process_line(HTTPContext *s, char *line, int line_count) { char *tag, *p; /* end of header */ if (line[0] == '\0') return 0; p = line; if (line_count == 0) { while (!isspace(*p) && *p != '\0') p++; while (isspace(*p)) p++; s->http_code = strtol(p, NULL, 10); #ifdef DEBUG dbglog(DBG_DEBUG, "http_code=%d\n", s->http_code); #endif } else { while (*p != '\0' && *p != ':') p++; if (*p != ':') return 1; *p = '\0'; tag = line; p++; while (isspace(*p)) p++; if (!strcmp(tag, "Location")) { strcpy(s->location, p); } if (!strcmp(tag, "Content-Length")) { s->len = strtol(p, NULL, 10); #ifdef DEBUG dbglog(DBG_DEBUG, "len=%d\n", s->len); #endif } } return 1; } static int http_connect(HTTPContext *s, const char *path, const char *hoststr, int flags, int wait) { int post, err, ch; char line[512], *q; /* send http header */ post = flags & O_WRONLY; s->len = 0; s->tread = 0; s->bpos = 0; s->bsz = 0; snprintf(line, sizeof(line), "%s %s HTTP/1.0\r\n" "User-Agent: %s\r\n" "Host: %s\r\n" "Accept: */*\r\n" "Connection: keep-alive\r\n" "\r\n", post ? "POST" : "GET", path, "DreamShell", hoststr); if (http_write((void*) s, line, (ssize_t)strlen(line)) < 0) return -1; #ifdef DEBUG dbglog(DBG_DEBUG, "http : sent header -->\n%s", line); #endif /* init input buffer */ s->line_count = 0; //s->location[0] = '\0'; if (post) { return 0; } /* wait for header */ q = line; if (wait) thd_sleep(wait); for(;;) { ch = http_getc((uint32) s); #ifdef DEBUG dbglog(DBG_DEBUG, "%c", ch); #endif if (ch < 0) { #ifdef DEBUG dbglog(DBG_DEBUG, "http header truncated\n"); #endif return -1; } if (ch == '\n') { /* process line */ if (q > line && q[-1] == '\r') q--; *q = '\0'; #ifdef DEBUG dbglog(DBG_DEBUG, "header='%s'\n", line); #endif err = process_line(s, line, s->line_count); if (err < 0) return err; if (err == 0) return 0; s->line_count++; q = line; } else { if ((q - line) < sizeof(line) - 1) *q++ = ch; } } } static ssize_t http_read(void *h, void *buffer, size_t size) { HTTPContext *s = (HTTPContext *)h; uint8 *buf = (uint8*)buffer; int len; if (!s->hd) return -1; while (size > 0 && s->bpos < s->bsz) { *buf++ = s->path[s->bpos++]; size--; } if (s->len && size > s->len - s->tread) size = s->len - s->tread; if (size <= 0) { #ifdef DEBUG dbglog(DBG_DEBUG, "HTTPFS: reached end of file\n"); #endif return -1; } len = fs_read(s->hd, buf, size); if (len < 0) return -1; s->tread += len; return len; } /* used only when posting data */ static ssize_t http_write(void *h, const void *buffer, size_t size) { HTTPContext *s = (HTTPContext *)h; uint8 *buf = (uint8*)buffer; if (!s->hd) return -1; return fs_write(s->hd, buf, size); } static off_t http_seek(void *hnd, off_t offset, int whence) { HTTPContext *s = (HTTPContext *)hnd; file_t hd; #ifdef DEBUG dbglog(DBG_DEBUG, "HTTPFS: seek %d %d\n", offset, whence); #endif if (whence == SEEK_SET) { whence = SEEK_CUR; offset = offset - s->tread; } if (whence == SEEK_CUR) { int pos = fs_seek(s->hd, 0, SEEK_CUR); int res = fs_seek(s->hd, offset, SEEK_CUR) - pos; #ifdef DEBUG dbglog(DBG_DEBUG, "HTTPFS: seek res = %d\n", res); #endif s->tread += res; return s->tread; } if (whence != SEEK_SET) return -1; fs_close(s->hd); s->hd = -1; #ifdef DEBUG dbglog(DBG_DEBUG, "HTTPFS: location = '%s'\n", s->location); #endif hd = fs_open(s->location, O_RDWR); if (hd < 0) { #ifdef DEBUG dbglog(DBG_DEBUG, "HTTPFS: seek: could not reconnect to '%s'\n", s->location); #endif goto fail; } s->hd = hd; if (http_connect(s, s->path, s->hoststr, s->flags, 0) < 0) goto fail; if (offset) { int pos = fs_seek(s->hd, 0, SEEK_CUR); s->tread = fs_seek(s->hd, offset, SEEK_CUR) - pos; #ifdef DEBUG dbglog(DBG_DEBUG, "HTTPFS: seek res = %d\n", s->tread); #endif return s->tread; } s->tread = 0; return 0; fail: #ifdef DEBUG dbglog(DBG_DEBUG, "HTTPFS: seek: failed reopen\n"); #endif if (s->hd >= 0) fs_close(s->hd); s->hd = 0; return -1; } static int http_close(void *h) { HTTPContext *s = (HTTPContext *)h; if (s->hd >= 0) { fs_close(s->hd); } free(s); return 0; } /* Pull all that together */ static vfs_handler_t vh = { /* Name handler */ { "/http", /* name */ 0, /* tbfi */ 0x00010000, /* Version 1.0 */ 0, /* flags */ NMMGR_TYPE_VFS, /* VFS handler */ NMMGR_LIST_INIT }, 0, NULL, /* no cacheing, privdata */ http_open, http_close, http_read, http_write, http_seek, NULL, NULL, NULL, NULL, /* ioctl */ NULL, NULL, NULL, /* mmap */ NULL, /* complete */ NULL, /* stat XXX */ NULL, /* mkdir XXX */ NULL /* rmdir XXX */ }; static int inited = 0; int httpfs_init() { if (inited) return 0; inited = 1; /* Register with VFS */ return nmmgr_handler_add(&vh.nmmgr); } void httpfs_shutdown() { if (!inited) return; inited = 0; nmmgr_handler_remove(&vh.nmmgr); } <file_sep>/applications/gdplay/modules/app_module.h /* DreamShell ##version## app_module.h - GDPlay app module header Copyright (C)2014 megavolt85 */ #include "ds.h" void gdplay_play(GUI_Widget *widget); void gdplay_Init(App_t *app); void gdplay_Exit(); <file_sep>/modules/ftpd/lftpd/private/lftpd_inet.h #pragma once #include <stdlib.h> int lftpd_inet_listen(int port); int lftpd_inet_get_socket_port(int socket); /** * @brief Read a line from the client, terminating when CRLF is received * or the buffer length is reached. */ int lftpd_inet_read_line(int socket, char* buffer, size_t buffer_len); int lftpd_inet_write_string(int socket, const char* message); <file_sep>/include/isofs/isofs.h /** * \file isofs.h * \brief ISO9660 filesystem for optical drive images * \date 2011-2016 * \author SWAT www.dc-swat.ru */ #ifndef _ISOFS_H #define _ISOFS_H #include <kos.h> #include <kos/blockdev.h> /** * fs_ioctl commands */ typedef enum isofs_ioctl { ISOFS_IOCTL_RESET = 0, /* No data */ ISOFS_IOCTL_GET_FD_LBA, /* 4 byte unsigned */ ISOFS_IOCTL_GET_DATA_TRACK_FILENAME, /* 256 bytes */ ISOFS_IOCTL_GET_DATA_TRACK_FILENAME2, /* 12 bytes (second data track of GDI) */ ISOFS_IOCTL_GET_DATA_TRACK_LBA, /* 4 byte unsigned */ ISOFS_IOCTL_GET_DATA_TRACK_LBA2, /* 4 byte unsigned (second data track of GDI) */ ISOFS_IOCTL_GET_DATA_TRACK_OFFSET, /* 4 byte unsigned */ ISOFS_IOCTL_GET_DATA_TRACK_SECTOR_SIZE, /* 4 byte unsigned */ ISOFS_IOCTL_GET_IMAGE_TYPE, /* 4 byte unsigned */ ISOFS_IOCTL_GET_IMAGE_HEADER_PTR, /* 4 byte unsigned (pointer to memory) */ ISOFS_IOCTL_GET_TOC_DATA, /* CDROM_TOC */ ISOFS_IOCTL_GET_BOOT_SECTOR_DATA, /* 2048 bytes */ ISOFS_IOCTL_GET_CDDA_OFFSET, /* 97*4 byte unsigned (CDDA tracks offset of CDI) */ ISOFS_IOCTL_GET_TRACK_SECTOR_COUNT, /* 4 byte unsigned */ ISOFS_IOCTL_GET_IMAGE_FD /* 4 byte unsigned */ } isofs_ioctl_t; /** * ISO image type */ typedef enum isofs_image_type { ISOFS_IMAGE_TYPE_ISO = 0, ISOFS_IMAGE_TYPE_CSO, ISOFS_IMAGE_TYPE_ZSO, ISOFS_IMAGE_TYPE_CDI, ISOFS_IMAGE_TYPE_GDI } isofs_image_type_t; /** * IP.BIN (boot sector) meta info */ typedef struct ipbin_meta { char hardware_ID[16]; char maker_ID[16]; char device_info[16]; char country_codes[8]; char ctrl[4]; char dev[1]; char VGA[1]; char WinCE[1]; char unk[1]; char product_ID[10]; char product_version[6]; char release_date[16]; char boot_file[16]; char software_maker_info[16]; char title[32]; } ipbin_meta_t; int fs_iso_init(); int fs_iso_shutdown(); int fs_iso_mount(const char *mountpoint, const char *filename); int fs_iso_unmount(const char *mountpoint); file_t fs_iso_first_file(const char *mountpoint); int fs_iso_map2dev(const char *filename, kos_blockdev_t *dev); #endif /* _ISOFS_H */ <file_sep>/modules/mp3/libmp3/xingmp3/L3.h /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1996-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 Emusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ #ifndef _L3_H_ #define _L3_H_ #ifndef LITTLE_ENDIAN #define LITTLE_ENDIAN 1 #endif /**** L3.h *************************************************** Layer III structures *** Layer III is 32 bit only *** *** Layer III code assumes 32 bit int *** ******************************************************************/ #define GLOBAL_GAIN_SCALE (4*15) /* #define GLOBAL_GAIN_SCALE 0 */ #ifdef _M_IX86 #define LITTLE_ENDIAN 1 #endif #ifdef _M_ALPHA #define LITTLE_ENDIAN 1 #endif #ifdef sparc #define LITTLE_ENDIAN 0 #endif #ifndef LITTLE_ENDIAN #error Layer III LITTLE_ENDIAN must be defined 0 or 1 #endif /*-----------------------------------------------------------*/ /*---- huffman lookup tables ---*/ /* endian dependent !!! */ #if LITTLE_ENDIAN typedef union { int ptr; struct { unsigned char signbits; unsigned char x; unsigned char y; unsigned char purgebits; // 0 = esc } b; } HUFF_ELEMENT; #else /* big endian machines */ typedef union { int ptr; /* int must be 32 bits or more */ struct { unsigned char purgebits; // 0 = esc unsigned char y; unsigned char x; unsigned char signbits; } b; } HUFF_ELEMENT; #endif /*--------------------------------------------------------------*/ typedef struct { unsigned int bitbuf; int bits; unsigned char *bs_ptr; unsigned char *bs_ptr0; unsigned char *bs_ptr_end; // optional for overrun test } BITDAT; /*-- side info ---*/ typedef struct { int part2_3_length; int big_values; int global_gain; int scalefac_compress; int window_switching_flag; int block_type; int mixed_block_flag; int table_select[3]; int subblock_gain[3]; int region0_count; int region1_count; int preflag; int scalefac_scale; int count1table_select; } GR; typedef struct { int mode; int mode_ext; /*---------------*/ int main_data_begin; /* beginning, not end, my spec wrong */ int private_bits; /*---------------*/ int scfsi[2]; /* 4 bit flags [ch] */ GR gr[2][2]; /* [gran][ch] */ } SIDE_INFO; /*-----------------------------------------------------------*/ /*-- scale factors ---*/ // check dimensions - need 21 long, 3*12 short // plus extra for implicit sf=0 above highest cb typedef struct { int l[23]; /* [cb] */ int s[3][13]; /* [window][cb] */ } SCALEFACT; /*-----------------------------------------------------------*/ typedef struct { int cbtype; /* long=0 short=1 */ int cbmax; /* max crit band */ // int lb_type; /* long block type 0 1 3 */ int cbs0; /* short band start index 0 3 12 (12=no shorts */ int ncbl; /* number long cb's 0 8 21 */ int cbmax_s[3]; /* cbmax by individual short blocks */ } CB_INFO; /*-----------------------------------------------------------*/ /* scale factor infor for MPEG2 intensity stereo */ typedef struct { int nr[3]; int slen[3]; int intensity_scale; } IS_SF_INFO; /*-----------------------------------------------------------*/ typedef union { int s; float x; } SAMPLE; /*-----------------------------------------------------------*/ #endif <file_sep>/lib/libparallax/include/prim.h /* Parallax for KallistiOS ##version## prim.h (c)2002 <NAME> */ #ifndef __PARALLAX_PRIM #define __PARALLAX_PRIM #include <sys/cdefs.h> __BEGIN_DECLS /** \file This header defines the Parallax library "primitives". These are simply inlined wrapper functions which make it simpler and more compact to deal with the plx vertex structures. Each function has a suffix which determines what kind of color values are used, what kind of texture u/v values are used, and whether the vertex will be submitted automatically. For colors, "f" means float and "i" means a pre-packed 32-bit integer. For u/v, "n" means none, and "f" means float. And for submission, "n" means none, "d" means DR, and "p" means plx_prim. */ #include "color.h" #include "dr.h" #include "matrix.h" /********************************************************* RAW VERTEX ****/ /** This simple primitive function will fill a vertex structure for you from parameters. It uses floating point numbers for the color values and no u/v coordinates. The "vert" parameter may be a DR target. */ static inline void plx_vert_fnn(plx_vertex_t * vert, int flags, float x, float y, float z, float a, float r, float g, float b) { vert->flags = flags; vert->x = x; vert->y = y; vert->z = z; vert->u = vert->v = 0.0f; vert->argb = plx_pack_color(a, r, g, b); vert->oargb = 0; } /** Like plx_vert_fnn, but it takes a pre-packed integer color value. */ static inline void plx_vert_inn(plx_vertex_t * vert, int flags, float x, float y, float z, uint32 color) { vert->flags = flags; vert->x = x; vert->y = y; vert->z = z; vert->u = vert->v = 0.0f; vert->argb = color; vert->oargb = 0; } /** Like plx_vert_fnn, but it takes u/v texture coordinates as well. */ static inline void plx_vert_ffn(plx_vertex_t * vert, int flags, float x, float y, float z, float a, float r, float g, float b, float u, float v) { vert->flags = flags; vert->x = x; vert->y = y; vert->z = z; vert->u = u; vert->v = v; vert->argb = plx_pack_color(a, r, g, b); vert->oargb = 0; } /** Like plx_vert_fnn, but it takes u/v texture coordinates and a pre-packed integer color value. */ static inline void plx_vert_ifn(plx_vertex_t * vert, int flags, float x, float y, float z, uint32 color, float u, float v) { vert->flags = flags; vert->x = x; vert->y = y; vert->z = z; vert->u = u; vert->v = v; vert->argb = color; vert->oargb = 0; } /********************************************************* DR VERTEX ****/ /** Like plx_vert_fnn, but submits the point using DR. */ static inline void plx_vert_fnd(plx_dr_state_t * state, int flags, float x, float y, float z, float a, float r, float g, float b) { plx_vertex_t * vert = plx_dr_target(state); vert->flags = flags; vert->x = x; vert->y = y; vert->z = z; vert->u = vert->v = 0.0f; vert->argb = plx_pack_color(a, r, g, b); vert->oargb = 0; plx_dr_commit(vert); } /** Like plx_vert_inn, but submits the point using DR. */ static inline void plx_vert_ind(plx_dr_state_t * state, int flags, float x, float y, float z, uint32 color) { plx_vertex_t * vert = plx_dr_target(state); vert->flags = flags; vert->x = x; vert->y = y; vert->z = z; vert->u = vert->v = 0.0f; vert->argb = color; vert->oargb = 0; plx_dr_commit(vert); } /** Like plx_vert_ffn, but submits the point using DR. */ static inline void plx_vert_ffd(plx_dr_state_t * state, int flags, float x, float y, float z, float a, float r, float g, float b, float u, float v) { plx_vertex_t * vert = plx_dr_target(state); vert->flags = flags; vert->x = x; vert->y = y; vert->z = z; vert->u = u; vert->v = v; vert->argb = plx_pack_color(a, r, g, b); vert->oargb = 0; plx_dr_commit(vert); } /** Like plx_vert_ifn, but submits the point using DR. */ static inline void plx_vert_ifd(plx_dr_state_t * state, int flags, float x, float y, float z, uint32 color, float u, float v) { plx_vertex_t * vert = plx_dr_target(state); vert->flags = flags; vert->x = x; vert->y = y; vert->z = z; vert->u = u; vert->v = v; vert->argb = color; vert->oargb = 0; plx_dr_commit(vert); } /** Like plx_vert_ind, but also transforms via the active matrices for 3D */ static inline void plx_vert_indm3(plx_dr_state_t * state, int flags, float x, float y, float z, uint32 color) { plx_mat_tfip_3d(x, y, z); plx_vert_ind(state, flags, x, y, z, color); } /** Like plx_vert_ifd, but also transforms via the active matrices for 3D */ static inline void plx_vert_ifdm3(plx_dr_state_t * state, int flags, float x, float y, float z, uint32 color, float u, float v) { plx_mat_tfip_3d(x, y, z); if (z <= 0.0f) z = 0.001f; plx_vert_ifd(state, flags, x, y, z, color, u, v); } /****************************************************** PLX_PRIM VERTEX ****/ /** Like plx_vert_fnp, but submits the point using plx_prim. */ static inline void plx_vert_fnp(int flags, float x, float y, float z, float a, float r, float g, float b) { plx_vertex_t vert; vert.flags = flags; vert.x = x; vert.y = y; vert.z = z; vert.u = vert.v = 0.0f; vert.argb = plx_pack_color(a, r, g, b); vert.oargb = 0; plx_prim(&vert, sizeof(vert)); } /** Like plx_vert_inn, but submits the point using plx_prim. */ static inline void plx_vert_inp(int flags, float x, float y, float z, uint32 color) { plx_vertex_t vert; vert.flags = flags; vert.x = x; vert.y = y; vert.z = z; vert.u = vert.v = 0.0f; vert.argb = color; vert.oargb = 0; plx_prim(&vert, sizeof(vert)); } /** Like plx_vert_indm3, but uses plx_prim. */ static inline void plx_vert_inpm3(int flags, float x, float y, float z, uint32 color) { plx_mat_tfip_3d(x, y, z); plx_vert_inp(flags, x, y, z, color); } /** Like plx_vert_ffn, but submits the point using plx_prim. */ static inline void plx_vert_ffp(int flags, float x, float y, float z, float a, float r, float g, float b, float u, float v) { plx_vertex_t vert; vert.flags = flags; vert.x = x; vert.y = y; vert.z = z; vert.u = u; vert.v = v; vert.argb = plx_pack_color(a, r, g, b); vert.oargb = 0; plx_prim(&vert, sizeof(vert)); } /** Like plx_vert_ifn, but submits the point using plx_prim. */ static inline void plx_vert_ifp(int flags, float x, float y, float z, uint32 color, float u, float v) { plx_vertex_t vert; vert.flags = flags; vert.x = x; vert.y = y; vert.z = z; vert.u = u; vert.v = v; vert.argb = color; vert.oargb = 0; plx_prim(&vert, sizeof(vert)); } __END_DECLS #endif /* __PARALLAX_PRIM */ <file_sep>/applications/filemanager/Makefile # # File manager App for DreamShell # Copyright (C) 2009-2016 SWAT # http://www.dc-swat.ru # include ../../sdk/Makefile.cfg APP_NAME = filemanager APP_DIR = $(DS_BUILD)/apps/$(APP_NAME) DEPS = app.xml lua/main.lua all: install clean: @echo Nothing clean install: $(DEPS) -mkdir -p $(APP_DIR) cp app.xml $(APP_DIR)/app.xml cp -R images $(APP_DIR) cp -R lua $(APP_DIR) <file_sep>/modules/isoldr/exec.c /* KallistiOS ##version## exec.c Copyright (C) 2002 <NAME> Copyright (C) 2013-2023 SWAT */ #include <kos.h> #include <arch/exec.h> #include <kos/dbgio.h> #include <arch/rtc.h> #include <dc/spu.h> #include <dc/sound/sound.h> #include <assert.h> #include <string.h> #include <stdio.h> /* Pull these in from execasm.s */ extern uint32 _isoldr_exec_template[]; extern uint32 _isoldr_exec_template_values[]; extern uint32 _isoldr_exec_template_end[]; /* Pull this in from startup.s */ extern uint32 _arch_old_sr, _arch_old_vbr, _arch_old_stack, _arch_old_fpscr; /* GCC stuff */ extern void _fini(void); static void isoldr_arch_auto_shutdown() { fs_dclsocket_shutdown(); net_shutdown(); snd_shutdown(); timer_shutdown(); la_shutdown(); bba_shutdown(); maple_shutdown(); cdrom_shutdown(); spu_dma_shutdown(); spu_shutdown(); pvr_shutdown(); library_shutdown(); fs_dcload_shutdown(); fs_vmu_shutdown(); vmufs_shutdown(); fs_iso9660_shutdown(); fs_ramdisk_shutdown(); fs_romdisk_shutdown(); fs_pty_shutdown(); fs_shutdown(); thd_shutdown(); rtc_shutdown(); } static void isoldr_arch_shutdown() { /* Run dtors */ _fini(); dbglog(DBG_CRITICAL, "arch: shutting down kernel\n"); /* Turn off UBC breakpoints, if any */ ubc_disable_all(); /* Do auto-shutdown */ isoldr_arch_auto_shutdown(); /* Shut down IRQs */ irq_shutdown(); } /* Replace the currently running image with whatever is at the pointer; note that this call will never return. */ void isoldr_exec_at(const void *image, uint32 length, uint32 address, uint32 params_len) { /* Find the start/end of the trampoline template and make a stack buffer of that size */ uint32 tstart = (uint32)_isoldr_exec_template, tend = (uint32)_isoldr_exec_template_end; uint32 tcount = (tend - tstart) / 4; uint32 buffer[tcount]; uint32 * values; uint32 i; assert((tend - tstart) % 4 == 0); /* Turn off interrupts */ irq_disable(); /* Flush the data cache for the source area */ dcache_flush_range((uint32)image, length); /* Copy over the trampoline */ for(i = 0; i < tcount; i++) buffer[i] = _isoldr_exec_template[i]; /* Plug in values */ values = buffer + (_isoldr_exec_template_values - _isoldr_exec_template); values[0] = (uint32)image; /* Source */ values[1] = address; /* Destination */ values[2] = length / 4; /* Length in uint32's */ values[3] = _arch_old_stack; /* Patch in old R15 */ values[4] = params_len; /* Params size */ /* Flush both caches for the trampoline area */ dcache_flush_range((uint32)buffer, tcount * 4); icache_flush_range((uint32)buffer, tcount * 4); /* Shut us down */ isoldr_arch_shutdown(); /* Reset our old SR, VBR, and FPSCR */ __asm__ __volatile__("ldc %0,sr\n" : /* no outputs */ : "z"(_arch_old_sr) : "memory"); __asm__ __volatile__("ldc %0,vbr\n" : /* no outputs */ : "z"(_arch_old_vbr) : "memory"); __asm__ __volatile__("lds %0,fpscr\n" : /* no outputs */ : "z"(_arch_old_fpscr) : "memory"); /* Jump to the trampoline */ { typedef void (*trampoline_func)() __noreturn; trampoline_func trampoline = (trampoline_func)buffer; trampoline(); } } <file_sep>/modules/bitcoin/Makefile # # Bitcoin module for DreamShell # Copyright (C)2022 SWAT # http://www.dc-swat.ru # TARGET_NAME = bitcoin OBJS = module.o DBG_LIBS = -lds LIBS = -lsecp256k1 EXPORTS_FILE = exports.txt VER_MAJOR = 0 VER_MINOR = 1 VER_MICRO = 0 KOS_CFLAGS += -I./secp256k1/include KOS_LIB_PATHS += -L./secp256k1/.libs all: rm-elf build_lib include ../../sdk/Makefile.loadable secp256k1/autogen.sh: git clone https://github.com/bitcoin-core/secp256k1.git cd ./secp256k1 && git checkout 485f608fa9e28f132f127df97136617645effe81 secp256k1/Makefile: secp256k1/autogen.sh cd ./secp256k1 && ./autogen.sh && ./configure \ --prefix="`pwd`/build" --host=$(KOS_CC_PREFIX) LIBS="$(KOS_LIBS)" \ CFLAGS="$(KOS_CFLAGS)" LDFLAGS="$(KOS_LDFLAGS)" \ --without-asm --disable-exhaustive-tests \ --disable-tests --disable-examples --disable-shared --disable-benchmark \ --with-ecmult-window=5 --with-ecmult-gen-precision=2 \ --enable-external-default-callbacks --enable-module-recovery \ --enable-module-ecdh --enable-module-schnorrsig build_lib: secp256k1/Makefile cd ./secp256k1 && make rm-elf: -rm -f $(TARGET) || true -rm -f $(TARGET_LIB) || true install: $(TARGET) $(TARGET_LIB) -rm -f $(DS_BUILD)/modules/$(TARGET) || true -rm -f $(DS_SDK)/lib/$(TARGET_LIB) || true cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/include/ds.h /** * \file ds.h * \brief DreamShell core header * \date 2004-2023 * \author SWAT www.dc-swat.ru */ #ifndef _DS_CORE_H #define _DS_CORE_H #include <kos.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include "video.h" #include "list.h" #include "module.h" #include "events.h" #include "console.h" #include "lua.h" #include "app.h" #include "utils.h" #include "cfg+.h" #include "exceptions.h" #include "settings.h" /** * Get DreamShell version code */ uint32 GetVersion(); /** * Set DreamShell version code and update env string */ void SetVersion(uint32 ver); /** * Get the build type as string (Alpha, Beta, RC and Release) */ const char *GetVersionBuildTypeString(int type); /** * Initialize and shutdown DreamShell core */ int InitDS(); void ShutdownDS(); #endif /* _DS_CORE_H */ <file_sep>/firmware/aica/codec/pll.h #ifndef _PLL_H_ #define _PLL_H_ #define PLLDIV 3 #define PLLMUL 26 #endif /* _PLL_H_ */ <file_sep>/include/drivers/rtc.h /** * \file rtc.h * \brief Real time clock * \date 2015-2016 * \author SWAT www.dc-swat.ru */ #ifndef _DS_RTC_H #define _DS_RTC_H #include <sys/cdefs.h> __BEGIN_DECLS #include <arch/types.h> #include <sys/time.h> #include <time.h> /** * Grabs the current RTC seconds counter and adjusts it to the Unix Epoch. * * Return: * On SUCCESS UNIX Time Stamp * On ERROR -1 */ time_t rtc_gettime(); /** * Adjusts the given time value to the AICA Epoch and sets the RTC seconds counter. * * Return: * On SUCCESS 0 * On ERROR -1 */ int rtc_settime(time_t time); /** * Grabs the current RTC seconds counter and write to struct tm. * * Return: * On SUCCESS 0 * On ERROR -1 */ int rtc_gettimeutc(struct tm *time); /** * Adjusts the given time value from struct tm to the AICA Epoch and sets the RTC seconds counter. * * Return: * On SUCCESS 0 * On ERROR -1 */ int rtc_settimeutc(const struct tm *time); /** * Grabs the current RTC seconds counter and write to struct timeval. */ void rtc_gettimeofday(struct timeval *tv); /** * Adjusts the given time value from struct timeval to the AICA Epoch and sets the RTC seconds counter. * * Return: * On SUCCESS 0 * On ERROR -1 */ int rtc_settimeofday(const struct timeval *tv); __END_DECLS #endif /* _DS_RTC_H */ <file_sep>/firmware/isoldr/loader/fs/fat/fs.c /** * DreamShell ISO Loader * FAT file system * (c)2011-2023 SWAT <http://www.dc-swat.ru> */ #include <main.h> #include <asic.h> #include "ffconf.h" #define SZ_TBL 32 enum FILE_STATE { FILE_STATE_UNUSED = 0, FILE_STATE_USED = 1, FILE_STATE_POLL = 2 }; typedef struct { FIL fp; uint32 state; fs_callback_f *poll_cb; int dma_mode; #if _USE_FASTSEEK DWORD cltbl[SZ_TBL]; #endif } FILE; static FATFS *_fat_fs = NULL; static FILE *_files = NULL; #ifdef DEV_TYPE_IDE static int dma_mode = FS_DMA_SHARED; #else static int dma_mode = 0; #endif PARTITION VolToPart[_VOLUMES] = {{0, 0}}; #ifdef LOG # define CHECK_FD() \ if(fd < 0 || fd > (MAX_OPEN_FILES - 1) || _files[fd].state == FILE_STATE_UNUSED) { \ LOGFF("Bad fd = %d\n", fd); \ return FS_ERR_NOFILE; \ } \ FILE *file = &_files[fd] #else # define CHECK_FD() FILE *file = &_files[fd] #endif static int fs_get_fd() { for(int i = 0; i < MAX_OPEN_FILES; i++) { if(_files[i].state == FILE_STATE_UNUSED) { return i; } } return FS_ERR_NUMFILES; } int fs_init() { char path[3] = "0:"; path[2] = '\0'; VolToPart[0].pd = 0; VolToPart[0].pt = IsoInfo->fs_part + 1; _fat_fs = (FATFS *) malloc(sizeof(FATFS) + 32); _files = (FILE *) malloc(sizeof(FILE) * MAX_OPEN_FILES); if (!_fat_fs || !_files) { LOGFF("Memory failed"); return -1; } _fat_fs = (FATFS *)ALIGN32_ADDR((uint32)_fat_fs); LOGF("FATFS: 0x%08lx, secbuf: 0x%08lx, FILEs: 0x%08lx\n", (uint32)_fat_fs, (uint32)_fat_fs->win, (uint32)_files); memset(_fat_fs, 0, sizeof(FATFS)); memset(_files, 0, sizeof(FILE) * MAX_OPEN_FILES); if(disk_initialize(0) == 0) { LOGF("Mounting FAT filesystem...\n"); if(f_mount(_fat_fs, path, 1) != FR_OK) { return -1; } return 0; } printf("Error, can't init "DEV_NAME".\n"); return -1; } void fs_enable_dma(int state) { #ifdef DBG if(dma_mode != state) LOGFF("%d\n", state); #endif dma_mode = state; } int fs_dma_enabled() { return dma_mode; } int open(const char *path, int flags) { if (!_files) { return FS_ERR_SYSERR; } int fd = fs_get_fd(); if(fd < 0) { LOGFF("ERROR, open limit is %d\n", MAX_OPEN_FILES); return fd; } FRESULT r; BYTE fat_flags = 0; FILE *file = &_files[fd]; int mode = (flags & O_MODE_MASK); switch(mode) { case O_RDONLY: fat_flags = (FA_OPEN_EXISTING | FA_READ); break; #if _FS_READONLY == 0 case O_WRONLY: fat_flags = FA_WRITE | (flags & O_TRUNC ? FA_CREATE_ALWAYS : FA_CREATE_NEW); break; case O_RDWR: fat_flags = (FA_WRITE | FA_READ) | (flags & O_TRUNC ? FA_CREATE_ALWAYS : FA_OPEN_ALWAYS); break; #endif default: return FS_ERR_PARAM; } int old_dma_mode = fs_dma_enabled(); fs_enable_dma(FS_DMA_DISABLED); r = f_open(&file->fp, path, fat_flags); if(r != FR_OK) { LOGFF("failed to open %s, error %d\n", path, r); fs_enable_dma(old_dma_mode); if (r == FR_EXIST) { return FS_ERR_EXISTS; } else if(r == FR_NO_PATH) { return FS_ERR_NO_PATH; } return FS_ERR_NOFILE; } if((flags & O_APPEND) && file->fp.fsize > 0) { f_lseek(&file->fp, file->fp.fsize - 1); } #if _USE_FASTSEEK if(mode == O_RDONLY) { /* Using fast seek feature */ file->fp.cltbl = file->cltbl; /* Enable fast seek feature */ file->cltbl[0] = SZ_TBL; /* Set table size to the first item */ /* Create linkmap */ r = f_lseek(&file->fp, CREATE_LINKMAP); if(r == FR_NOT_ENOUGH_CORE) { size_t count = file->fp.cltbl[0]; DWORD *cltbl = (DWORD *)malloc(count * sizeof(DWORD)); if (cltbl) { memset(cltbl, 0, count * sizeof(DWORD)); cltbl[0] = count; file->fp.cltbl = cltbl; r = f_lseek(&file->fp, CREATE_LINKMAP); } } if(r != FR_OK) { file->fp.cltbl = NULL; LOGFF("ERROR, creating linkmap required %d dwords, code %d\n", file->fp.cltbl[0], r); } else { LOGFF("Created linkmap with %d sequences\n", file->fp.cltbl[0]); } } #endif /* _USE_FASTSEEK */ fs_enable_dma(old_dma_mode); if(flags & O_PIO) { file->dma_mode = FS_DMA_DISABLED; } else { file->dma_mode = -1; } file->state = FILE_STATE_USED; return fd; } int close(int fd) { FRESULT rc; CHECK_FD(); if(file->poll_cb) { LOGFF("WARNING, aborting async for fd %d\n", fd); abort_async(fd); } rc = f_close(&file->fp); if (file->fp.cltbl && file->fp.cltbl[0] > SZ_TBL) { free(file->fp.cltbl); } memset(file, 0, sizeof(FILE)); if(rc != FR_OK) { LOGFF("ERROR, fd %d code %d\n", fd, rc); return FS_ERR_SYSERR; } return 0; } int read(int fd, void *ptr, unsigned int size) { CHECK_FD(); if(file->poll_cb) { LOGFF("WARNING, aborting async for fd %d\n", fd); abort_async(fd); } int old_dma_mode = fs_dma_enabled(); if(file->dma_mode > -1) { fs_enable_dma(file->dma_mode); } uint br; FRESULT rs = f_read(&file->fp, ptr, size, &br); fs_enable_dma(old_dma_mode); if(rs != FR_OK) { LOGFF("ERROR %d\n", rs); return FS_ERR_SYSERR; } return br; } int pre_read(int fd, unsigned int size) { CHECK_FD(); FRESULT rc = f_pre_read(&file->fp, size); if(rc != FR_OK) { LOGFF("ERROR, fd %d code %d\n", fd, rc); return FS_ERR_SYSERR; } return 0; } int read_async(int fd, void *ptr, unsigned int size, fs_callback_f *cb) { CHECK_FD(); if(file->poll_cb) { LOGFF("WARNING, aborting async for fd %d\n", fd); abort_async(fd); } if (fs_dma_enabled() == FS_DMA_DISABLED) { int rv = read(fd, ptr, size); cb(rv); return 0; } file->poll_cb = cb; if(f_read_async(&file->fp, ptr, size) == FR_OK) { return 0; } file->poll_cb = NULL; return FS_ERR_SYSERR; } int abort_async(int fd) { CHECK_FD(); FRESULT rc; if(!file->poll_cb) { return FS_ERR_PARAM; } file->poll_cb = NULL; rc = f_abort(&file->fp); if(rc != FR_OK) { LOGFF("ERROR, fd %d code %d\n", fd, rc); return FS_ERR_SYSERR; } return 0; } int poll(int fd) { UINT bp = 0; FRESULT rc; int rv = 0; fs_callback_f *cb; CHECK_FD(); if(!file->poll_cb || file->state == FILE_STATE_POLL) { LOGFF("Error, not async fd\n"); return 0; } if(file->state == FILE_STATE_POLL) { LOGFF("Busy\n"); return 1; } file->state = FILE_STATE_POLL; rc = f_poll(&file->fp, &bp); DBGFF("%d %d %d\n", fd, rc, bp); switch(rc) { case FR_OK: cb = file->poll_cb; file->poll_cb = NULL; cb(bp); rv = 0; break; case FR_NOT_READY: rv = bp; break; default: LOGFF("ERROR, fd %d code %d bytes %d\n", fd, rc, bp); cb = file->poll_cb; file->poll_cb = NULL; cb(-1); rv = -1; break; } file->state = FILE_STATE_USED; return rv; } void poll_all(int err) { for(int i = 0; i < MAX_OPEN_FILES; i++) { FILE *file = &_files[i]; if(file->state == FILE_STATE_USED && file->poll_cb != NULL) { if (err) { fs_callback_f *cb = file->poll_cb; file->poll_cb = NULL; cb(err); } else { poll(i); } } } } #if _FS_READONLY == 0 int write(int fd, void *ptr, unsigned int size) { CHECK_FD(); int old_dma_mode = fs_dma_enabled(); if(file->dma_mode > -1) { fs_enable_dma(file->dma_mode); } uint bw; FRESULT rs = f_write(&file->fp, ptr, size, &bw); fs_enable_dma(old_dma_mode); if(rs != FR_OK) { LOGFF("ERROR %d\n", rs); return FS_ERR_SYSERR; } return bw; } #endif long int lseek(int fd, long int offset, int whence) { FRESULT r = FR_OK; CHECK_FD(); switch(whence) { case SEEK_SET: if(file->fp.fptr != (uint32)offset) r = f_lseek(&file->fp, offset); break; case SEEK_CUR: r = f_lseek(&file->fp, file->fp.fptr + offset); break; case SEEK_END: r = f_lseek(&file->fp, file->fp.fsize + offset); break; default: break; } return r == FR_OK ? (long int)file->fp.fptr : FS_ERR_SYSERR; } long int tell(int fd) { CHECK_FD(); return file->fp.fptr; } unsigned long total(int fd) { CHECK_FD(); return file->fp.fsize; } int ioctl(int fd, int cmd, void *data) { CHECK_FD(); switch(cmd) { case FS_IOCTL_GET_LBA: { unsigned long sec = clust2sect(file->fp.fs, file->fp.sclust); memcpy(data, &sec, sizeof(sec)); return 0; } #if _FS_READONLY == 0 case FS_IOCTL_SYNC: if (f_sync(&file->fp) == FR_OK) { return 0; } break; #endif default: return FS_ERR_PARAM; } return FS_ERR_SYSERR; } <file_sep>/sdk/toolchain/versions.sh #!/bin/sh export GCC_VER=9.3.0 export BINUTILS_VER=2.34 export NEWLIB_VER=3.3.0 export GMP_VER=6.1.0 export MPFR_VER=3.1.4 export MPC_VER=1.0.3 <file_sep>/firmware/isoldr/Makefile # # DreamShell ISO Loader Makefile # Copyright (C) 2022 SWAT # http://www.dc-swat.ru # _SUBDIRS = loader syscalls all: $(patsubst %, _dir_%, $(_SUBDIRS)) $(patsubst %, _dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _dir_%, %, $@) clean: $(patsubst %, _clean_dir_%, $(_SUBDIRS)) $(patsubst %, _clean_dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _clean_dir_%, %, $@) clean install: $(patsubst %, _install_dir_%, $(_SUBDIRS)) $(patsubst %, _install_dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _install_dir_%, %, $@) install <file_sep>/modules/ogg/liboggvorbis/liboggvorbis/libogg/include/ogg/config_types.h #ifndef __CONFIG_TYPES_H__ #define __CONFIG_TYPES_H__ /* these are filled in by configure */ typedef int16 ogg_int16_t; typedef uint16 ogg_uint16_t; typedef int32 ogg_int32_t; typedef uint32 ogg_uint32_t; typedef int64 ogg_int64_t; #endif <file_sep>/sdk/bin/src/Makefile # # DreamShell SDK utils Makefile # Copyright (C) 2020-2022 SWAT # http://www.dc-swat.ru # _SUBDIRS = scramble ciso gdiopt raw2wav wav2adpcm img4dc mkbios # cdirip nerorip all: $(patsubst %, _dir_%, $(_SUBDIRS)) $(patsubst %, _dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _dir_%, %, $@) clean: $(patsubst %, _clean_dir_%, $(_SUBDIRS)) $(patsubst %, _clean_dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _clean_dir_%, %, $@) clean install: $(patsubst %, _install_dir_%, $(_SUBDIRS)) $(patsubst %, _install_dir_%, $(_SUBDIRS)): $(MAKE) -C $(patsubst _install_dir_%, %, $@) install <file_sep>/modules/ftpd/lftpd/lftpd_io.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdarg.h> #include <stdbool.h> #include <unistd.h> #include <ctype.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <dirent.h> #include <errno.h> #include <sys/stat.h> #include "private/lftpd_io.h" char* lftpd_io_canonicalize_path(const char* base, const char* name) { // if either argument is null, treat it as empty if (base == NULL) { base = ""; } if (name == NULL) { name = ""; } // if name is absolute, ignore the base and use name as the // full path char* path = NULL; if (name[0] == '/') { path = strdup(name); } // otherwise append name to base with / as a separator else { int err = asprintf(&path, "%s/%s", base, name); if (err < 0) { return NULL; } } // allocate enough room for the absolute path, which can never be // longer than the path, plus 1 for a / and 1 for the terminator size_t abs_path_len = strlen(path) + 1 + 1; char* abs_path = malloc(abs_path_len); memset(abs_path, 0, abs_path_len); // run through the path a segment at a time, adding each to // abs_path with with a preceding / and resolving . and .. char* save_pointer = NULL; char* token = strtok_r(path, "/", &save_pointer); while (token) { if (strcmp(token, ".") == 0) { // ignore it } else if (strcmp(token, "..") == 0) { // go back one element char* p = strrchr(abs_path, '/'); if (p != NULL) { p[0] = '\0'; } } else { strcat(abs_path, "/"); strcat(abs_path, token); } token = strtok_r(NULL, "/", &save_pointer); } free(path); // a path like /test/.. might have removed everything and left // an empty path, so detect that condition and fix it if (strlen(abs_path) == 0) { strcpy(abs_path, "/"); } return abs_path; } <file_sep>/modules/openssl/module.c /* DreamShell ##version## module.c - openssl module Copyright (C)2022 SWAT */ #include "ds.h" DEFAULT_MODULE_EXPORTS(openssl); <file_sep>/include/audio/ogg.h /* KallistiOS Ogg/Vorbis Decoder Library * for KOS ##version## * * sndoggvorbis.c * Copyright (C)2001,2002 <NAME> * Copyright (C)2002,2003,2004 <NAME> * * An Ogg/Vorbis player library using sndstream and functions provided by * ivorbisfile (Tremor). */ #include <kos.h> #include <vorbis/vorbisfile.h> int sndoggvorbis_init(); void sndoggvorbis_shutdown(); void sndoggvorbis_thd_quit(); /* Enable/disable queued waiting */ void sndoggvorbis_queue_enable(); void sndoggvorbis_queue_disable(); /* Wait for the song to be queued */ void sndoggvorbis_queue_wait(); /* Queue the song to start if it's in QUEUED */ void sndoggvorbis_queue_go(); /* getter and setter functions for information access */ int sndoggvorbis_isplaying(); void sndoggvorbis_setbitrateinterval(int interval); /* sndoggvorbis_getbitrate() * * returns the actual bitrate of the playing stream. * * NOTE: * The value returned is only actualized every once in a while ! */ long sndoggvorbis_getbitrate(); long sndoggvorbis_getposition(); /* The following getters only return the contents of specific comment * fields. It is thinkable that these return something like "NOT SET" * in case the specified field has not been set ! */ char *sndoggvorbis_getartist(); char *sndoggvorbis_gettitle(); char *sndoggvorbis_getgenre(); char *sndoggvorbis_getcommentbyname(const char *commentfield); /* sndoggvorbis_wait_start() * * let's the caller wait until the vorbis thread is signalling that it is ready * to decode data */ void sndoggvorbis_wait_start(); /* sndoggvorbis_thread() * * this function is called by sndoggvorbis_mainloop and handles all the threads * status handling and playing functionality. */ void sndoggvorbis_thread(); /* sndoggvorbis_stop() * * function to stop the current playback and set the thread back to * STATUS_READY mode. */ void sndoggvorbis_stop(); /* Same as sndoggvorbis_start, but takes an already-opened file. Once a file is passed into this function, we assume that _we_ own it. */ int sndoggvorbis_start_fd(FILE * fd, int loop); /* sndoggvorbis_start(...) * * function to start playback of a Ogg/Vorbis file. Expects a filename to * a file in the KOS filesystem. */ int sndoggvorbis_start(const char *filename,int loop); /* sndoggvorbis_shutdown() * * function that stops playing and shuts down the player thread. */ void sndoggvorbis_thd_quit(); /* sndoggvorbis_volume(...) * * function to set the volume of the streaming channel */ void sndoggvorbis_volume(int vol); /* sndoggvorbis_mainloop() * * code that runs in our decoding thread. sets up the semaphore. initializes the stream * driver and calls our *real* thread code */ void sndoggvorbis_mainloop(); <file_sep>/applications/region_changer/modules/Makefile # # Region Changer module for DreamShell # Copyright (C) 2010-2016 SWAT # http://www.dc-swat.ru # APP_NAME = region_changer LUA_MODULE_NAME = RC TARGET_NAME = app_$(APP_NAME) OBJS = module.o flashrom.o DBG_LIBS = -lds -ltolua EXPORTS_FILE = exports.txt VER_MAJOR = 1 VER_MINOR = 8 VER_MICRO = 5 KOS_CFLAGS += -I./ all: rm-elf include ../../../sdk/Makefile.loadable KOS_CFLAGS += -I$(DS_SDK)/include/lua rm-elf: -rm -f $(TARGET) install: $(TARGET) -rm $(DS_BUILD)/apps/$(APP_NAME)/modules/$(TARGET) cp $(TARGET) $(DS_BUILD)/apps/$(APP_NAME)/modules/$(TARGET) <file_sep>/modules/aicaos/arm/task.h #ifndef _TASK_H #define _TASK_H #include <stdint.h> #include <sys/reent.h> #include "../aica_common.h" #define DEFAULT_STACK_SIZE 4096 struct context { /* XXX: don't change the order */ uint32_t r0_r7[8]; aica_funcp_t pc; uint32_t r8_r14[7]; uint32_t cpsr; }; struct task { struct context context; struct _reent reent; char * stack; size_t stack_size; uint32_t id; }; /* Pointer to the current task */ extern struct task *current_task; /* Create a new task that will execute the given * routine, with the corresponding arguments. */ struct task * task_create(void *func, void *param[4]); /* Add the task to the runnable queue */ void task_add_to_runnable(struct task *task, unsigned char prio); /* Execute the given task. * XXX: This doesn't save the current context. */ void task_select(struct task *task); /* Reschedule (yield the task). * Located in task_asm.S */ void task_reschedule(void); /* Exit the currently running task. * This function is called automatically when the routine returns. */ void task_exit(void); #endif <file_sep>/include/settings.h /** * \file list.h * \brief DreamShell settings * \date 2016 * \author SWAT www.dc-swat.ru */ #ifndef _DS_SETTINGS_H #define _DS_SETTINGS_H #include <kos.h> typedef struct VideoSettings { /* Native video mode */ vid_mode_t mode; /* Bits per pixel */ int bpp; /* Screen texture size and filter */ int tex_width; int tex_height; int tex_filter; /* -1 (auto) */ // Virtual screen size int virt_width; int virt_height; int reserved[16]; } VideoSettings_t; typedef struct Settings { /* Core version */ uint32 version; /* Root directory with resources (leave empty for auto detect) */ char root[NAME_MAX / 2]; /* Default startup lua script path (without root) or console/lua script content */ char startup[NAME_MAX / 2]; /* Default app name */ char app[64]; /* Video */ VideoSettings_t video; } Settings_t; Settings_t *GetSettings(); void SetSettings(Settings_t *settings); void ResetSettings(); int LoadSettings(); int SaveSettings(); #endif /* _DS_SETTINGS_H */ <file_sep>/include/utils.h /** * \file utils.h * \brief DreamShell utils * \date 2004-2023 * \author SWAT www.dc-swat.ru */ #ifndef _DS_UTILS_H #define _DS_UTILS_H /* Macros v2 for accessing/creating DreamShell version codes */ #define DS_VER_MAJOR(v) ((v >> 24) & 0xff) #define DS_VER_MINOR(v) ((v >> 16) & 0xff) #define DS_VER_MICRO(v) ((v >> 8) & 0xff) #define DS_VER_BUILD(v) ((v >> 0) & 0xff) /* Divide build to type and number (if build counter is not used) */ #define DS_VER_BUILD_TYPE(b) ((b & 0xf0) / 0xf) #define DS_VER_BUILD_TYPE_STR(b) (GetVersionBuildTypeString(DS_VER_BUILD_TYPE(b))) #define DS_VER_BUILD_NUM(b) (b & 0x0f) enum { DS_VER_BUILD_TYPE_APLHA = 0, DS_VER_BUILD_TYPE_BETA, DS_VER_BUILD_TYPE_RC, DS_VER_BUILD_TYPE_RELEASE }; #define DS_MAKE_VER(MAJOR, MINOR, MICRO, BUILD) \ ( (((MAJOR) & 0xff) << 24) \ | (((MINOR) & 0xff) << 16) \ | (((MICRO) & 0xff) << 8) \ | (((BUILD) & 0xff) << 0) ) /* Return 0 if error */ int FileSize(const char *fn); int FileExists(const char *fn); int DirExists(const char *dir); int PeriphExists(const char *name); int CopyFile(const char *src_fn, const char *dest_fn, int verbose); int CopyDirectory(const char *src_path, const char *dest_path, int verbose); void arch_shutdown(); int flashrom_get_region_only(); int is_hacked_bios(); int is_custom_bios(); int is_no_syscalls(); uint32 gzip_get_file_size(const char *filename); void dbgio_set_dev_ds(); void dbgio_set_dev_scif(); void dbgio_set_dev_fb(); void dbgio_set_dev_sd(); char *realpath(const char *path, char *resolved); int makeabspath_wd(char *buff, char *path, char *dir, size_t size); const char *relativeFilePath(const char *rel, const char *file); int relativeFilePath_wb(char *buff, const char *rel, const char *file); char *getFilePath(const char *file); int mkpath(const char *path); void readstr(FILE *f, char *string); int splitline(char **argv, int max, char *line); int hex_to_int(char c); char *strtolower(char *str); char *strsep(char **stringp, const char *delim); char* substring(const char* str, size_t begin, size_t len); #if defined(__STRICT_ANSI__) char *strndup(const char *, size_t); #endif /* Optimized memory utils */ void *memcpy_sh4(void *dest, const void *src, size_t count); void *memmove_sh4(void *dest, const void *src, size_t count); void *memset_sh4(void *dest, uint32 val, size_t count); #define memcpy memcpy_sh4 #define memmove memmove_sh4 #define memset memset_sh4 #ifndef strcasestr char *strcasestr(const char *str1, const char *str2); #endif #endif /*_DS_UTILS_H */ <file_sep>/firmware/aica/codec/dac.h /* Copyright (C) 2006 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef _DAC_H_ #define _DAC_H_ #define AIC_REG_LINVOL 0x00 #define AIC_REG_RINVOL 0x01 #define AIC_REG_LOUTVOL 0x02 #define AIC_REG_ROUTVOL 0x03 #define AIC_REG_AN_PATH 0x04 #define AIC_REG_DIG_PATH 0x05 #define AIC_REG_POWER 0x06 #define AIC_REG_DIG_FORMAT 0x07 #define AIC_REG_SRATE 0x08 #define AIC_REG_DIG_ACT 0x09 #define AIC_REG_RESET 0x0F #define AIC_USB (1 << 0) #define AIC_BOSR (1 << 1) #define AIC_SR0 (1 << 2) #define AIC_SR1 (1 << 3) #define AIC_SR2 (1 << 4) #define AIC_SR3 (1 << 5) #define AIC_MICB (1 << 0) #define AIC_MICM (1 << 1) #define AIC_INSEL (1 << 2) #define AIC_BYP (1 << 3) #define AIC_DAC (1 << 4) #define AIC_STE (1 << 5) #define AIC_STA0 (1 << 6) #define AIC_STA1 (1 << 7) #define AIC_STA2 (1 << 8) #define MAX_BUFFERS 3 #define DAC_BUFFER_MAX_SIZE 2400 extern short dac_buffer[MAX_BUFFERS][DAC_BUFFER_MAX_SIZE]; extern int dac_buffer_size[MAX_BUFFERS]; extern unsigned long current_srate; extern unsigned int underruns; void dac_reset(); int dac_get_writeable_buffer(); int dac_get_readable_buffer(); int dac_readable_buffers(); int dac_writeable_buffers(); int dac_busy_buffers(); int adc_busy_buffers(); int dac_fill_dma(); void dac_enable_dma(); void dac_disable_dma(); int dac_next_dma_empty(); int dac_first_dma_empty(); int adc_next_dma_empty(); int adc_first_dma_empty(); void dac_set_first_dma(short *buffer, int n); void dac_set_next_dma(short *buffer, int n); int dma_endtx(void); void dac_write_reg(unsigned char reg, unsigned short value); int dac_set_srate(unsigned long srate); void dac_init(void); #endif /* _DAC_H_ */ <file_sep>/modules/bflash/bflash.c /* DreamShell ##version## bflash.c (c)2009-2014 SWAT http://www.dc-swat.ru 04/10/2016 jfdelnero : MX29L3211 & MX29F1610 support fixed. */ #include <assert.h> #include <stdio.h> #include "ds.h" #include "drivers/bflash.h" #include "flash_if.h" /* Flash port address */ static vuint8 *const flashport = (vuint8 *)BIOS_FLASH_ADDR; /* Accurate usec delay for JEDEC */ /* jfdn : I am very suspicious about this function. Seems a way slower than it should in my setup... To be checked */ static void jedec_delay(int usec) { timer_prime(TMU1, 1000000, 0); timer_clear(TMU1); timer_start(TMU1); while(usec--) { while(!timer_clear(TMU1)) ; } timer_stop(TMU1); } static void delay(int usec) { if(usec) { timer_prime(TMU1, 1000000 / usec, 0); timer_clear(TMU1); timer_start(TMU1); while(!timer_clear(TMU1)) ; timer_stop(TMU1); } } /* Read a flash value */ #define bflash_read(addr) flashport[addr] /* Determine if the flash memory is busy writing */ #define bflash_busy(addr) ((bflash_read(addr) & D6_MASK) != (bflash_read(addr) & D6_MASK)) /* We'll do this before sending a command */ #define send_unlock(dev) \ flashport[dev->unlock[0]] = CMD_UNLOCK_DATA_1; \ flashport[dev->unlock[1]] = CMD_UNLOCK_DATA_2 #define send_unlock_jedec(dev) \ flashport[dev->unlock[0]] = CMD_UNLOCK_DATA_1; \ jedec_delay(10); \ flashport[dev->unlock[1]] = CMD_UNLOCK_DATA_2; \ jedec_delay(10) /* Send a command (including unlock) */ static void send_cmd(bflash_dev_t *dev, uint16 cmd) { if(dev->unlock[0] == ADDR_UNLOCK_1_JEDEC) { // int old = irq_disable(); switch(cmd) { case CMD_MANUFACTURER_UNLOCK_DATA: send_unlock_jedec(dev); flashport[dev->unlock[0]] = cmd; timer_spin_sleep(10); // Same as jedec_delay(10000); break; case CMD_RESET_DATA: send_unlock_jedec(dev); flashport[dev->unlock[0]] = cmd; jedec_delay(40); case CMD_PROGRAM_UNLOCK_DATA: send_unlock(dev); flashport[dev->unlock[0]] = cmd; default: send_unlock_jedec(dev); flashport[dev->unlock[0]] = cmd; jedec_delay(10); break; } // irq_restore(old); } else { send_unlock(dev); flashport[dev->unlock[0]] = cmd; } } bflash_manufacturer_t *bflash_find_manufacturer(uint16 mfr_id) { int i = 0; while (bflash_manufacturers[i].id != 0) { if (mfr_id == bflash_manufacturers[i].id) return (bflash_manufacturer_t *)&bflash_manufacturers[i]; i++; } return NULL; } bflash_dev_t *bflash_find_dev(uint16 dev_id) { int i = 0; while (bflash_devs[i].id != 0) { if (dev_id == bflash_devs[i].id) return (bflash_dev_t *)&bflash_devs[i]; i++; } return NULL; } /* Return sector index by sector addr */ int bflash_get_sector_index(bflash_dev_t *dev, uint32 addr) { int i = 0; for (i = 0; i < dev->sec_count; i++) { if(dev->sectors[i] == addr) { return i; } } return -1; } /* Wait until the flash is ready, with timeout */ static int bflash_wait_ready(bflash_dev_t *dev, uint32 addr, int timeout) { int wait = 0; if (timeout < 0) { timeout = -timeout; wait = 1; } while (timeout-- && bflash_busy(addr)) { if (wait) thd_sleep(100); else thd_pass(); } if (timeout <= 0) { ds_printf("DS_ERROR: Writing to flash timed out\n"); return -1; } return 0; } /* Wait a flag from the flash, with timeout */ static int bflash_wait_flag(bflash_dev_t *dev, uint32 addr, int timeout,uint8 mask) { int wait = 0; if (timeout < 0) { timeout = -timeout; wait = 1; } while (timeout-- && !( bflash_read(0) & mask ) ) { if (wait) thd_sleep(10); else thd_pass(); } if (timeout <= 0) { ds_printf("DS_ERROR: Writing to flash timed out (mask : 0x%.2X)\n",mask); return -1; } return 0; } /* Write a single flash value, return -1 if we fail or timeout */ int bflash_write_value(bflash_dev_t *dev, uint32 addr, uint8 value) { int irqState; switch(dev->prog_mode) { case F_FLASH_DATAPOLLING_PM: send_cmd(dev, CMD_PROGRAM_UNLOCK_DATA); flashport[addr] = value; if (bflash_wait_ready(dev, addr, 1000) < 0) { ds_printf("DS_ERROR: Failed writing value to flash at 0x%08lx (0x%02x vs 0x%02x)\n", addr, flashport[addr], value); return -1; } break; case F_FLASH_REGPOLLING_PM: flashport[dev->unlock[0]] = CMD_UNLOCK_DATA_1; flashport[dev->unlock[1]] = CMD_UNLOCK_DATA_2; /* The following loop must not be interrupted ! The flash device flush its buffer after 100us without access. */ irqState = irq_disable(); // Disable interrupts flashport[dev->unlock[0]] = CMD_PROGRAM_UNLOCK_DATA; flashport[addr] = value; irq_restore(irqState); // re-enable interrupts delay(250); // let's start the flash process (wait 100us min) if (bflash_wait_flag(dev, addr + dev->page_size, -800,D7_MASK) < 0) { send_cmd(dev, CMD_RESET_DATA); ds_printf("DS_ERROR: Failed writing page to flash at 0x%08lx : timeout !\n",addr); return -1; } /* Fast CMD_RESET_DATA */ flashport[dev->unlock[0]] = CMD_UNLOCK_DATA_1; delay(5); flashport[dev->unlock[1]] = CMD_UNLOCK_DATA_2; delay(5); flashport[dev->unlock[0]] = CMD_RESET_DATA; delay(5); break; default: return -2; break; } if (flashport[addr] != value) { ds_printf("DS_ERROR: Failed writing value to flash at 0x%08lx (0x%02x vs 0x%02x)\n", addr, flashport[addr], value); return -1; } return 0; } /* Write a page of flash, return -1 if we fail or timeout */ int bflash_write_page(bflash_dev_t *dev, uint32 addr, uint8 *data) { uint32 irqState; uint32 i; if(dev->page_size <= 1) { ds_printf("DS_ERROR: The flash device doesn't support page program mode.\n"); return -1; } switch(dev->prog_mode) { case F_FLASH_DATAPOLLING_PM: send_cmd(dev, CMD_PROGRAM_UNLOCK_DATA); for(i = 0; i < dev->page_size; i++) { flashport[addr + i] = data[i]; } if (bflash_wait_ready(dev, addr + dev->page_size, -15000) < 0) { ds_printf("DS_ERROR: Failed writing page to flash at 0x%08lx (0x%02x vs 0x%02x)\n", addr, flashport[addr + dev->page_size], data[dev->page_size - 1]); return -1; } if (flashport[addr + dev->page_size - 1] != data[dev->page_size - 1]) { ds_printf("DS_ERROR: Failed writing page to flash at 0x%08lx (0x%02x vs 0x%02x)\n", addr, flashport[addr + dev->page_size], data[dev->page_size - 1]); return -1; } break; case F_FLASH_REGPOLLING_PM: flashport[dev->unlock[0]] = CMD_UNLOCK_DATA_1; flashport[dev->unlock[1]] = CMD_UNLOCK_DATA_2; /* The following loop must not be interrupted ! The flash device flush its buffer after 100us without access.*/ irqState = irq_disable(); // Disable interrupts flashport[dev->unlock[0]] = CMD_PROGRAM_UNLOCK_DATA; for(i = 0; i < dev->page_size; i++) { flashport[addr + i] = data[i]; } irq_restore(irqState); // re-enable interrupts delay(250); // let's start the flash process (wait 100us min) if (bflash_wait_flag(dev, addr + dev->page_size, -800,D7_MASK) < 0) { send_cmd(dev, CMD_RESET_DATA); ds_printf("DS_ERROR: Failed writing page to flash at 0x%08lx : timeout !\n",addr); return -1; } /* Fast CMD_RESET_DATA */ flashport[dev->unlock[0]] = CMD_UNLOCK_DATA_1; delay(5); flashport[dev->unlock[1]] = CMD_UNLOCK_DATA_2; delay(5); flashport[dev->unlock[0]] = CMD_RESET_DATA; delay(5); /* Check the whole page */ for(i = 0; i < dev->page_size; i++) { if(flashport[addr + i] != data[i]){ ds_printf("DS_ERROR: Failed writing page to flash at 0x%08lx (0x%02x vs 0x%02x)\n", addr+i, flashport[addr + dev->page_size], data[dev->page_size - 1]); return -1; } } break; default: return -2; break; } return 0; } /* Write a buffer of data */ int bflash_write_data(bflash_dev_t *dev, uint32 addr, void *data, uint32 len) { uint8 *db = (uint8 *)data; uint32 i, cur_len = len, pos = 0; if(!(dev->flags & F_FLASH_PROGRAM)) { ds_printf("DS_ERROR: The flash device doesn't support program mode.\n"); return -1; } if(dev->page_size > 1) { while(cur_len >= dev->page_size) { pos = (len - cur_len); if (!(pos % 0x10000)) { ds_printf("DS_PROCESS: Writing page at 0x%08lx\n", addr + pos); } if (bflash_write_page(dev, addr + pos, db + pos) < 0) { ds_printf("DS_PROCESS: Aborting write page at 0x%08lx\n", addr + pos); return -1; } cur_len -= dev->page_size; } } for (i = 0; i < cur_len; i++) { if (!(i % 0x10000)) { ds_printf("DS_PROCESS: Writing value at 0x%08lx\n", i + addr); } if (bflash_write_value(dev, addr + i, db[i]) < 0) { ds_printf("DS_PROCESS: Aborting write value at 0x%08lx\n", i + addr); return -1; } } return 0; } /* Erase a sector of flash */ int bflash_erase_sector(bflash_dev_t *dev, uint32 addr) { if(!(dev->flags & F_FLASH_ERASE_SECTOR)) { ds_printf("DS_ERROR: The flash device doesn't support erase sectors.\n"); return -1; } switch(dev->prog_mode) { case F_FLASH_DATAPOLLING_PM: send_cmd(dev, CMD_SECTOR_ERASE_UNLOCK_DATA); send_unlock(dev); flashport[addr] = CMD_SECTOR_ERASE_UNLOCK_DATA_2; if (bflash_wait_ready(dev, addr, -15000) < 0) { ds_printf("DS_ERROR: Failed erasing flash sector at 0x%08lx (timeout...)\n", addr); return -1; } break; case F_FLASH_REGPOLLING_PM: send_cmd(dev, CMD_SECTOR_ERASE_UNLOCK_DATA); send_unlock(dev); flashport[addr] = CMD_SECTOR_ERASE_UNLOCK_DATA_2; if (bflash_wait_flag(dev, addr, -400,D7_MASK) < 0) { ds_printf("DS_ERROR: Failed erasing flash sector at 0x%08lx (timeout...)\n", addr); send_cmd(dev, CMD_RESET_DATA); return -1; } send_cmd(dev, CMD_RESET_DATA); break; default: return -2; break; } if (flashport[addr] != 0xff) { ds_printf("DS_ERROR: Failed erasing flash sector at 0x%08lx\n", addr); return -1; } return 0; } /* Erase the whole flash chip */ int bflash_erase_all(bflash_dev_t *dev) { uint32 i; if(!(dev->flags & F_FLASH_ERASE_ALL)) { ds_printf("DS_ERROR: The flash device doesn't support erase full chip.\n"); return -1; } switch(dev->prog_mode) { case F_FLASH_DATAPOLLING_PM: send_cmd(dev, CMD_SECTOR_ERASE_UNLOCK_DATA); send_cmd(dev, CMD_ERASE_ALL); if (bflash_wait_ready(dev, 0, -30000) < 0) { ds_printf("DS_ERROR: Failed erasing full chip.\n"); return -1; } break; case F_FLASH_REGPOLLING_PM: send_cmd(dev, CMD_SECTOR_ERASE_UNLOCK_DATA); send_cmd(dev, CMD_ERASE_ALL); if (bflash_wait_flag(dev, 0, -30000,D6_MASK) < 0) { ds_printf("DS_ERROR: Failed erasing full chip. (ready timeout...)\n"); send_cmd(dev, CMD_RESET_DATA); return -1; } send_cmd(dev, CMD_RESET_DATA); break; } for(i=0;i<dev->size;i++) { if (flashport[i] != 0xff) { ds_printf("DS_ERROR: Failed erasing full chip.\n"); return -1; } } return 0; } int bflash_erase_suspend(bflash_dev_t *dev) { if(dev->flags & F_FLASH_ERASE_SUSPEND) { send_cmd(dev, CMD_ERASE_SUSPEND); return 0; } return -1; } int bflash_erase_resume(bflash_dev_t *dev) { if(dev->flags & F_FLASH_ERASE_SUSPEND) { send_cmd(dev, CMD_ERASE_RESUME); return 0; } return -1; } int bflash_sleep(bflash_dev_t *dev) { if(dev->flags & F_FLASH_SLEEP) { send_cmd(dev, CMD_SLEEP); return 0; } return -1; } int bflash_abort(bflash_dev_t *dev) { if(dev->flags & F_FLASH_ABORT) { send_cmd(dev, CMD_ABORT); return 0; } return -1; } void bflash_reset(bflash_dev_t *dev) { send_cmd(dev, CMD_RESET_DATA); } /* Reset and ask for manufacturer code */ static void bflash_get_id(bflash_dev_t *dev, uint16 *mfr_id, uint16 *dev_id) { send_cmd(dev, CMD_RESET_DATA); send_cmd(dev, CMD_MANUFACTURER_UNLOCK_DATA); *mfr_id = bflash_read(ADDR_MANUFACTURER); *dev_id = bflash_read(ADDR_DEVICE_ID) | (*mfr_id & 0xff) << 8; } /* Return 0 if detected supported flashchip */ int bflash_detect(bflash_manufacturer_t **mfr, bflash_dev_t **dev) { uint16 mfr_id = 0, dev_id = 0; bflash_manufacturer_t *b_mfr = NULL; bflash_dev_t *b_dev = NULL; bflash_dev_t tmp_dev; uint8 prev_mfrid,prev_devid; // To slowdown the rom access timings... // The default read/write speed is almost // the max eeprom read/write speed. // And the CS signal is not very clean due to the diode D501. //*((vuint32 *)0xA05F7484) = 0x1FF7; // SB_G1RWC - System ROM write access timing //*((vuint32 *)0xA05F7480) = 0x1FF7; // SB_G1RRC - System ROM read access timing // Commented - seems working fine at full speed now. memset(&tmp_dev, 0, sizeof(tmp_dev)); tmp_dev.flags = F_FLASH_READ; tmp_dev.unlock[0] = ADDR_UNLOCK_1_BM; tmp_dev.unlock[1] = ADDR_UNLOCK_2_BM; /* Store current rom value. Used to detect if the chip respond to the read id command */ prev_mfrid = flashport[ADDR_MANUFACTURER]; prev_devid = flashport[ADDR_DEVICE_ID]; bflash_get_id(&tmp_dev, &mfr_id, &dev_id); if( ( ( prev_mfrid == ( mfr_id & 0xFF ) ) && ( prev_devid == ( dev_id & 0xFF ) ) ) && getenv("EMU") == NULL) { tmp_dev.unlock[0] = ADDR_UNLOCK_1_JEDEC; tmp_dev.unlock[1] = ADDR_UNLOCK_2_JEDEC; bflash_get_id(&tmp_dev, &mfr_id, &dev_id); if( ( prev_mfrid == ( mfr_id & 0xFF ) ) && ( prev_devid == ( dev_id & 0xFF ) ) ) { tmp_dev.unlock[0] = ADDR_UNLOCK_1_WM; tmp_dev.unlock[1] = ADDR_UNLOCK_2_WM; bflash_get_id(&tmp_dev, &mfr_id, &dev_id); } } send_cmd(&tmp_dev, CMD_RESET_DATA); //ds_printf("DS_PROCESS: Searching device %04x/%04x\n", mfr_id, dev_id); b_mfr = bflash_find_manufacturer(mfr_id); b_dev = bflash_find_dev(dev_id); if(b_mfr == NULL && b_dev == NULL) { ds_printf("DS_WARNING: Unknown manufacturer/device pair 0x%02x/0x%02x\n", (mfr_id & 0xff), (dev_id & 0xff)); return -1; } if(b_mfr != NULL) { ds_printf("DS_OK: %s flash detected [0x%04x]\n", b_mfr->name, b_mfr->id); if(mfr != NULL) { *mfr = b_mfr; } } else { ds_printf("DS_OK: Uknown manufacturer flash detected [0x%04x]\n", mfr_id); } if(b_dev != NULL) { ds_printf("DS_OK: Flash device is %s [0x%04x]\n", b_dev->name, b_dev->id); if(dev != NULL) { *dev = b_dev; if(b_dev->id != SEGA_FLASH_DEVICE_ID && tmp_dev.unlock[0] != b_dev->unlock[0]) { ds_printf("DS_WARNING: Flash device detected with another commands than in database.\n" " Please send bug report about it (0x%04x/0x%04x)\n", tmp_dev.unlock[0], tmp_dev.unlock[1]); } } } else { ds_printf("DS_ERROR: Unknown flash device 0x%04x\n", dev_id); return -1; } return 0; } int bflash_auto_reflash(const char *file, uint32 start_sector, int erase_mode) { file_t f; uint8 *ptr; uint32 len; int i, b_idx; bflash_dev_t *dev = NULL; bflash_manufacturer_t *mrf = NULL; if(bflash_detect(&mrf, &dev) < 0) { return -1; } if(!(dev->flags & F_FLASH_PROGRAM)) { ds_printf("DS_ERROR: %s %s flash chip is not programmable.\n", mrf->name, dev->name); return -1; } f = fs_open(file, O_RDONLY); if (f < 0) { ds_printf("DS_ERROR: Couldn't open %s\n", file); return -1; } len = fs_total(f); if((len / 1024) > dev->size) { ds_printf("DS_ERROR: The firmware larger than a flash chip (%d KB vs %d KB).\n", (len / 1024), dev->size); fs_close(f); return -1; } ds_printf("DS_PROCESS: Loading firmware in to memory...\n"); ptr = (uint8 *) malloc(len); if(ptr == NULL) { ds_printf("DS_ERROR: Not enough memory\n"); fs_close(f); return -1; } memset(ptr, 0, len); fs_read(f, ptr, len); fs_close(f); ds_printf("DS_WARTING: Don't power off your DC and don't switch the bios!\n"); EXPT_GUARD_BEGIN; b_idx = bflash_get_sector_index(dev, start_sector); if(b_idx < 0) { ds_printf("DS_ERROR: Uknown sector addr 0x%08x\n", start_sector); free(ptr); EXPT_GUARD_RETURN -1; } if(erase_mode) { ds_printf("DS_PROCESS: Erasing flash chip...\n"); if(erase_mode == F_FLASH_ERASE_ALL && (dev->size<=2048) ) { /* Don't full erase a with more than 2MB -> The others bank datas may be usefull ;) */ if (bflash_erase_all(dev) < 0) { free(ptr); EXPT_GUARD_RETURN -1; } } else if(erase_mode == F_FLASH_ERASE_SECTOR) { for (i = b_idx; i < dev->sec_count; i++) { if (dev->sectors[i] >= (len + dev->sectors[b_idx])) break; /* Don't try to erase the others banks sectors. */ if(dev->sectors[i] >= 0x200000) break; ds_printf("DS_PROCESS: Erasing sector: 0x%08x\n", dev->sectors[i]); if (bflash_erase_sector(dev, dev->sectors[i]) < 0) { free(ptr); EXPT_GUARD_RETURN -1; } } } else { ds_printf("DS_ERROR: Unsupported erase mode: %04x\n", erase_mode); free(ptr); EXPT_GUARD_RETURN -1; } } else { ds_printf("DS_WARNING: Writing to flash without erasing.\n"); } ds_printf("DS_PROCESS: Writing firmware (%d KB) into the flash chip...\n", len / 1024); if (bflash_write_data(dev, start_sector, ptr, len) < 0) { free(ptr); EXPT_GUARD_RETURN -1; } EXPT_GUARD_CATCH; ds_printf("DS_ERROR: Fatal error in reflash process.\n"); ds_printf("DS_WARNING: Maybe when you reboot your DC can't boot from the current bios.\n"); ds_printf("DS_INFO: Try to reflash again without rebooting.\n"); free(ptr); EXPT_GUARD_RETURN -1; EXPT_GUARD_END; free(ptr); ds_printf("DS_OK: Firmware written successfully\n"); return 0; } <file_sep>/lib/SDL_gui/CardStack.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" extern "C" { void UpdateActiveMouseCursor(); } GUI_CardStack::GUI_CardStack(const char *aname, int x, int y, int w, int h) : GUI_Container(aname, x, y, w, h) { visible_index = 0; wtype = WIDGET_TYPE_CARDSTACK; } GUI_CardStack::~GUI_CardStack(void) { } void GUI_CardStack::Update(int force) { if (flags & WIDGET_CHANGED) { force = 1; flags &= ~WIDGET_CHANGED; } if (force) { SDL_Rect r = area; r.x = x_offset; r.y = y_offset; Erase(&r); } if (n_widgets) { if (visible_index < 0 || visible_index >= n_widgets) visible_index = 0; widgets[visible_index]->DoUpdate(force); } } int GUI_CardStack::Event(const SDL_Event *event, int xoffset, int yoffset) { if (n_widgets) { if (visible_index < 0 || visible_index >= n_widgets) visible_index = 0; if (widgets[visible_index]->Event(event, xoffset + area.x - y_offset, yoffset + area.y - y_offset)) return 1; } return GUI_Drawable::Event(event, xoffset, yoffset); } void GUI_CardStack::Next() { if (n_widgets) { if (++visible_index >= n_widgets) visible_index = 0; MarkChanged(); } } void GUI_CardStack::Prev() { if (n_widgets) { if (--visible_index < 0) visible_index = n_widgets-1; MarkChanged(); } } void GUI_CardStack::ShowIndex(int index) { if (n_widgets) { if (index >= 0 && index < n_widgets) { visible_index = index; MarkChanged(); UpdateActiveMouseCursor(); } } } void GUI_CardStack::Show(const char *aname) { int i; for (i=0; i<n_widgets; i++) if (widgets[i]->CheckName(aname) == 0) { visible_index = i; MarkChanged(); UpdateActiveMouseCursor(); break; } } int GUI_CardStack::GetIndex() { return visible_index; } int GUI_CardStack::IsVisibleWidget(GUI_Widget *widget) { if (!widget) return 0; int i; for (i=0; i < n_widgets; i++) if (widgets[i] == widget && i == visible_index) { return 1; } return 0; } extern "C" { GUI_Widget *GUI_CardStackCreate(const char *name, int x, int y, int w, int h) { return new GUI_CardStack(name, x, y, w, h); } int GUI_CardStackCheck(GUI_Widget *widget) { // FIXME not implemented return 0; } void GUI_CardStackSetBackground(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_CardStack *) widget)->SetBackground(surface); } void GUI_CardStackSetBackgroundColor(GUI_Widget *widget, SDL_Color c) { ((GUI_CardStack *) widget)->SetBackgroundColor(c); } void GUI_CardStackNext(GUI_Widget *widget) { ((GUI_CardStack *) widget)->Next(); } void GUI_CardStackPrev(GUI_Widget *widget) { ((GUI_CardStack *) widget)->Prev(); } void GUI_CardStackShowIndex(GUI_Widget *widget, int index) { ((GUI_CardStack *) widget)->ShowIndex(index); } void GUI_CardStackShow(GUI_Widget *widget, const char *name) { ((GUI_CardStack *) widget)->Show(name); } int GUI_CardStackGetIndex(GUI_Widget *widget) { return ((GUI_CardStack *) widget)->GetIndex(); } } <file_sep>/firmware/aica/Makefile # # AICA driver for DreamShell # Copyright (C) 2009-2014 SWAT # http://www.dc-swat.ru # TARGET = ds_stream all: $(TARGET).drv CODEC = codec ASRC = $(CODEC)/mp3/real/arm/asmpoly_gcc.o \ $(CODEC)/aac/real/asm/armgcc_nosyms/sbrcov.o \ $(CODEC)/aac/real/asm/armgcc_nosyms/sbrqmfak.o \ $(CODEC)/aac/real/asm/armgcc_nosyms/sbrqmfsk.o MP3_SRC = mp3.o \ $(CODEC)/mp3/real/polyphase.o \ $(CODEC)/mp3/real/huffman.o \ $(CODEC)/mp3/real/hufftabs.o \ $(CODEC)/mp3/real/buffers.o \ $(CODEC)/mp3/mp3dec.o \ $(CODEC)/mp3/mp3tabs.o \ $(CODEC)/mp3/real/dqchan.o \ $(CODEC)/mp3/real/imdct.o \ $(CODEC)/mp3/real/stproc.o \ $(CODEC)/mp3/real/bitstream.o \ $(CODEC)/mp3/real/dequant.o \ $(CODEC)/mp3/real/scalfact.o \ $(CODEC)/mp3/real/subband.o \ $(CODEC)/mp3/real/trigtabs.o \ $(CODEC)/mp3/real/dct32.o AAC_SRC = aac.o \ $(CODEC)/aac/real/dct4.o \ $(CODEC)/aac/real/dequant.o \ $(CODEC)/aac/real/fft.o \ $(CODEC)/aac/real/imdct.o \ $(CODEC)/aac/real/pns.o \ $(CODEC)/aac/real/sbrfft.o \ $(CODEC)/aac/real/sbrfreq.o \ $(CODEC)/aac/real/sbrhfadj.o \ $(CODEC)/aac/real/sbrhfgen.o \ $(CODEC)/aac/real/sbrhuff.o \ $(CODEC)/aac/real/sbrimdct.o \ $(CODEC)/aac/real/sbrmath.o \ $(CODEC)/aac/real/sbrqmf.o \ $(CODEC)/aac/real/sbrside.o \ $(CODEC)/aac/real/stproc.o \ $(CODEC)/aac/real/tns.o \ $(CODEC)/aac/aacdec.o \ $(CODEC)/aac/aactabs.o \ $(CODEC)/aac/real/bitstream.o \ $(CODEC)/aac/real/buffers.o \ $(CODEC)/aac/real/decelmnt.o \ $(CODEC)/aac/real/filefmt.o \ $(CODEC)/aac/real/huffman.o \ $(CODEC)/aac/real/hufftabs.o \ $(CODEC)/aac/real/noiseless.o \ $(CODEC)/aac/real/sbr.o \ $(CODEC)/aac/real/sbrtabs.o \ $(CODEC)/aac/real/trigtabs.o \ $(CODEC)/aac/real/trigtabs_fltgen.o OBJ = crt0.o main.o aica.o $(MP3_SRC) $(CODEC)/filter.o #$(AAC_SRC) $(ASRC) include ../../sdk/Makefile.cfg INCS = -I./codec/mp3/pub -I./codec/aac/pub -I./codec -I$(DS_SDK)/include DC_ARM_CFLAGS += $(INCS) -DARM -DARM7DI -DUSE_DEFAULT_STDLIB #-mcpu=arm7tdmi DC_ARM_AFLAGS += $(INCS) #-mcpu=arm7tdmi $(TARGET): $(TARGET).drv $(TARGET).drv: $(TARGET).elf $(DC_ARM_OBJCOPY) -O binary $(TARGET).elf $(TARGET).drv $(TARGET).elf: $(OBJ) $(DC_ARM_CC) -Wl,-Ttext,0x00000000 -nostartfiles -nostdlib -e reset -o $(TARGET).elf $(OBJ) -lgcc %.o: %.c $(DC_ARM_CC) $(DC_ARM_CFLAGS) $(DC_ARM_INCS) -c $< -o $@ %.o: %.C $(DC_ARM_CC) $(DC_ARM_CFLAGS) $(DC_ARM_INCS) -c $< -o $@ %.o: %.s $(DC_ARM_AS) $(DC_ARM_AFLAGS) $< -o $@ %.o: %.S $(DC_ARM_AS) $(DC_ARM_AFLAGS) $< -o $@ clean: -rm -f $(TARGET).elf $(TARGET).drv $(TARGET).srec $(OBJ) install: $(TARGET).drv -rm $(DS_BUILD)/firmware/aica/$(TARGET).drv cp $(TARGET).drv $(DS_BUILD)/firmware/aica/$(TARGET).drv <file_sep>/firmware/isoldr/loader/cdda.c /** * DreamShell ISO Loader * CDDA audio playback emulation * (c)2014-2023 SWAT <http://www.dc-swat.ru> */ //#define DEBUG 1 #include <main.h> #include <mmu.h> #include <asic.h> #include <exception.h> #include <drivers/aica.h> #include <arch/irq.h> #include <arch/cache.h> #include <arch/timer.h> #include <dc/sq.h> /* static const uint8 logs[] = { 0, 15, 22, 27, 31, 35, 39, 42, 45, 47, 50, 52, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 74, 76, 78, 79, 81, 82, 84, 85, 87, 88, 90, 91, 92, 94, 95, 96, 98, 99, 100, 102, 103, 104, 105, 106, 108, 109, 110, 111, 112, 113, 114, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 138, 139, 140, 141, 142, 143, 144, 145, 146, 146, 147, 148, 149, 150, 151, 152, 152, 153, 154, 155, 156, 156, 157, 158, 159, 160, 160, 161, 162, 163, 164, 164, 165, 166, 167, 167, 168, 169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178, 178, 179, 180, 181, 181, 182, 183, 183, 184, 185, 185, 186, 187, 187, 188, 189, 189, 190, 191, 191, 192, 193, 193, 194, 195, 195, 196, 197, 197, 198, 199, 199, 200, 200, 201, 202, 202, 203, 204, 204, 205, 205, 206, 207, 207, 208, 209, 209, 210, 210, 211, 212, 212, 213, 213, 214, 215, 215, 216, 216, 217, 217, 218, 219, 219, 220, 220, 221, 221, 222, 223, 223, 224, 224, 225, 225, 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 232, 232, 233, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 239, 239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, 254, 255 }; */ #define AICA_PAN(x) ((x) == 0x80 ? (0) : ((x) < 0x80 ? (0x1f) : (0x0f))) //#define AICA_VOL(x) (0xff - logs[128 + (((x) & 0xff) / 2)]) /* AICA sample formats */ #define AICA_SM_16BIT 0 #define AICA_SM_8BIT 1 #define AICA_SM_ADPCM 3 #define AICA_SM_ADPCM_LS 4 /* WAV sample formats */ #define WAVE_FMT_PCM 0x0001 /* PCM */ #define WAVE_FMT_YAMAHA_ADPCM 0x0020 /* Yamaha ADPCM (ffmpeg) */ #define WAVE_FMT_YAMAHA_ADPCM_ITU_G723 0x0014 /* ITU G.723 Yamaha ADPCM (KallistiOS) */ #define AICA_CHANNELS_COUNT 64 /* AICA channels for CDDA audio playback by default */ #define AICA_CDDA_CH_LEFT (AICA_CHANNELS_COUNT - 2) #define AICA_CDDA_CH_RIGHT (AICA_CHANNELS_COUNT - 1) /* AICA memory end for PCM buffer */ #define AICA_MEMORY_END 0x00A00000 #define AICA_MEMORY_END_ARM 0x00200000 #define G2BUS_FIFO (*(vuint32 *)0xa05f688c) #define aica_dma_in_progress() AICA_DMA_ADST #define aica_dma_wait() do { } while(AICA_DMA_ADST) #define RAW_SECTOR_SIZE 2352 static cdda_ctx_t _cdda; static cdda_ctx_t *cdda = &_cdda; cdda_ctx_t *get_CDDA(void) { return &_cdda; } /* G2 Bus locking */ static void g2_lock(void) { cdda->g2_lock = irq_disable(); AICA_DMA_ADSUSP = 1; do { } while(G2BUS_FIFO & 0x20) ; } static void g2_unlock(void) { AICA_DMA_ADSUSP = 0; irq_restore(cdda->g2_lock); } /* When writing to the SPU RAM, this is required at least every 8 32-bit writes that you execute */ static void g2_fifo_wait() { for (uint32 i = 0; i < 0x1800; ++i) { if (!(G2BUS_FIFO & 0x11)) { break; } } } static void aica_dma_irq_hide() { if (*ASIC_IRQ11_MASK & ASIC_NRM_AICA_DMA) { if (exception_inited()) { cdda->irq_code = EXP_CODE_INT9; *ASIC_IRQ9_MASK |= ASIC_NRM_AICA_DMA; } else { cdda->irq_code = EXP_CODE_INT11; } } else { if (exception_inited()) { cdda->irq_code = EXP_CODE_INT11; } else { cdda->irq_code = EXP_CODE_INT9; } } } static void aica_dma_irq_restore() { if (cdda->irq_code == 0) { return; } else if(exception_inited() && cdda->irq_code == EXP_CODE_INT9) { ASIC_IRQ_STATUS[ASIC_MASK_NRM_INT] = ASIC_NRM_AICA_DMA; *ASIC_IRQ9_MASK &= ~ASIC_NRM_AICA_DMA; } cdda->irq_code = 0; } static void aica_dma_transfer(uint8 *data, uint32 dest, uint32 size) { DBGFF("0x%08lx %ld\n", data, size); uint32 addr = (uint32)data; dcache_purge_range(addr, size); addr = addr & 0x0FFFFFFF; AICA_DMA_G2APRO = 0x4659007F; // Protection code AICA_DMA_ADEN = 0; // Disable wave DMA AICA_DMA_ADDIR = 0; // To wave memory AICA_DMA_ADTRG = 0x00000004; // Initiate by CPU, suspend enabled AICA_DMA_ADSTAR = addr; // System memory address AICA_DMA_ADSTAG = dest; // Wave memory address AICA_DMA_ADLEN = size|0x80000000; // Data size, disable after DMA end AICA_DMA_ADEN = 1; // Enable wave DMA AICA_DMA_ADST = 1; // Start wave DMA } static void aica_sq_transfer(uint8 *data, uint32 dest, uint32 size) { uint32 *d = (uint32 *)(void *)(0xe0000000 | (dest & 0x03ffffe0)); uint32 *s = (uint32 *)data; /* Set store queue memory area as desired */ QACR0 = ((dest >> 26) << 2) & 0x1c; QACR1 = ((dest >> 26) << 2) & 0x1c; /* fill/write queues as many times necessary */ size >>= 5; g2_fifo_wait(); while(size--) { /* Prefetch 32 bytes for next loop */ dcache_pref_block(s + 8); d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; d[3] = s[3]; d[4] = s[4]; d[5] = s[5]; d[6] = s[6]; d[7] = s[7]; /* Write back memory */ dcache_pref_block(d); d += 8; s += 8; } /* Wait for both store queues to complete */ d = (uint32 *)0xe0000000; d[0] = d[8] = 0; } static void aica_transfer(uint8 *data, uint32 dest, uint32 size) { if (cdda->dma) { aica_dma_irq_hide(); aica_dma_transfer(data, dest, size); } else { aica_sq_transfer(data, dest, size); } } static int aica_transfer_in_progress() { if (cdda->dma) { return aica_dma_in_progress(); } return 0; } static void aica_transfer_wait() { if (cdda->dma) { aica_dma_wait(); } } static void aica_transfer_stop() { if (cdda->dma) { AICA_DMA_ADEN = 0; } } static void setup_pcm_buffer() { /* * SH4 timer counter value for polling playback position * * Some values for PCM 16 bit 44100 Hz: * * 32 KB = 72374 / chn * 24 KB = 54278 / chn * 16 KB = 36176 / chn */ cdda->end_tm = 72374 / cdda->chn; size_t old_size = cdda->size; // cdda->size = (cdda->bitsize << 10) * cdda->chn; switch(cdda->bitsize) { case 4: cdda->size = 0x4000; cdda->end_tm *= 2; /* 4 bits decoded to 16 bits */ cdda->end_tm += 10; /* Fixup timer value for ADPCM */ break; case 8: cdda->size = 0x4000; break; case 16: default: cdda->size = 0x8000; if(exception_inited()) { cdda->size = 0x4000; cdda->end_tm = 36176 / cdda->chn; #ifdef LOG if (malloc_heap_pos() < APP_ADDR) { // Need some memory for logging in some cases cdda->size >>= 1; cdda->end_tm >>= 1; } #endif } break; } if (cdda->alloc_buff && old_size != cdda->size) { free(cdda->alloc_buff); cdda->alloc_buff = NULL; } if (cdda->alloc_buff == NULL) { cdda->alloc_buff = malloc(cdda->size + 32); } if (cdda->alloc_buff == NULL) { LOGFF("Failed malloc"); return; } cdda->buff[0] = (uint8 *)ALIGN32_ADDR((uint32)cdda->alloc_buff); cdda->buff[1] = cdda->buff[0] + (cdda->size >> 1); /* Setup buffer at end of sound memory */ cdda->aica_left[0] = AICA_MEMORY_END - cdda->size; cdda->aica_left[1] = cdda->aica_left[0] + (cdda->size >> 2); cdda->aica_right[0] = AICA_MEMORY_END - (cdda->size >> 1); cdda->aica_right[1] = cdda->aica_right[0] + (cdda->size >> 2); /* Setup end position for sound buffer */ if(cdda->aica_format == AICA_SM_ADPCM) { cdda->end_pos = cdda->size - 1; } else { cdda->end_pos = ((cdda->size / cdda->chn) / (cdda->bitsize >> 3)) - (cdda->bitsize >> 3); } LOGFF("0x%08lx 0x%08lx %d\n", (uint32)cdda->buff[0], (uint32)cdda->aica_left[0], cdda->size); } static void aica_set_volume(int volume) { uint32 val; cdda->volume = volume; g2_fifo_wait(); g2_lock(); /* Get original CDDA volume (doesn't work) */ // SNDREG32(0x2040) & 0xff00; // Left // SNDREG32(0x2044) & 0xff00; // Right val = 0x24 | (volume << 8); //(AICA_VOL(vol) << 8); CHNREG32(cdda->left_channel, 40) = val; if(cdda->chn > 1) { // val = 0x24 | (right_chn << 8); //(AICA_VOL(right_chn) << 8); CHNREG32(cdda->right_channel, 40) = val; CHNREG32(cdda->left_channel, 36) = AICA_PAN(0) | (0xf << 8); CHNREG32(cdda->right_channel, 36) = AICA_PAN(255) | (0xf << 8); } else { CHNREG32(cdda->left_channel, 36) = AICA_PAN(128) | (0xf << 8); } g2_unlock(); } static void aica_stop_cdda(void) { uint32 val; DBGFF(NULL); g2_fifo_wait(); g2_lock(); val = CHNREG32(cdda->left_channel, 0); CHNREG32(cdda->left_channel, 0) = (val & ~0x4000) | 0x8000; if(cdda->chn > 1) { val = CHNREG32(cdda->right_channel, 0); CHNREG32(cdda->right_channel, 0) = (val & ~0x4000) | 0x8000; } g2_unlock(); timer_stop(cdda->timer); timer_clear(cdda->timer); } static void aica_stop_clean_cdda() { DBGFF(NULL); aica_stop_cdda(); #ifdef _FS_ASYNC while(cdda->stat == CDDA_STAT_WAIT) { if (poll(cdda->fd) < 0) { break; } } #endif if(aica_transfer_in_progress()) { aica_transfer_stop(); aica_transfer_wait(); } cdda->stat = CDDA_STAT_IDLE; } static void aica_setup_cdda(int clean) { int freq_hi = 7; uint32 val, freq_lo, freq_base = 5644800; const uint32 smp_ptr = AICA_MEMORY_END_ARM - cdda->size; const int smp_size = cdda->size / cdda->chn; /* Need to convert frequency to floating point format (freq_hi is exponent, freq_lo is mantissa) Formula is freq = 44100*2^freq_hi*(1+freq_lo/1024) */ while (cdda->freq < freq_base && freq_hi > -8) { freq_base >>= 1; --freq_hi; } freq_lo = (cdda->freq << 10) / freq_base; freq_base = (freq_hi << 11) | (freq_lo & 1023); /* Stop AICA channels */ aica_stop_cdda(); if(clean) { LOGFF("0x%08lx 0x%08lx %d %d %d %d\n", smp_ptr, (smp_ptr + smp_size), smp_size, cdda->freq, cdda->aica_format, cdda->end_tm); cdda->restore_count = 0; cdda->cur_buff = 0; } timer_prime_cdda(cdda->timer, cdda->end_tm, 0); /* Setup AICA channels */ g2_fifo_wait(); g2_lock(); CHNREG32(cdda->left_channel, 8) = 0; CHNREG32(cdda->left_channel, 12) = cdda->end_pos & 0xffff; CHNREG32(cdda->left_channel, 24) = freq_base; if(cdda->chn > 1) { CHNREG32(cdda->right_channel, 8) = 0; CHNREG32(cdda->right_channel, 12) = cdda->end_pos & 0xffff; CHNREG32(cdda->right_channel, 24) = freq_base; } cdda->check_freq = freq_base; g2_unlock(); aica_set_volume(clean ? 255 : 0); g2_fifo_wait(); g2_lock(); CHNREG32(cdda->left_channel, 16) = 0x1f; CHNREG32(cdda->left_channel, 4) = smp_ptr & 0xffff; if(cdda->chn > 1) { CHNREG32(cdda->right_channel, 16) = 0x1f; CHNREG32(cdda->right_channel, 4) = (smp_ptr + smp_size) & 0xffff; } /* Channels check value (for both the same) */ cdda->check_status = 0x4000 | (cdda->aica_format << 7) | 0x200 | (smp_ptr >> 16); /* start play | format | use loop */ val = 0xc000 | (cdda->aica_format << 7) | 0x200; CHNREG32(cdda->left_channel, 0) = val | (smp_ptr >> 16); if(cdda->chn > 1) { CHNREG32(cdda->right_channel, 0) = val | ((smp_ptr + smp_size) >> 16); } g2_fifo_wait(); /* Start SH4 timer */ timer_start(cdda->timer); g2_unlock(); } static uint32 aica_change_cdda_channel(uint32 channel, uint32 exclude) { uint32 val = 0, try_count = 1; g2_lock(); do { if (++channel >= AICA_CHANNELS_COUNT) { channel = 0; } if (channel == cdda->left_channel || channel == cdda->right_channel || channel == exclude ) { continue; } if (++try_count >= AICA_CHANNELS_COUNT) { break; } val = CHNREG32(channel, 0); } while ((val & 0x4000) != 0); g2_unlock(); #ifdef LOG if (try_count >= AICA_CHANNELS_COUNT) { LOGF("CDDA: No free channel\n"); } #endif return channel; } static void aica_check_cdda(void) { const uint32 check_vol = 0x24 | (cdda->volume << 8); uint32 invalid_level = 0; uint32 val; // g2_fifo_wait(); g2_lock(); if(cdda->chn > 1) { val = CHNREG32(cdda->left_channel, 36) & 0xffff; if(val != (AICA_PAN(0) | (0xf << 8))) { invalid_level |= 0x11; // LOGF("CDDA: L PAN %04lx != %04lx\n", val, (AICA_PAN(0) | (0xf << 8))); } val = CHNREG32(cdda->right_channel, 36) & 0xffff; if(val != (AICA_PAN(255) | (0xf << 8))) { invalid_level |= 0x12; // LOGF("CDDA: R PAN %04lx != %04lx\n", val, (AICA_PAN(255) | (0xf << 8))); } val = CHNREG32(cdda->right_channel, 40) & 0xffff; if(val != check_vol) { invalid_level |= 0x22; // LOGF("CDDA: R VOL %04lx != %04lx\n", val, check_vol); } val = CHNREG32(cdda->right_channel, 24) & 0xffff; if(val != cdda->check_freq) { invalid_level |= 0x42; // LOGF("CDDA: R FRQ %04lx != %04lx\n", val, cdda->check_freq); } val = CHNREG32(cdda->left_channel, 12) & 0xffff; if (val != (cdda->end_pos & 0xffff)) { invalid_level |= 0x42; // LOGF("CDDA: R POS %04lx != %04lx\n", val, cdda->end_pos & 0xffff); } val = CHNREG32(cdda->right_channel, 0) & 0xffff; if (val != cdda->check_status) { invalid_level |= 0x82; // LOGF("CDDA: R CON %04lx != %04lx\n", val, cdda->check_status); } } else { val = CHNREG32(cdda->left_channel, 36) & 0xffff; if(val != (AICA_PAN(128) | (0xf << 8))) { invalid_level |= 0x11; } } val = CHNREG32(cdda->left_channel, 40) & 0xffff; if(val != check_vol) { invalid_level |= 0x21; // LOGF("CDDA: L VOL %04lx != %04lx\n", val, check_vol); } val = CHNREG32(cdda->left_channel, 24) & 0xffff; if(val != cdda->check_freq) { invalid_level |= 0x41; // LOGF("CDDA: L FRQ %04lx != %04lx\n", val, cdda->check_freq); } val = CHNREG32(cdda->left_channel, 12) & 0xffff; if (val != (cdda->end_pos & 0xffff)) { invalid_level |= 0x41; // LOGF("CDDA: L POS %04lx != %04lx\n", val, cdda->end_pos & 0xffff); } val = CHNREG32(cdda->left_channel, 0) & 0xffff; if (val != cdda->check_status) { invalid_level |= 0x81; // LOGF("CDDA: L CON %04lx != %04lx\n", val, cdda->check_status); } g2_unlock(); if ((invalid_level >> 4) == 0) { return; } LOGF("CDDA: Invalid 0x%02lx\n", invalid_level); if (cdda->restore_count++ < 10) { if ((invalid_level >> 4) <= 3) { aica_set_volume(0); return; } if ((invalid_level >> 4) < 8) { aica_setup_cdda(0); return; } } aica_stop_cdda(); if (cdda->restore_count >= 10 || (invalid_level >> 4) == 8) { uint32 left_channel = cdda->left_channel; if (invalid_level & 0x01) { left_channel = aica_change_cdda_channel(cdda->left_channel, left_channel); } if (invalid_level & 0x02) { cdda->right_channel = aica_change_cdda_channel(cdda->right_channel, left_channel); LOGF("CDDA: Right channel: %d\n", cdda->right_channel); } if (left_channel != cdda->left_channel) { cdda->left_channel = left_channel; LOGF("CDDA: Left channel: %d\n", cdda->left_channel); } cdda->restore_count = 0; } aica_setup_cdda(0); } #if 0 // For debugging /* Get channel position */ static uint32 aica_get_pos(void) { uint32 p; g2_fifo_wait(); /* Observe channel ch */ g2_lock(); SNDREG32(0x280c) = (SNDREG32(0x280c) & 0xffff00ff) | (cdda->left_channel << 8); g2_unlock(); g2_fifo_wait(); /* Update position counters */ g2_lock(); p = SNDREG32(0x2814) & 0xffff; g2_unlock(); return p; } static void aica_init(void) { g2_fifo_wait(); g2_lock(); SNDREG32(0x2800) = 0x0000; g2_fifo_wait(); for(int i = 0; i < 64; ++i) { if(!(i % 4)) g2_fifo_wait(); CHNREG32(i, 0) = 0x8000; CHNREG32(i, 20) = 0x1f; } g2_fifo_wait(); SNDREG32(0x2800) = 0x000f; *((vuint32*)SPU_RAM_BASE) = 0xeafffff8; g2_fifo_wait(); SNDREG32(0x2c00) = SNDREG32(0x2c00) & ~1; g2_unlock(); } static void aica_dma_init(void) { uint32 main_addr = ((uint32)cdda->buff[0]) & 0x0FFFFFFF; uint32 sound_addr = AICA_MEMORY_END - cdda->size; AICA_DMA_G2APRO = 0x4659007F; // Protection code AICA_DMA_ADEN = 0; // Disable wave DMA AICA_DMA_ADDIR = 0; // To wave memory AICA_DMA_ADTRG = 0; // Initiate by CPU AICA_DMA_ADSTAR = main_addr; // System memory address AICA_DMA_ADSTAG = sound_addr; // Wave memory address AICA_DMA_ADLEN = cdda->size; // Data size AICA_DMA_ADEN = 1; // Enable wave DMA } #endif static int aica_suitable_pos() { uint32 tm = timer_count(cdda->timer); uint32 ta = cdda->end_tm >> 1; // uint32 pos = aica_get_pos(); // LOGF("CDDA: POS %ld %ld\n", pos, tm); // if((cdda->cur_buff == 0 && pos >= (cdda->end_pos >> 1)) || // (cdda->cur_buff == 1 && pos < (cdda->end_pos >> 1))) { if((cdda->cur_buff == 0 && tm < ta) || (cdda->cur_buff == 1 && tm > ta)) { return 1; } return 0; } static void aica_pcm_split(uint8 *src, uint8 *dst, uint32 size) { DBGFF("0x%08lx 0x%08lx %ld\n", src, dst, size); if(cdda->chn > 1/* && cdda->wav_format != WAVE_FMT_YAMAHA_ADPCM_ITU_G723*/) { uint32 count = size >> 1; switch(cdda->bitsize) { case 4: adpcm_split(src, dst, dst + count, size); break; case 8: pcm8_split(src, dst, dst + count, size); break; case 16: pcm16_split((int16 *)src, (int16 *)dst, (int16 *)(dst + count), size); break; default: break; } } else { /* TODO optimize it, maybe just switch the buffer? */ memcpy(dst, src, size); } } static void switch_cdda_track(uint8 track) { gd_state_t *GDS = get_GDS(); if(GDS->cdda_track != track) { cdda->filename[cdda->fn_len - 6] = (track / 10) + '0'; cdda->filename[cdda->fn_len - 5] = (track % 10) + '0'; cdda->filename[cdda->fn_len - 3] = 'r'; cdda->filename[cdda->fn_len - 1] = 'w'; cdda->filename[cdda->fn_len - 0] = '\0'; LOGF("Opening track%02d: %s\n", track, cdda->filename); if(cdda->fd > FILEHND_INVALID) { close(cdda->fd); } cdda->fd = open(cdda->filename, O_RDONLY); if(cdda->fd < 0) { cdda->filename[cdda->fn_len - 3] = 'w'; cdda->filename[cdda->fn_len - 1] = 'v'; LOGF("Not found, opening: %s\n", cdda->filename); cdda->fd = open(cdda->filename, O_RDONLY); if(cdda->fd < 0) { cdda->filename[cdda->fn_len - 3] = 'r'; cdda->filename[cdda->fn_len - 1] = 'w'; cdda->filename[cdda->fn_len - 0] = '.'; cdda->filename[cdda->fn_len + 1] = 'w'; cdda->filename[cdda->fn_len + 2] = 'a'; cdda->filename[cdda->fn_len + 3] = 'v'; LOGF("Not found, opening: %s\n", cdda->filename); cdda->fd = open(cdda->filename, O_RDONLY); #ifdef LOG if(cdda->fd < 0) { LOGF("CDDA track not found\n"); } #endif } } } } static uint32 sector_align(uint32 offset) { #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_SD) if (offset % 512) { offset = ((offset / 512) + 1) * 512; } #elif defined(DEV_TYPE_GD) if (offset % 2048) { offset = ((offset / 2048) + 1) * 2048; } #endif return offset; } #ifdef HAVE_EXPT /* static void* tmu_handle_exception(register_stack *stack, void *current_vector) { uint32 code = *REG_EXPEVT; (void)stack; if ((code == EXC_CODE_TMU2 && cdda->timer == TMU2) || (code == EXC_CODE_TMU1 && cdda->timer == TMU1) ) { timer_clear(cdda->timer); } return current_vector; } */ void *aica_dma_handler(void *passer, register_stack *stack, void *current_vector) { (void)passer; (void)stack; if (cdda->irq_code == *REG_INTEVT) { aica_dma_irq_restore(); CDDA_MainLoop(); uint32 st = ASIC_IRQ_STATUS[ASIC_MASK_NRM_INT] & ~ASIC_NRM_AICA_DMA; if (cdda->irq_code == EXP_CODE_INT9) { st = ((*ASIC_IRQ9_MASK) & st); } else { st = ((*ASIC_IRQ11_MASK) & st); } if (st == 0) { return my_exception_finish; } } return current_vector; } void *aica_vsync_handler(void *passer, register_stack *stack, void *current_vector) { (void)passer; (void)stack; CDDA_MainLoop(); return current_vector; } # ifndef NO_ASIC_LT static asic_handler_f old_vsync_handler; static void *vsync_handler(void *passer, register_stack *stack, void *current_vector) { if(old_vsync_handler) { current_vector = old_vsync_handler(passer, stack, current_vector); } return aica_vsync_handler(passer, stack, current_vector); } static asic_handler_f old_dma_handler; static void *dma_handler(void *passer, register_stack *stack, void *current_vector) { if(old_dma_handler) { current_vector = old_dma_handler(passer, stack, current_vector); } return aica_dma_handler(passer, stack, current_vector); } # endif #endif int CDDA_Init() { unlock_cdda(); memset(cdda, 0, sizeof(cdda_ctx_t)); if(IsoInfo->image_type == ISOFS_IMAGE_TYPE_CDI) { cdda->fd = iso_fd; } else { cdda->filename = relative_filename("track04.raw"); cdda->fn_len = strlen(cdda->filename); cdda->fd = FILEHND_INVALID; } cdda->left_channel = AICA_CDDA_CH_LEFT; cdda->right_channel = AICA_CDDA_CH_RIGHT; /* AICA DMA */ if(IsoInfo->emu_cdda <= CDDA_MODE_DMA_TMU1) { cdda->dma = 1; } else { cdda->dma = 0; } /* SH4 timer */ if (IsoInfo->emu_cdda == CDDA_MODE_DMA_TMU1 || IsoInfo->emu_cdda == CDDA_MODE_SQ_TMU1) { cdda->timer = TMU1; } else { cdda->timer = TMU2; } #if 0 /* It's not need for games (they do it), only for local test */ aica_init(); aica_dma_init(); #endif #if defined(HAVE_EXPT) # if !defined(NO_ASIC_LT) asic_lookup_table_entry vsync_entry, dma_entry; memset(&vsync_entry, 0, sizeof(vsync_entry)); memset(&dma_entry, 0, sizeof(dma_entry)); dma_entry.irq = EXP_CODE_ALL; dma_entry.mask[ASIC_MASK_NRM_INT] = ASIC_NRM_AICA_DMA; dma_entry.handler = dma_handler; asic_add_handler(&dma_entry, NULL, 0); vsync_entry.irq = EXP_CODE_ALL; vsync_entry.mask[ASIC_MASK_NRM_INT] = ASIC_NRM_VSYNC; vsync_entry.handler = vsync_handler; asic_add_handler(&vsync_entry, &old_vsync_handler, 0); # endif /* exception_table_entry tmu_entry; tmu_entry.type = EXP_TYPE_GEN; tmu_entry.code = (cdda->timer == TMU2 ? EXC_CODE_TMU2 : EXC_CODE_TMU1); tmu_entry.handler = tmu_handle_exception; exception_add_handler(&tmu_entry, NULL); */ #endif return 0; } static void play_track(uint32 track) { if(IsoInfo->image_type == ISOFS_IMAGE_TYPE_CDI) { if(IsoInfo->cdda_offset[track - 3] > 0) { cdda->offset = IsoInfo->cdda_offset[track - 3]; } else { return; } } else { switch_cdda_track(track); if(cdda->fd < 0) { return; } cdda->offset = 0; } uint32 len = 0; #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) fs_enable_dma(FS_DMA_DISABLED); #endif /* Check file magic */ lseek(cdda->fd, cdda->offset + 8, SEEK_SET); read(cdda->fd, &len, 4); if(!memcmp(&len, "WAVE", 4)) { /* Read WAV header info */ lseek(cdda->fd, cdda->offset + 0x14, SEEK_SET); read(cdda->fd, &cdda->wav_format, 2); read(cdda->fd, &cdda->chn, 2); read(cdda->fd, &cdda->freq, 4); lseek(cdda->fd, cdda->offset + 0x22, SEEK_SET); read(cdda->fd, &cdda->bitsize, 2); read(cdda->fd, &len, 4); if(len != 0x61746164) { cdda->offset += 0x32; lseek(cdda->fd, cdda->offset, SEEK_SET); read(cdda->fd, &len, 4); if(len != 0x61746164) { cdda->offset += 0x14; lseek(cdda->fd, cdda->offset, SEEK_SET); read(cdda->fd, &len, 4); } } else { cdda->offset += 0x2C; } read(cdda->fd, &len, 4); switch(cdda->wav_format) { case WAVE_FMT_PCM: cdda->aica_format = cdda->bitsize == 8 ? AICA_SM_8BIT : AICA_SM_16BIT; break; case WAVE_FMT_YAMAHA_ADPCM: case WAVE_FMT_YAMAHA_ADPCM_ITU_G723: cdda->aica_format = AICA_SM_ADPCM; break; default: cdda->aica_format = AICA_SM_16BIT; break; } } else { cdda->freq = 44100; cdda->chn = 2; cdda->bitsize = 16; cdda->aica_format = AICA_SM_16BIT; cdda->wav_format = WAVE_FMT_PCM; } /* Make alignment by sector */ if(cdda->offset > 0) { cdda->offset = sector_align(cdda->offset); } lseek(cdda->fd, cdda->offset, SEEK_SET); cdda->cur_offset = 0; cdda->lba = TOC_LBA(IsoInfo->toc.entry[track - 1]); if(IsoInfo->image_type == ISOFS_IMAGE_TYPE_CDI) { if(IsoInfo->toc.entry[track] != (uint32)-1) { cdda->track_size = (TOC_LBA(IsoInfo->toc.entry[track]) - cdda->lba - 2) * RAW_SECTOR_SIZE; } else { cdda->track_size = (((total(cdda->fd) - cdda->offset) / RAW_SECTOR_SIZE) - cdda->lba - 2) * RAW_SECTOR_SIZE; } } else { cdda->track_size = total(cdda->fd) - cdda->offset - (cdda->size >> 1); } LOGFF("Track #%lu, %s %luHZ %d bits/sample, %lu bytes total," " format %d, LBA %ld\n", track, cdda->chn == 1 ? "mono" : "stereo", cdda->freq, cdda->bitsize, cdda->track_size, cdda->wav_format, cdda->lba); #ifdef DEV_TYPE_SD if(cdda->bitsize == 4) { fs_enable_dma(cdda->size >> 13); } else { fs_enable_dma(cdda->size >> 12); } #else if(IsoInfo->emu_cdda <= CDDA_MODE_DMA_TMU1) { fs_enable_dma(FS_DMA_HIDDEN); } #endif cdda->stat = CDDA_STAT_FILL; gd_state_t *GDS = get_GDS(); GDS->cdda_track = track; GDS->drv_stat = CD_STATUS_PLAYING; GDS->cdda_stat = SCD_AUDIO_STATUS_PLAYING; setup_pcm_buffer(); aica_setup_cdda(1); } int CDDA_Play(uint32 first, uint32 last, uint32 loop) { gd_state_t *GDS = get_GDS(); if(!IsoInfo->emu_cdda) { GDS->cdda_track = first; GDS->drv_stat = CD_STATUS_PLAYING; GDS->cdda_stat = SCD_AUDIO_STATUS_PLAYING; return COMPLETED; } if(cdda->stat || (first != cdda->first_track && cdda->fd > FILEHND_INVALID)) { CDDA_Stop(); } cdda->first_track = first; cdda->first_lba = 0; cdda->last_track = last; cdda->last_lba = 0; cdda->loop = loop; play_track(first); return COMPLETED; } int CDDA_Play2(uint32 first_lba, uint32 last_lba, uint32 loop) { uint8 track = 0; for(int i = 3; i < 99; ++i) { if(IsoInfo->toc.entry[i] == (uint32)-1) { break; } else if(TOC_LBA(IsoInfo->toc.entry[i]) == TOC_LBA(first_lba)) { track = i + 1; break; } else if(TOC_LBA(IsoInfo->toc.entry[i]) > TOC_LBA(first_lba)) { track = i; break; } } if (track == 0) { return FAILED; } CDDA_Play(track, track, loop); if(cdda->fd > FILEHND_INVALID) { cdda->first_lba = TOC_LBA(first_lba); cdda->last_lba = TOC_LBA(last_lba); gd_state_t *GDS = get_GDS(); GDS->lba = first_lba; uint32 offset = cdda->offset + ((first_lba - cdda->lba) * RAW_SECTOR_SIZE); lseek(cdda->fd, sector_align(offset), SEEK_SET); } return COMPLETED; } int CDDA_Seek(uint32 offset) { gd_state_t *GDS = get_GDS(); if(IsoInfo->emu_cdda && cdda->fd > FILEHND_INVALID) { aica_stop_clean_cdda(); uint32 value = cdda->offset + ((offset - cdda->lba) * RAW_SECTOR_SIZE); lseek(cdda->fd, sector_align(value), SEEK_SET); cdda->stat = CDDA_STAT_FILL; aica_setup_cdda(1); } GDS->lba = offset; return COMPLETED; } int CDDA_Pause(void) { gd_state_t *GDS = get_GDS(); if(cdda->stat) { aica_stop_clean_cdda(); cdda->cur_offset = tell(cdda->fd) - cdda->offset; } GDS->drv_stat = CD_STATUS_PAUSED; GDS->cdda_stat = SCD_AUDIO_STATUS_PAUSED; return COMPLETED; } int CDDA_Release() { gd_state_t *GDS = get_GDS(); if(IsoInfo->emu_cdda && cdda->fd > FILEHND_INVALID) { lseek(cdda->fd, cdda->cur_offset + cdda->offset, SEEK_SET); cdda->stat = CDDA_STAT_FILL; aica_setup_cdda(1); #ifdef _FS_ASYNC # ifdef DEV_TYPE_SD if(cdda->bitsize == 4) fs_enable_dma(cdda->size >> 13); else fs_enable_dma(cdda->size >> 12); # else fs_enable_dma(FS_DMA_HIDDEN); # endif #endif /* _FS_ASYNC */ } GDS->drv_stat = CD_STATUS_PLAYING; GDS->cdda_stat = SCD_AUDIO_STATUS_PLAYING; return COMPLETED; } int CDDA_Stop(void) { do {} while(lock_cdda()); LOGFF(NULL); gd_state_t *GDS = get_GDS(); if(cdda->stat) { aica_stop_clean_cdda(); } if(cdda->fd > FILEHND_INVALID && IsoInfo->image_type != ISOFS_IMAGE_TYPE_CDI) { close(cdda->fd); cdda->fd = FILEHND_INVALID; } if(cdda->alloc_buff) { free(cdda->alloc_buff); cdda->alloc_buff = NULL; } GDS->cdda_track = 0; GDS->drv_stat = CD_STATUS_STANDBY; GDS->cdda_stat = SCD_AUDIO_STATUS_NO_INFO; unlock_cdda(); return COMPLETED; } static void end_playback() { LOGFF(NULL); aica_stop_clean_cdda(); gd_state_t *GDS = get_GDS(); GDS->drv_stat = CD_STATUS_PAUSED; GDS->cdda_stat = SCD_AUDIO_STATUS_ENDED; } static void play_next_track() { if (cdda->stat != CDDA_STAT_END) { end_playback(); } if (exception_inside_int() && IsoInfo->exec.type == BIN_TYPE_WINCE) { cdda->stat = CDDA_STAT_END; return; } LOGFF(NULL); if(cdda->first_track < cdda->last_track) { gd_state_t *GDS = get_GDS(); uint32 track = GDS->cdda_track; if(GDS->cdda_track < cdda->last_track) { track++; } else { if(cdda->loop == 0) { return; } else if(cdda->loop < 0xf) { cdda->loop--; } track = cdda->first_track; } play_track(track); } else if(cdda->loop != 0) { if (cdda->loop < 0xf) { cdda->loop--; } if(cdda->first_lba == 0) { CDDA_Play(cdda->first_track, cdda->last_track, cdda->loop); } else { CDDA_Play2(cdda->first_lba, cdda->last_lba, cdda->loop); } } } #ifdef _FS_ASYNC static void read_callback(size_t size) { DBGF("CDDA: FILL END %d\n", size); if(cdda->stat > CDDA_STAT_IDLE) { if(size == (size_t)-1) { lseek(cdda->fd, cdda->cur_offset + cdda->offset, SEEK_SET); cdda->stat = CDDA_STAT_FILL; } else if(size < cdda->size >> 1) { cdda->stat = CDDA_STAT_FILL; } else { cdda->stat = CDDA_STAT_PREP; } } } #endif static void fill_pcm_buff() { if(cdda->volume && cdda->cur_offset) { aica_set_volume(0); } cdda->cur_offset = tell(cdda->fd) - cdda->offset; if(cdda->last_lba > 0) { uint32 offset = (cdda->cur_offset / RAW_SECTOR_SIZE) + cdda->lba; if (offset > cdda->last_lba) { play_next_track(); return; } } if(cdda->cur_offset >= cdda->track_size) { play_next_track(); return; } DBGF("CDDA: FILL %ld %ld\n", cdda->cur_offset, cdda->track_size - cdda->cur_offset); /* Reading data for all channels to work buffer. Using physical address to prevent cache invalidation becuase it's already done at PCM splitting. */ uint8 *buff; if (cdda->cur_offset) { buff = (uint8 *)PHYS_ADDR((uint32)cdda->buff[PCM_TMP_BUFF]); } else { buff = cdda->buff[PCM_TMP_BUFF]; } #ifdef _FS_ASYNC cdda->stat = CDDA_STAT_WAIT; int rc = read_async(cdda->fd, buff, cdda->size >> 1, read_callback); #else int rc = read(cdda->fd, buff, cdda->size >> 1); cdda->stat = CDDA_STAT_PREP; #endif if(rc < 0) { LOGFF("Unable to read data\n"); end_playback(); } } void CDDA_MainLoop(void) { if(lock_cdda()) { return; } if(cdda->stat == CDDA_STAT_IDLE) { unlock_cdda(); return; } DBGFF("%d %d\n", IsoInfo->emu_cdda, cdda->stat); if(cdda->stat == CDDA_STAT_END && !exception_inside_int()) { play_next_track(); } #ifdef _FS_ASYNC if(cdda->stat == CDDA_STAT_WAIT) { /* Polling async data transfer */ #if defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD) if(!exception_inited() || !pre_read_xfer_busy()) #endif { if(poll(cdda->fd) < 0) { lseek(cdda->fd, cdda->cur_offset + cdda->offset, SEEK_SET); cdda->stat = CDDA_STAT_FILL; } } unlock_cdda(); return; } #endif /* Reading data for left or all channels */ if(cdda->stat == CDDA_STAT_FILL) { aica_check_cdda(); fill_pcm_buff(); /* Update LBA for SCD command */ gd_state_t *GDS = get_GDS(); GDS->lba = cdda->lba + (cdda->cur_offset / RAW_SECTOR_SIZE); unlock_cdda(); return; } /* Split PCM data to left and right channels */ if(cdda->stat == CDDA_STAT_PREP && !aica_transfer_in_progress()) { aica_dma_irq_restore(); aica_pcm_split(cdda->buff[PCM_TMP_BUFF], cdda->buff[PCM_DMA_BUFF], cdda->size >> 1); cdda->stat = CDDA_STAT_POS; } /* Wait suitable channels position */ if(cdda->stat == CDDA_STAT_POS && aica_suitable_pos()) { cdda->stat = CDDA_STAT_SNDL; } /* Send data to AICA */ if(cdda->stat == CDDA_STAT_SNDL && !aica_transfer_in_progress()) { if(cdda->chn > 1) { aica_transfer(cdda->buff[PCM_DMA_BUFF], cdda->aica_left[cdda->cur_buff], cdda->size >> 2); cdda->stat = CDDA_STAT_SNDR; } else { uint32 dest = cdda->cur_buff ? cdda->aica_right[0] : cdda->aica_left[0]; aica_transfer(cdda->buff[PCM_DMA_BUFF], dest, cdda->size >> 1); cdda->cur_buff = !cdda->cur_buff; cdda->stat = CDDA_STAT_FILL; } } /* If transfer of left channel is done, start for right channel */ else if(cdda->stat == CDDA_STAT_SNDR && !aica_transfer_in_progress()) { uint32 size = cdda->size >> 2; aica_transfer(cdda->buff[PCM_DMA_BUFF] + size, cdda->aica_right[cdda->cur_buff], size); cdda->cur_buff = !cdda->cur_buff; cdda->stat = CDDA_STAT_FILL; } unlock_cdda(); } #ifdef DEBUG void CDDA_Test() { /* Internal CDDA test */ // uint32 next = loader_addr; int i = 0, track = 4; while(1) { i = 0; // next = next * 1103515245 + 12345; // track = (((uint)(next / 65536) % 32768) % 32) + 4; track++; CDDA_Play(track, track, 15); while(i++ < 400000) { CDDA_MainLoop(); timer_spin_sleep(15); } } } #endif <file_sep>/modules/vkb/module.c /* DreamShell ##version## module.c - virtual keyboard module Copyright (C)2004 - 2014 SWAT */ #include "ds.h" DEFAULT_MODULE_HEADER(vkb); int lib_open(klibrary_t *lib) { if(VirtKeyboardInit() < 0) { ds_printf("DS_ERROR: Can't initialize virtual keyboard.\n"); } return nmmgr_handler_add(&ds_vkb_hnd.nmmgr); } int lib_close(klibrary_t *lib) { VirtKeyboardShutdown(); return nmmgr_handler_remove(&ds_vkb_hnd.nmmgr); } <file_sep>/modules/mp3/libmp3/Makefile # KallistiOS ##version## # # libmp3 Makefile TARGET = libmp3_mpg123.a OBJS = LIB_OBJS = build/*.o #SUBDIRS = xingmp3 libmp3 LOCAL_CLEAN = build/*.o build/*.a SUBDIRS = mpg123 libmp3 #KOS_CFLAGS += -DNOANALYSIS include ../../../sdk/Makefile.library <file_sep>/lib/libparallax/include/list.h /* Parallax for KallistiOS ##version## list.h (c)2002 <NAME> */ #ifndef __PARALLAX_LIST #define __PARALLAX_LIST #include <sys/cdefs.h> __BEGIN_DECLS /** \file List specification. These are more wrappers for PVR stuff to help make porting easier. This is really pretty DC specific, but it will help a porting layer to sort out what's going on anyway, and avoid having to #define more names. */ #include <dc/pvr.h> #define PLX_LIST_OP_POLY PVR_LIST_OP_POLY #define PLX_LIST_TR_POLY PVR_LIST_TR_POLY #define PLX_LIST_OP_MOD PVR_LIST_OP_MOD #define PLX_LIST_TR_MOD PVR_LIST_TR_MOD #define PLX_LIST_PT_POLY PVR_LIST_PT_POLY __END_DECLS #endif /* __PARALLAX_LIST */ <file_sep>/include/audio/s3m.h /* LibS3MPLAY (C) PH3NOM 2011 */ void s3m_stop(); int s3m_play(char *fn); #define S3M_NULL 0x00 #define S3M_SUCCESS 0x01 #define S3M_ERROR_MEM 0x02 #define S3M_ERROR_IO 0x03 <file_sep>/lib/libparallax/src/font.c /* Parallax for KallistiOS ##version## font.c (c)2002 <NAME> */ #include <assert.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <kos/fs.h> #include <plx/font.h> #include <plx/prim.h> /* See the header file for all comments and documentation */ /* Implementation notes... TXF Header (thanks to PLIB and gentexfont) BYTES WHAT ----------------------------- 4 0xff + 'txf' 4 0x12345678 for endian testing 4 format: 0 for bytes, 1 for bits 4 texture width 4 texture height 4 maximum font ascent 4 maximum font descent 4 glyph count TXF Per-Glyph Data BYTES WHAT ----------------------------- 2 character index 1 width in pixels 1 height in pixels 1 x offset for left side of char 1 y offset for bottom of char 1 advance 1 char for padding 2 texture x for left of char 2 texture y for bottom of char We'll mimic PLIB here as far as handling the fonts: each u/v coord is offset by half a pixel (which provides a bit of an anti-aliasing effect) and all character sizes are scaled to 1 pixel high using the maximum font ascent. We then multiply this by the point size to get the real quad size. Additionally, we add to the X coordinate of the top of the glyph to achieve an oblique effect (it's not a proper italic...) */ #define PACKED __attribute__((packed)) typedef struct { uint8 magic[4] PACKED; uint32 endian PACKED; uint32 format PACKED; uint32 txr_width PACKED; uint32 txr_height PACKED; int32 max_ascent PACKED; int32 max_descent PACKED; uint32 glyph_cnt PACKED; } txfhdr_t; typedef struct { int16 idx PACKED; int8 w PACKED; int8 h PACKED; int8 x_offset PACKED; int8 y_offset PACKED; int8 advance PACKED; char padding PACKED; uint16 x PACKED; uint16 y PACKED; } txfglyph_t; /* This function DEFINITELY has function growth hormone inbalance syndrome, but whatever... :P And ohh the smell of gotos in the morning! ;) */ plx_font_t * plx_font_load(const char * fn) { plx_font_t * fnt; file_t f; txfhdr_t hdr; txfglyph_t g; int i, x, y; float xstep, ystep, w, h; uint8 * bmtmp = NULL; uint32 bmsize; uint16 * txrtmp = NULL; int stride; /* Open the input file */ f = fs_open(fn, O_RDONLY); if (f == FILEHND_INVALID) { dbglog(DBG_WARNING, "plx_font_load: couldn't open file '%s'\n", fn); return NULL; } /* Create a font struct */ fnt = malloc(sizeof(plx_font_t)); if (fnt == NULL) { dbglog(DBG_WARNING, "plx_font_load: couldn't allocate memory for '%s'\n", fn); goto fail_1; /* bail */ } memset(fnt, 0, sizeof(plx_font_t)); /* Load up the TXF header */ if (fs_read(f, &hdr, sizeof(txfhdr_t)) != sizeof(txfhdr_t)) { dbglog(DBG_WARNING, "plx_font_load: truncated file '%s'\n", fn); goto fail_2; /* bail */ } if (hdr.magic[0] != 0xff || strncmp("txf", hdr.magic+1, 3)) { dbglog(DBG_WARNING, "plx_font_load: invalid font file '%s'\n", fn); goto fail_2; /* bail */ } if (hdr.endian != 0x12345678) { dbglog(DBG_WARNING, "plx_font_load: invalid endianness for '%s'\n", fn); goto fail_2; /* bail */ } /* dbglog(DBG_DEBUG, "plx_font_load: loading font '%s'\n" " texture size: %ldx%ld\n" " max ascent: %ld\n" " max descent: %ld\n" " glyph count: %ld\n", fn, hdr.txr_width, hdr.txr_height, hdr.max_ascent, hdr.max_descent, hdr.glyph_cnt); */ /* Make sure we can allocate texture space for it */ fnt->txr = plx_txr_canvas(hdr.txr_width, hdr.txr_height, PVR_TXRFMT_ARGB4444); if (fnt->txr == NULL) { dbglog(DBG_WARNING, "plx_font_load: can't allocate texture for '%s'\n", fn); goto fail_2; /* bail */ } /* Copy over some other misc housekeeping info */ fnt->glyph_cnt = hdr.glyph_cnt; fnt->map_cnt = 256; /* Just ASCII for now */ /* Allocate structs for the various maps */ fnt->map = malloc(2 * fnt->map_cnt); fnt->txr_ll = malloc(sizeof(point_t) * fnt->glyph_cnt * 4); if (fnt->map == NULL || fnt->txr_ll == NULL) { dbglog(DBG_WARNING, "plx_font_load: can't allocate memory for maps for '%s'\n", fn); goto fail_3; /* bail */ } fnt->txr_ur = fnt->txr_ll + fnt->glyph_cnt * 1; fnt->vert_ll = fnt->txr_ll + fnt->glyph_cnt * 2; fnt->vert_ur = fnt->txr_ll + fnt->glyph_cnt * 3; /* Set all chars as not present */ for (i=0; i<fnt->map_cnt; i++) fnt->map[i] = -1; /* Some more helpful values... */ w = (float)hdr.txr_width; h = (float)hdr.txr_height; xstep = ystep = 0.0f; /* Use this instead to get a pseudo-antialiasing effect */ /* xstep = 0.5f / w; ystep = 0.5f / h; */ /* Ok, go through and load up each glyph */ for (i=0; i<fnt->glyph_cnt; i++) { /* Load up the glyph info */ if (fs_read(f, &g, sizeof(txfglyph_t)) != sizeof(txfglyph_t)) { dbglog(DBG_WARNING, "plx_font_load: truncated file '%s'\n", fn); goto fail_3; /* bail */ } /* Is it above our limit? If so, ignore it */ if (g.idx >= fnt->map_cnt) continue; /* Leave out the space glyph, if we have one */ if (g.idx == ' ') continue; /* Pull in all the relevant parameters */ fnt->map[g.idx] = i; fnt->txr_ll[i].x = g.x / w + xstep; fnt->txr_ll[i].y = g.y / h + ystep; fnt->txr_ur[i].x = (g.x + g.w) / w + xstep; fnt->txr_ur[i].y = (g.y + g.h) / h + ystep; fnt->vert_ll[i].x = (float)g.x_offset / hdr.max_ascent; fnt->vert_ll[i].y = (float)g.y_offset / hdr.max_ascent; fnt->vert_ur[i].x = ((float)g.x_offset + g.w) / hdr.max_ascent; fnt->vert_ur[i].y = ((float)g.y_offset + g.h) / hdr.max_ascent; /* dbglog(DBG_DEBUG, " loaded glyph %d(%c): uv %.2f,%.2f - %.2f,%.2f, vert %.2f,%.2f - %.2f, %.2f\n", g.idx, (char)g.idx, (double)fnt->txr_ll[i].x, (double)fnt->txr_ll[i].y, (double)fnt->txr_ur[i].x, (double)fnt->txr_ur[i].y, (double)fnt->vert_ll[i].x, (double)fnt->vert_ll[i].y, (double)fnt->vert_ur[i].x, (double)fnt->vert_ur[i].y); */ } /* What format are we using? */ switch (hdr.format) { case 1: /* TXF_FORMAT_BITMAP */ /* Allocate temp texture space */ bmsize = hdr.txr_width * hdr.txr_height / 8; bmtmp = malloc(bmsize); txrtmp = malloc(hdr.txr_width * hdr.txr_height * 2); if (bmtmp == NULL || txrtmp == NULL) { dbglog(DBG_WARNING, "plx_font_load: can't allocate temp texture space for '%s'\n", fn); goto fail_3; /* bail */ } /* Load the bitmap and convert to a texture */ if (fs_read(f, bmtmp, bmsize) != bmsize) { dbglog(DBG_WARNING, "plx_font_load: truncated file '%s'\n", fn); goto fail_4; /* bail */ } stride = hdr.txr_width / 8; for (y=0; y<hdr.txr_height; y++) { for (x=0; x<hdr.txr_width; x++) { if (bmtmp[y * stride + x/8] & (1 << (x%8))) { txrtmp[y*hdr.txr_width+x] = 0xffff; } else { txrtmp[y*hdr.txr_width+x] = 0; } } } break; case 0: /* TXF_FORMAT_BYTE */ /* Allocate temp texture space */ bmsize = hdr.txr_width * hdr.txr_height; txrtmp = malloc(bmsize * 2); if (txrtmp == NULL) { dbglog(DBG_WARNING, "plx_font_load: can't allocate temp texture space for '%s'\n", fn); goto fail_3; /* bail */ } /* Load the texture */ if (fs_read(f, txrtmp, bmsize) != bmsize) { dbglog(DBG_WARNING, "plx_font_load: truncated file '%s'\n", fn); goto fail_4; /* bail */ } /* Convert to ARGB4444 -- go backwards so we can do it in place */ /* PLIB seems to duplicate the alpha value into luminance. I think it * looks nicer to hardcode luminance to 1.0; characters look more robust. */ bmtmp = (uint8 *)txrtmp; for (x=bmsize-1; x>=0; x--) { uint8 alpha = (bmtmp[x] & 0xF0) >> 4; /* uint8 lum = alpha; */ uint8 lum = 0x0f; txrtmp[x] = (alpha << 12) | (lum << 8) | (lum << 4) | (lum << 0); } bmtmp = NULL; break; } /* dbglog(DBG_DEBUG, "plx_font_load: load done\n"); */ /* Close the file */ fs_close(f); /* Now load the temp texture into our canvas texture and twiddle it */ pvr_txr_load_ex(txrtmp, fnt->txr->ptr, hdr.txr_width, hdr.txr_height, PVR_TXRLOAD_16BPP); /* Yay! Everything's happy. Clean up our temp textures and return the font. */ if (bmtmp) free(bmtmp); if (txrtmp) free(txrtmp); return fnt; /* Error handlers */ fail_4: /* Temp texture is allocated */ if (bmtmp) free(bmtmp); if (txrtmp) free(txrtmp); fail_3: /* Texture and some maps are allocated */ if (fnt->map != NULL) free(fnt->map); if (fnt->txr_ll != NULL) free(fnt->txr_ll); plx_txr_destroy(fnt->txr); fail_2: /* Font struct is allocated */ free(fnt); fail_1: /* Only the file is open */ fs_close(f); return NULL; } void plx_font_destroy(plx_font_t * fnt) { assert( fnt != NULL ); if (fnt == NULL) return; assert( fnt->txr != NULL ); if (fnt->txr != NULL) plx_txr_destroy(fnt->txr); assert( fnt->map != NULL ); if (fnt->map != NULL) free(fnt->map); assert( fnt->txr_ll != NULL ); if (fnt->txr_ll != NULL) free(fnt->txr_ll); free(fnt); } plx_fcxt_t * plx_fcxt_create(plx_font_t * fnt, int list) { plx_fcxt_t * cxt; assert( fnt != NULL ); if (fnt == NULL) return NULL; /* Allocate a struct */ cxt = malloc(sizeof(plx_fcxt_t)); if (cxt == NULL) { dbglog(DBG_WARNING, "plx_fcxt_create: couldn't allocate memory for context\n"); return NULL; } /* Fill in some default values */ memset(cxt, 0, sizeof(plx_fcxt_t)); cxt->fnt = fnt; cxt->list = list; cxt->slant = 0.0f; cxt->size = 24.0f; cxt->gap = 0.1f; cxt->fixed_width = 1.0f; cxt->flags = 0; cxt->color = PVR_PACK_COLOR(1.0f, 1.0f, 1.0f, 1.0f); cxt->pos.x = 0.0f; cxt->pos.y = 0.0f; cxt->pos.z = 0.0f; return cxt; } void plx_fcxt_destroy(plx_fcxt_t * cxt) { assert( cxt != NULL ); if (cxt == NULL) return; free(cxt); } void plx_fcxt_char_metrics(plx_fcxt_t * cxt, uint16 ch, float * outleft, float * outup, float * outright, float *outdown) { plx_font_t * fnt; int g; assert( cxt != NULL ); assert( cxt->fnt != NULL ); if (cxt == NULL || cxt->fnt == NULL) return; fnt = cxt->fnt; if (ch >= fnt->map_cnt) ch = ' '; if (fnt->map[ch] == -1) ch = ' '; if (ch == ' ') { *outleft = 0; *outup = 0; *outright = cxt->gap + cxt->size / 2.0f; *outdown = 0; return; } g = fnt->map[ch]; assert( 0 <= g && g < fnt->glyph_cnt ); if (g < 0 || g >= fnt->glyph_cnt) return; *outleft = fnt->vert_ll[g].x * cxt->size; *outup = fnt->vert_ur[g].y * cxt->size; if (cxt->flags & PLX_FCXT_FIXED) *outright = (cxt->gap + cxt->fixed_width) * cxt->size; else *outright = (cxt->gap + fnt->vert_ur[g].x) * cxt->size; *outdown = fnt->vert_ll[g].y * -cxt->size; } void plx_fcxt_str_metrics(plx_fcxt_t * cxt, const char * str, float * outleft, float * outup, float * outright, float *outdown) { float l = 0, u = 0, r = 0, d = 0; int i, ch, g, len; plx_font_t * fnt; assert( cxt != NULL ); assert( cxt->fnt != NULL ); if (cxt == NULL || cxt->fnt == NULL) return; len = strlen(str); fnt = cxt->fnt; for (i=0; i<len; i++) { /* Find the glyph (if any) */ ch = str[i]; if (ch < 0 || ch >= fnt->map_cnt) ch = ' '; if (fnt->map[ch] == -1) ch = ' '; if (ch == ' ') { r += cxt->gap + cxt->size / 2.0f; continue; } g = fnt->map[ch]; assert( 0 <= g && g < fnt->glyph_cnt ); if (g < 0 || g >= fnt->glyph_cnt) continue; /* If this is the first char, do the left */ if (i == 0) { l = fnt->vert_ll[g].x * cxt->size; } /* Handle the others */ if (cxt->flags & PLX_FCXT_FIXED) r += (cxt->gap + cxt->fixed_width) * cxt->size; else r += (cxt->gap + fnt->vert_ur[g].x) * cxt->size; if (fnt->vert_ur[g].y * cxt->size > u) u = fnt->vert_ur[g].y * cxt->size; if (fnt->vert_ll[g].y * -cxt->size > d) d = fnt->vert_ll[g].y * -cxt->size; } if (outleft) *outleft = l; if (outup) *outup = u; if (outright) *outright = r; if (outdown) *outdown = d; } void plx_fcxt_setsize(plx_fcxt_t * cxt, float size) { assert( cxt != NULL ); if (cxt == NULL) return; cxt->size = size; } void plx_fcxt_setcolor4f(plx_fcxt_t * cxt, float a, float r, float g, float b) { assert( cxt != NULL ); if (cxt == NULL) return; cxt->color = plx_pack_color(a, r, g, b); } void plx_fcxt_setpos_pnt(plx_fcxt_t * cxt, const point_t * pos) { assert( cxt != NULL ); if (cxt == NULL) return; cxt->pos = *pos; } void plx_fcxt_setpos(plx_fcxt_t * cxt, float x, float y, float z) { point_t pnt = {x, y, z}; plx_fcxt_setpos_pnt(cxt, &pnt); } void plx_fcxt_getpos(plx_fcxt_t * cxt, point_t * outpos) { *outpos = cxt->pos; } void plx_fcxt_begin(plx_fcxt_t * cxt) { assert( cxt != NULL ); assert( cxt->fnt != NULL ); assert( cxt->fnt->txr != NULL ); if (cxt == NULL || cxt->fnt == NULL || cxt->fnt->txr == NULL) return; /* Submit the polygon header for the font texture */ plx_txr_send_hdr(cxt->fnt->txr, cxt->list, 0); } void plx_fcxt_end(plx_fcxt_t * cxt) { assert( cxt != NULL ); } float plx_fcxt_draw_ch(plx_fcxt_t * cxt, uint16 ch) { plx_vertex_t vert; plx_font_t * fnt; int i; assert( cxt != NULL ); assert( cxt->fnt != NULL ); if (cxt == NULL || cxt->fnt == NULL) return 0.0f; fnt = cxt->fnt; /* Do we have the character in question? */ if (ch >= fnt->map_cnt) ch = 32; if (fnt->map[ch] == -1) ch = 32; if (ch == 32) { cxt->pos.x += cxt->gap + cxt->size / 2.0f; return cxt->gap + cxt->size / 2.0f; } i = fnt->map[ch]; assert( i < fnt->glyph_cnt ); if (i >= fnt->glyph_cnt) return 0.0f; /* Submit the vertices */ plx_vert_ifn(&vert, PLX_VERT, cxt->pos.x + fnt->vert_ll[i].x * cxt->size, cxt->pos.y - fnt->vert_ll[i].y * cxt->size, cxt->pos.z, cxt->color, fnt->txr_ll[i].x, fnt->txr_ll[i].y); plx_prim(&vert, sizeof(vert)); vert.x += cxt->slant; vert.y = cxt->pos.y - fnt->vert_ur[i].y * cxt->size; vert.v = fnt->txr_ur[i].y; plx_prim(&vert, sizeof(vert)); vert.x = cxt->pos.x + fnt->vert_ur[i].x * cxt->size; vert.y = cxt->pos.y - fnt->vert_ll[i].y * cxt->size; vert.u = fnt->txr_ur[i].x; vert.v = fnt->txr_ll[i].y; plx_prim(&vert, sizeof(vert)); vert.flags = PLX_VERT_EOS; vert.x += cxt->slant; vert.y = cxt->pos.y - fnt->vert_ur[i].y * cxt->size; vert.v = fnt->txr_ur[i].y; plx_prim(&vert, sizeof(vert)); /* Advance the cursor position */ float adv; if (cxt->flags & PLX_FCXT_FIXED) adv = (cxt->gap + cxt->fixed_width) * cxt->size; else adv = (cxt->gap + fnt->vert_ur[i].x) * cxt->size; cxt->pos.x += adv; return adv; } void plx_fcxt_draw(plx_fcxt_t * cxt, const char * str) { float origx = cxt->pos.x; float ly = 0.0f; while (*str != 0) { if (*str == '\n') { /* Handle newlines somewhat */ cxt->pos.x = origx; ly = cxt->size; cxt->pos.y += ly; str++; } else plx_fcxt_draw_ch(cxt, *str++); } } <file_sep>/modules/mp3/module.c /* DreamShell ##version## module.c - mpg123 module Copyright (C)2009-2014 SWAT */ #include "ds.h" #include "audio/mp3.h" DEFAULT_MODULE_HEADER(mpg123); static int builtin_mpg123(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: %s option args...\n\n" "Options: \n" " -p, --play -Start playing\n" " -s, --stop -Stop playing\n" " -t, --restart -Restart playing\n" " -a, --pause -Pause playing\n" " -o, --forward -Fast forward\n" " -e, --rewind -Rewind\n\n" "Arguments: \n" " -l, --loop -Loop N times (not supported yet)\n" " -f, --file -File for playing\n\n" "Examples: %s --play --file /cd/file.mp3\n" " %s -s", argv[0], argv[0], argv[0]); return CMD_NO_ARG; } int start = 0, stop = 0, loop = 0, forward = 0, rewind = 0, restart = 0, pause = 0; char *file = NULL; struct cfg_option options[] = { {"play", 'p', NULL, CFG_BOOL, (void *) &start, 0}, {"stop", 's', NULL, CFG_BOOL, (void *) &stop, 0}, {"forward", 'o', NULL, CFG_BOOL, (void *) &forward, 0}, {"rewind", 'e', NULL, CFG_BOOL, (void *) &rewind, 0}, {"restart", 't', NULL, CFG_BOOL, (void *) &restart, 0}, {"pause", 'a', NULL, CFG_BOOL, (void *) &pause, 0}, {"loop", 'l', NULL, CFG_INT, (void *) &loop, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(start) { if(file == NULL) { ds_printf("DS_ERROR: Need file for playing\n"); return CMD_ERROR; } sndmp3_stop(); if(sndmp3_start(file, loop) < 0) { ds_printf("DS_ERROR: Maybe bad or unsupported MP3 file: %s\n", file); return CMD_ERROR; } return CMD_OK; } if(stop) { sndmp3_stop(); return CMD_OK; } if(forward) { sndmp3_fastforward(); return CMD_OK; } if(rewind) { sndmp3_rewind(); return CMD_OK; } if(restart) { sndmp3_restart(); return CMD_OK; } if(pause) { sndmp3_pause(); return CMD_OK; } return CMD_NO_ARG; } int lib_open(klibrary_t * lib) { AddCmd(lib_get_name(), "MP1/MP2/MP3 player", (CmdHandler *) builtin_mpg123); return nmmgr_handler_add(&ds_mpg123_hnd.nmmgr); } int lib_close(klibrary_t * lib) { RemoveCmd(GetCmdByName(lib_get_name())); sndmp3_stop(); return nmmgr_handler_remove(&ds_mpg123_hnd.nmmgr); } <file_sep>/commands/sip/main.c /* DreamShell ##version## sip.c Copyright (C) 2015 SWAT */ #include <ds.h> #include <dc/maple.h> #include <dc/maple/sip.h> #include "wave_format.h" #define SAMPLE_BUFF_SIZE 4096 static file_t fd = FILEHND_INVALID; static uint32_t samples_size = 0, sample_buff_len = 0; static uint8_t _sample_buff[SAMPLE_BUFF_SIZE] __attribute__((aligned(32))); static uint8_t *sample_buff = _sample_buff; static WAVE_HEADER_COMPLETE wave_hdr = { { { 'R', 'I', 'F', 'F'}, 0, { 'W', 'A', 'V', 'E'}, }, { { 'f', 'm', 't', ' '}, 16, {1, 0}, 1, 11025, 0, 0, 16, }, { { 'd', 'a', 't', 'a' }, 0 }, }; static void update_wav_header(uint16_t channels, uint32_t frequency, uint16_t bits, uint32_t size) { wave_hdr.wave_hdr.channels = channels; wave_hdr.wave_hdr.samplerate = frequency; wave_hdr.wave_hdr.bitwidth = bits; wave_hdr.wave_hdr.blockalign = channels * (bits / 8); wave_hdr.wave_hdr.bytespersec = frequency * channels * (bits / 8); wave_hdr.riff_hdr.filesize_minus_8 = sizeof(WAVE_HEADER_COMPLETE) + (size * 4) - 8; wave_hdr.sub2.data_size = size * 4; } static void save_sample_buff(file_t fd) { // dbglog(DBG_DEBUG, "Saving sample buffer: %ld\n", sample_buff_len); fs_write(fd, _sample_buff, sample_buff_len); sample_buff_len = 0; sample_buff = _sample_buff; } static file_t create_wav_file(char *fn) { file_t fd; fd = fs_open(fn, O_CREAT | O_WRONLY | O_TRUNC); if(fd == FILEHND_INVALID) { return fd; } update_wav_header(1, 11025, 16, 0); // fs_seek(fd, sizeof(wave_hdr), SEEK_SET); fs_write(fd, &wave_hdr, sizeof(wave_hdr)); return fd; } static void finish_wav_file(file_t fd) { if(sample_buff_len) { save_sample_buff(fd); } ssize_t rv; uint32_t size = samples_size;//fs_total(fd) - sizeof(wave_hdr); update_wav_header(1, 11025, 16, size); fs_seek(fd, 0, SEEK_SET); fs_write(fd, &wave_hdr, sizeof(wave_hdr)); fs_complete(fd, &rv); fs_close(fd); } static void sip_sample_callback(maple_device_t *dev, uint8 *samples, size_t len) { // dbglog(DBG_DEBUG, "Sample: %d (%02x %02x %02x %02x)\n", len, samples[0], samples[1], samples[2], samples[3]); if(!len) { return; } samples_size += len; if(sample_buff_len + len > SAMPLE_BUFF_SIZE) { save_sample_buff(fd); } memcpy_sh4(sample_buff, samples, len); sample_buff_len += len; sample_buff += len; } static void wait_button_press() { ds_printf("DS_PROCESS: Recording... Press A button to stop process.\n"); while(1) { MAPLE_FOREACH_BEGIN(MAPLE_FUNC_CONTROLLER, cont_state_t, st); if(st->buttons & CONT_A) { return; } thd_sleep(500); MAPLE_FOREACH_END(); } } int main(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s options args...\n" "Options: \n" " -r, --record -Start recording to file\n\n" // " -s, --stop -Stop recording\n\n" "Arguments: \n" " -f, --file -File for save audio data\n\n" "Example: %s -s -f /sd/audio.wav\n", argv[0], argv[0]); return CMD_NO_ARG; } /* Arguments */ int record = 0, stop = 0; char *file = NULL; /* Device state */ maple_device_t *sip; // sip_state_t *state; struct cfg_option options[] = { {"record", 'r', NULL, CFG_BOOL, (void *) &record, 0}, {"stop", 's', NULL, CFG_BOOL, (void *) &stop, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); sip = maple_enum_type(0, MAPLE_FUNC_MICROPHONE); if(!sip) { ds_printf("DS_ERROR: Couldn't find any attached devices, bailing out.\n"); return CMD_ERROR; } // state = (sip_state_t *)maple_dev_status(sip); /* Start recording */ if(record) { if(sip_set_gain(sip, SIP_DEFAULT_GAIN) < 0) { ds_printf("DS_ERROR: Couldn't set gain.\n"); return CMD_ERROR; } if(sip_set_sample_type(sip, SIP_SAMPLE_16BIT_SIGNED) < 0) { ds_printf("DS_ERROR: Couldn't set sample type.\n"); return CMD_ERROR; } if(sip_set_frequency(sip, SIP_SAMPLE_11KHZ) < 0) { ds_printf("DS_ERROR: Couldn't set frequency.\n"); return CMD_ERROR; } if((fd = create_wav_file(file)) < 0) { ds_printf("DS_ERROR: Couldn't create file %s\n", file); return CMD_ERROR; } if(sip_start_sampling(sip, sip_sample_callback, 1) < 0) { ds_printf("DS_ERROR: Couldn't start sampling.\n"); finish_wav_file(fd); return CMD_ERROR; } wait_button_press(); // thd_sleep(10 * 1000); sip_stop_sampling(sip, 1); finish_wav_file(fd); ds_printf("DS_OK: Complete.\n"); return CMD_OK; } /* Stop recording */ if(stop) { sip_stop_sampling(sip, 1); ds_printf("DS_OK: Complete.\n"); return CMD_OK; } return CMD_NO_ARG; } <file_sep>/include/opk.h #ifndef OPK_H #define OPK_H #ifdef __cplusplus extern "C" { #endif #include <stdlib.h> struct OPK; struct OPK *opk_open(const char *opk_filename); void opk_close(struct OPK *opk); /* Open the next meta-data file. * if 'filename' is set, the pointer passed as argument will * be set to point to a string corresponding to the filename. * XXX: the pointer will be invalid as soon as opk_close() is called. * * Returns: * -EIO if the file cannot be read, * -ENOMEM if the buffer cannot be allocated, * 0 if no more meta-data file can be found, * 1 otherwise. */ int opk_open_metadata(struct OPK *opk, const char **filename); /* Read a key/value pair. * 'key_chars' and 'val_chars' must be valid pointers. The pointers passed * as arguments will point to the key and value read. 'key_size' and * 'val_size' are set to the length of their respective char arrays. * XXX: the pointers will be invalid as soon as opk_close() is called. * * Returns: * -EIO if the file cannot be read, * 0 if no more key/value pairs can be found, * 1 otherwise. */ int opk_read_pair(struct OPK *opk, const char **key_chars, size_t *key_size, const char **val_chars, size_t *val_size); /* Extract the file with the given filename from the OPK archive. * The 'data' pointer is set to an allocated buffer containing * the file's content. The 'size' variable is set to the length * of the buffer, in bytes. * * Returns: * -ENOENT if the file to extract is not found, * -ENOMEM if the buffer cannot be allocated, * -EIO if the file cannot be read, * 0 otherwise. */ int opk_extract_file(struct OPK *opk, const char *name, void **data, size_t *size); #ifdef __cplusplus } #endif #endif /* OPK_H */ <file_sep>/include/gl/glu.h #ifndef __GL_XLU_H #define __GL_GLU_H #include <sys/cdefs.h> __BEGIN_DECLS #include <gl/gl.h> #define GLU_FALSE 0 #define GLU_TRUE 1 void gluPerspective(GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar); void gluLookAt(GLfloat eyex, GLfloat eyey, GLfloat eyez, GLfloat centerx, GLfloat centery, GLfloat centerz, GLfloat upx, GLfloat upy, GLfloat upz); GLint gluBuild2DMipmaps( GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *data ); /*+HT*/ void gluOrtho2D(GLfloat left, GLfloat right, GLfloat bottom, GLfloat top); void gluPickMatrix(GLfloat x, GLfloat y, GLfloat width, GLfloat height, GLint viewport[4]); GLint gluProject(GLfloat objx, GLfloat objy, GLfloat objz, const GLfloat modelMatrix[16], const GLfloat projMatrix[16], const GLint viewport[4], GLfloat *winx, GLfloat *winy, GLfloat *winz); /*-HT*/ __END_DECLS #endif /* __GL_GLU_H */ <file_sep>/lib/SDL_gui/Mouse.cc /* class GUI_Mouse - used for drawing a colored mousepointer */ #include "SDL_gui.h" /* contructor -call GUI_Surface-contructor -set x=y=0 -create new SDL_Surface for the background */ GUI_Mouse::GUI_Mouse(char *aname, SDL_Surface * sf) : GUI_Surface(aname, sf) { x = 0; y = 0; bgsave = SDL_CreateRGBSurface(sf->flags, sf->w, sf->h, sf->format->BitsPerPixel, sf->format->Rmask, sf->format->Gmask, sf->format->Bmask, sf->format->Amask); } /* destructor -free the background surface */ GUI_Mouse::~GUI_Mouse() { SDL_FreeSurface(bgsave); } /* function Draw */ void GUI_Mouse::Draw(GUI_Screen * screen, int nx, int ny) { //int ox=x; //int oy=y; SDL_Surface *scr; scr = screen->GetSurface()->GetSurface(); x = nx; y = ny; SDL_Rect src, dst; src.x = 0; src.y = 0; if (x + GetWidth() <= scr->w) src.w = GetWidth(); else { src.w = scr->w - x - 1; //printf("adjust: src.w=%d x=%d\n",src.w,x); } if (y + GetHeight() <= scr->h) src.h = GetHeight(); else src.h = scr->h - y - 1; dst.x = x; dst.y = y; dst.w = src.w; dst.h = src.h; SDL_BlitSurface(scr, &dst, bgsave, &src); SDL_BlitSurface(GetSurface(), &src, scr, &dst); SDL_UpdateRect(scr, dst.x, dst.y, dst.w, dst.h); SDL_UpdateRect(scr, odst.x, odst.y, odst.w, odst.h); SDL_BlitSurface(bgsave, &src, scr, &dst); odst = dst; osrc = src; } extern "C" { GUI_Mouse *GUI_MouseCreate(char *name, SDL_Surface * sf) { return new GUI_Mouse(name, sf); } } <file_sep>/lib/SDL_gui/Object.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" extern "C" { int GUI_Object2Trash(GUI_Object *object); } GUI_Object::GUI_Object(const char *aname) { //assert(aname != NULL); if(aname == NULL) { name = NULL; } else { name = strdup(aname); } refcount = 1; } GUI_Object::~GUI_Object(void) { if(name != NULL) free(name); } void GUI_Object::IncRef(void) { refcount++; } int GUI_Object::DecRef(void) { if (--refcount <= 0) { delete this; return 1; } return 0; } int GUI_Object::GetRef(void) { return refcount; } int GUI_Object::Trash(void) { return GUI_Object2Trash(this); } const char *GUI_Object::GetName(void) { return name; } void GUI_Object::SetName(const char *s) { if(name != NULL) free(name); name = strdup(s); } int GUI_Object::CheckName(const char *aname) { return strcmp(name, aname); } extern "C" { GUI_Object *GUI_ObjectCreate(const char *s) { return new GUI_Object(s); } const char *GUI_ObjectGetName(GUI_Object *object) { return object->GetName(); } void GUI_ObjectSetName(GUI_Object *object, const char *s) { object->SetName(s); } void GUI_ObjectIncRef(GUI_Object *object) { if (object) object->IncRef(); } int GUI_ObjectDecRef(GUI_Object *object) { if (object) return object->DecRef(); return 0; } int GUI_ObjectGetRef(GUI_Object *object) { if (object) return object->GetRef(); return 0; } int GUI_ObjectTrash(GUI_Object *object) { if (object) return object->Trash(); return 0; } int GUI_ObjectKeep(GUI_Object **target, GUI_Object *source) { if (source != *target) { GUI_ObjectIncRef(source); GUI_ObjectDecRef(*target); (*target) = source; return 1; } return 0; } } <file_sep>/firmware/bios/bootstrap/Makefile # # Bootstrap for BIOS ROM # Copyright (C) 2009-2014 SWAT # http://www.dc-swat.ru # all: prog.s font.s boot.bin boot.bin: boot.o $(KOS_OBJCOPY) -R .stack -O binary boot.o Dreamshell.bios boot.o: boot.s font.s prog.s $(KOS_AS) -little boot.s -o boot.o font.s: font.bin ./makefonts.py > font.s prog.s: prog.bin ./makeprog.py > prog.s clean: -rm -f boot.o Dreamshell.bios prog.s <file_sep>/applications/vmu_manager/modules/fs_vmd.h /* KallistiOS ##version## fs_vmd.h (c)2000-2001 <NAME> Copyright (C) 2015 megavolt85 */ /* \file fs_vmd.h \brief VMD filesystem driver. The VMD filesystem driver mounts itself on /vmd of the VFS. Each memory card has its own subdirectory off of that directory (i.e, /vmd/a1 for slot 1 of the first controller). VMDs themselves have no subdirectories, so the driver itself is fairly simple. Files on a VMD must be multiples of 512 bytes in size, and should have a header attached so that they show up in the BIOS menu. This layer is built off of the vmdfs layer, which does all the low-level operations. It is generally easier to work with things at this level though, so that you can use the normal libc file access functions. */ #ifndef __DC_FS_VMD_H #define __DC_FS_VMD_H #include <sys/cdefs.h> __BEGIN_DECLS #include <kos/fs.h> /* \cond */ /* Initialization */ int fs_vmd_init(); int fs_vmd_shutdown(); void fs_vmd_vmdfile(const char *infile); /* \endcond */ /* \cond */ #define __packed__ __attribute__((packed)) /* \endcond */ /** \brief BCD timestamp, used several places in the vmdfs. \headerfile vmdfs.h */ typedef struct { uint8 cent; /**< \brief Century */ uint8 year; /**< \brief Year, within century */ uint8 month; /**< \brief Month of the year */ uint8 day; /**< \brief Day of the month */ uint8 hour; /**< \brief Hour of the day */ uint8 min; /**< \brief Minutes */ uint8 sec; /**< \brief Seconds */ uint8 dow; /**< \brief Day of week (0 = monday, etc) */ } __packed__ vmd_timestamp_t; /** \brief VMD FS Root block layout. \headerfile vmdfs.h */ typedef struct { uint8 magic[16]; /**< \brief All should contain 0x55 */ uint8 use_custom; /**< \brief 0 = standard, 1 = custom */ uint8 custom_color[4];/**< \brief blue, green, red, alpha */ uint8 pad1[27]; /**< \brief All zeros */ vmd_timestamp_t timestamp; /**< \brief BCD timestamp */ uint8 pad2[8]; /**< \brief All zeros */ uint8 unk1[6]; /**< \brief ??? */ uint16 fat_loc; /**< \brief FAT location */ uint16 fat_size; /**< \brief FAT size in blocks */ uint16 dir_loc; /**< \brief Directory location */ uint16 dir_size; /**< \brief Directory size in blocks */ uint16 icon_shape; /**< \brief Icon shape for this VMS */ uint16 blk_cnt; /**< \brief Number of user blocks */ uint8 unk2[430]; /**< \brief ??? */ } __packed__ vmd_root_t; /** \brief VMD FS Directory entries, 32 bytes each. \headerfile vmdfs.h */ typedef struct { uint8 filetype; /**< \brief 0x00 = no file; 0x33 = data; 0xcc = a game */ uint8 copyprotect; /**< \brief 0x00 = copyable; 0xff = copy protected */ uint16 firstblk; /**< \brief Location of the first block in the file */ char filename[12]; /**< \brief Note: there is no null terminator */ vmd_timestamp_t timestamp; /**< \brief File time */ uint16 filesize; /**< \brief Size of the file in blocks */ uint16 hdroff; /**< \brief Offset of header, in blocks from start of file */ uint8 dirty; /**< \brief See header notes */ uint8 pad1[3]; /**< \brief All zeros */ } __packed__ vmd_dir_t; #undef __packed__ int vmdfs_readdir(const char *vmdfile, vmd_dir_t ** outbuf, int * outcnt); int vmdfs_read(const char *vmdfile, const char * fn, void ** outbuf, int * outsize); int vmdfs_init(); int vmdfs_shutdown(); __END_DECLS #endif /* __DC_FS_VMD_H */ <file_sep>/include/plx/color.h /* Parallax for KallistiOS ##version## color.h (c)2002 <NAME> */ #ifndef __PARALLAX_COLOR #define __PARALLAX_COLOR #include <sys/cdefs.h> __BEGIN_DECLS /** \file Color handling routines. This is all just wrappers for PVR stuff at the moment to ease portability. */ #include <dc/pvr.h> static inline uint32 plx_pack_color(float a, float r, float g, float b) { return PVR_PACK_COLOR(a, r, g, b); } __END_DECLS #endif /* __PARALLAX_COLOR */ <file_sep>/firmware/aica/mp3.c #include <stddef.h> #include "drivers/aica_cmd_iface.h" #include "aica.h" #include "mp3dec.h" static HMP3Decoder hMP3Decoder; static MP3FrameInfo mp3FrameInfo; static aica_channel_t mp3_chan[2]; extern volatile aica_channel_t *chans; void * memcpy(void *dest, const void *src, size_t count); int init_mp3() { if(!hMP3Decoder) hMP3Decoder = MP3InitDecoder(); return 0; } void shutdown_mp3() { MP3FreeDecoder(hMP3Decoder); } int decode_mp3(aica_decoder_t *dat) { int offset = 0, i = 0; int bytes = dat->length; unsigned char *buf = (unsigned char*)dat->base; short *out = (short*)dat->out; offset = MP3FindSyncWord(buf, bytes); if(offset < 0) { return -1; } buf += offset; bytes -= offset; if(MP3Decode(hMP3Decoder, &buf, &bytes, out, 0)) { return -1; } MP3GetLastFrameInfo(hMP3Decoder, &mp3FrameInfo); for(i = 0; i < mp3FrameInfo.nChans; i++) { mp3_chan[i].cmd = AICA_CH_CMD_START | AICA_CH_START_DELAY; mp3_chan[i].base = dat->chan[i]; mp3_chan[i].type = AICA_SM_16BIT; mp3_chan[i].length = (mp3FrameInfo.outputSamps / mp3FrameInfo.nChans); mp3_chan[i].loop = 1; mp3_chan[i].loopstart = 0; mp3_chan[i].loopend = (mp3FrameInfo.outputSamps / mp3FrameInfo.nChans); mp3_chan[i].freq = mp3FrameInfo.samprate; mp3_chan[i].vol = 255; mp3_chan[i].pan = 0; memcpy((void*)(chans + dat->chan[i]), &mp3_chan[i], sizeof(aica_channel_t)); chans[dat->chan[i]].pos = 0; aica_play(dat->chan[i], 0); } return mp3FrameInfo.nChans; } <file_sep>/firmware/aica/codec/ir.h #ifndef _IR_H_ #define _IR_H_ void ir_receive(void); int ir_get_cmd(void); void ir_init(void); #endif /* _IR_H_ */ <file_sep>/modules/aicaos/sh4/aica_sh4.h #ifndef _AICA_SH4_H #define _AICA_SH4_H /* Init the AICA communication subsystem. * The argument is the filename of the AICA driver. */ int aica_init(char *fn); #endif <file_sep>/src/main.c /**************************** * DreamShell ##version## * * main.c * * DreamShell main * * (c)2004-2023 SWAT * * http://www.dc-swat.ru * ***************************/ #include "ds.h" #include "fs.h" #include "vmu.h" #include "profiler.h" #include "network/net.h" extern uint8 romdisk[]; KOS_INIT_FLAGS(INIT_IRQ | INIT_THD_PREEMPT); KOS_INIT_ROMDISK(romdisk); static uint32 ver_int = 0; static const char *build_str[4] = {"Alpha", "Beta", "RC", "Release"}; static uint32 net_inited = 0; void gdb_init(); uint32 _fs_dclsocket_get_ip(void); uint32 GetVersion() { return ver_int; } void SetVersion(uint32 ver) { char ver_str[32]; uint ver_bld; if(ver == 0) { ver_int = DS_MAKE_VER(VER_MAJOR, VER_MINOR, VER_MICRO, VER_BUILD); } else { ver_int = ver; } ver_bld = (uint)DS_VER_BUILD(ver_int); if(DS_VER_BUILD_TYPE(ver_bld) == DS_VER_BUILD_TYPE_RELEASE) { snprintf(ver_str, sizeof(ver_str), "%d.%d.%d %s", (uint)DS_VER_MAJOR(ver_int), (uint)DS_VER_MINOR(ver_int), (uint)DS_VER_MICRO(ver_int), DS_VER_BUILD_TYPE_STR(ver_bld)); } else { snprintf(ver_str, sizeof(ver_str), "%d.%d.%d.%s.%d", (uint)DS_VER_MAJOR(ver_int), (uint)DS_VER_MINOR(ver_int), (uint)DS_VER_MICRO(ver_int), DS_VER_BUILD_TYPE_STR(ver_bld), DS_VER_BUILD_NUM(ver_bld)); } setenv("VERSION", ver_str, 1); } const char *GetVersionBuildTypeString(int type) { return build_str[type]; } static uint8 *get_board_id() { uint8 *(*sc)(int, int, int, int) = NULL; uint32 *scv = (uint32 *)&sc; *scv = *((uint32 *)0x8c0000b0); return sc(0, 0, 0, 3); } int InitNet(uint32 ipl) { #if defined(DS_DEBUG) net_inited = 1; #endif if(net_inited) { return 0; } union { uint32 ipl; uint8 ipb[4]; } ip; ip.ipl = ipl; /* Check if the dcload-ip console is up, and if so, disable it, otherwise we'll crash when we attempt to bring up the BBA */ if(dcload_type == DCLOAD_TYPE_IP) { /* Grab the IP address from dcload before we disable dbgio... */ ip.ipl = _fs_dclsocket_get_ip(); dbglog(DBG_INFO, "dc-load says our IP is %d.%d.%d.%d\n", ip.ipb[3], ip.ipb[2], ip.ipb[1], ip.ipb[0]); dbgio_disable(); } int rv = net_init(ip.ipl); /* Enable networking (and drivers) */ if(rv < 0) { dbgio_enable(); return -1; } if(dcload_type == DCLOAD_TYPE_IP) { fs_dclsocket_init_console(); if(!fs_dclsocket_init()) { dbgio_dev_select("fs_dclsocket"); dbgio_enable(); dbglog(DBG_INFO, "fs_dclsocket console support enabled\n"); } else { dbgio_enable(); } } if (net_default_dev != NULL) { char ip_str[64]; memset(ip_str, 0, sizeof(ip_str)); snprintf(ip_str, sizeof(ip_str), "%d.%d.%d.%d", net_default_dev->ip_addr[0], net_default_dev->ip_addr[1], net_default_dev->ip_addr[2], net_default_dev->ip_addr[3]); setenv("NET_IPV4", ip_str, 1); dbglog(DBG_INFO, "Network IPv4 address: %s\n", ip_str); } net_inited = 1; return rv; } void ShutdownNet() { if(dcload_type == DCLOAD_TYPE_IP) { dbgio_set_dev_ds(); } net_shutdown(); net_inited = 0; setenv("NET_IPV4", "0.0.0.0", 1); } int InitDS() { char fn[NAME_MAX], bf[32]; int tmpi = 0; uint8 *tmpb = NULL; Settings_t *settings; #ifdef DS_EMU int emu = 1; #else int emu = 0; #endif SetVersion(0); #if defined(DS_DEBUG) && DS_DEBUG == 2 gdb_init(); #elif defined(USE_DS_EXCEPTIONS) expt_init(); #endif #ifdef DS_DEBUG uint64 t_start = timer_ms_gettime64(); dbglog_set_level(DBG_KDEBUG); #endif if(!emu) { InitIDE(); InitSDCard(); if(is_custom_bios()) { InitRomdisk(); } } else { setenv("EMU", "Unknown", 1); } SearchRoot(); settings = GetSettings(); InitVideoHardware(); ShowLogo(); if(settings->root[0] != 0 && DirExists(settings->root)) { setenv("PATH", settings->root, 1); if( !strncmp(getenv("PATH"), "/sd", 3) || !strncmp(getenv("PATH"), "/ide", 4) || !strncmp(getenv("PATH"), "/pc", 3)) { setenv("TEMP", getenv("PATH"), 1); } else { setenv("TEMP", "/ram", 1); } } setenv("HOST", "DreamShell", 1); setenv("OS", getenv("HOST"), 1); setenv("USER", getenv("HOST"), 1); setenv("ARCH", hardware_sys_mode(&tmpi) == HW_TYPE_SET5 ? "Set5.xx" : "Dreamcast", 1); setenv("NET_IPV4", "0.0.0.0", 1); setenv("SDL_DEBUG", "0", 1); setenv("SDL_VIDEODRIVER", "dcvideo", 1); vmu_draw_string(getenv("HOST")); dbglog(DBG_INFO, "Initializing DreamShell Core...\n"); SetConsoleDebug(1); setenv("HOME", getenv("PATH"), 1); setenv("$PATH", getenv("PATH"), 1); setenv("LUA_PATH", getenv("PATH"), 1); setenv("LUA_CPATH", getenv("PATH"), 1); setenv("PWD", fs_getwd(), 1); setenv("APP", (settings->app[0] != 0 ? settings->app : "Main"), 1); /* If used custom BIOS and syscalls is not installed, setting up it */ if(is_custom_bios() && is_no_syscalls()) { tmpb = (uint8 *)0x8c000068; } else { /* Getting board ID */ tmpb = get_board_id(); if(strncmp(getenv("PATH"), "/cd", 3)) { /* Relax GD drive =) */ cdrom_spin_down(); } } memset(fn, 0, sizeof(fn)); for(tmpi = 0; tmpi < 8; tmpi++) { sprintf(bf, "%02X", tmpb[tmpi]); strcat(fn, bf); } setenv("BOARD_ID", fn, 1); IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG); InitEvents(); /* Initializing video */ if(!InitVideo(settings->video.tex_width, settings->video.tex_height, settings->video.bpp)) { dbglog(DBG_ERROR, "Can't init video: %dx%dx\n", settings->video.tex_width, settings->video.tex_height); arch_reboot(); } SetScreenMode(settings->video.virt_width, settings->video.virt_height, 0.0f, 0.0f, 1.0f); snprintf(fn, NAME_MAX, "%s/gui/cursors/default.png", getenv("PATH")); SetActiveMouseCursor(CreateMouseCursor(fn, NULL)); TTF_Init(); InitGUI(); snd_stream_init(); snprintf(fn, NAME_MAX, "%s/fonts/bitmap/console.png", getenv("PATH")); InitCmd(); InitConsole(fn, NULL, 40, 0, 0, GetScreenWidth(), GetScreenHeight(), 255); if(InitModules()) { dbglog(DBG_ERROR, "Can't init modules\n"); return -1; } if(InitApps()) { dbglog(DBG_ERROR, "Can't init apps\n"); return -1; } if(InitLua()) { dbglog(DBG_ERROR, "Can't init lua library\n"); return -1; } #ifdef DS_DEBUG uint64 t_end = timer_ms_gettime64(); dbglog(DBG_INFO, "Initializing time: %ld ms\n", (uint32)(t_end - t_start)); #endif if(settings->startup[0] == '/') { snprintf(fn, NAME_MAX, "%s%s", getenv("PATH"), settings->startup); LuaDo(LUA_DO_FILE, fn, GetLuaState()); } else if(settings->startup[0] == '#') { dsystem_buff(settings->startup); } else if(settings->startup[0] != 0) { LuaDo(LUA_DO_STRING, settings->startup, GetLuaState()); } else { snprintf(fn, NAME_MAX, "%s/lua/startup.lua", getenv("PATH")); LuaDo(LUA_DO_FILE, fn, GetLuaState()); } #ifdef DS_DEBUG t_end = timer_ms_gettime64(); dbglog(DBG_INFO, "Startup time: %ld ms\n", (uint32)(t_end - t_start)); #else if(!emu) { SetConsoleDebug(0); dbgio_set_dev_ds(); } #endif HideLogo(); #ifdef DS_PROF if(dcload_type == DCLOAD_TYPE_IP) { profiler_init("/pc"); } else { profiler_init(getenv("PATH")); } profiler_start(); #endif return 0; } void ShutdownDS() { #ifdef DS_PROF profiler_stop(); profiler_clean_up(); #endif dbglog(DBG_INFO, "Shutting down DreamShell Core...\n"); char fn[NAME_MAX]; snprintf(fn, NAME_MAX, "%s/lua/shutdown.lua", getenv("PATH")); LuaDo(LUA_DO_FILE, fn, GetLuaState()); ShutdownCmd(); ShutdownVideoThread(); ShutdownApps(); ShutdownConsole(); ShutdownModules(); ShutdownEvents(); ShutdownLua(); ShutdownNet(); expt_shutdown(); g1_ata_shutdown(); } int main(int argc, char **argv) { SDL_Event event; maple_device_t *dev; int key; if(InitDS()) { return -1; } while(1) { while(SDL_PollEvent(&event)) { if((dev = maple_enum_type(0, MAPLE_FUNC_KEYBOARD))) { key = kbd_queue_pop(dev, 1); /* ASCII? */ if(!(key & 0xFFFFFF00)) { event.key.keysym.unicode = key; } } ProcessInputEvents(&event); } UnLoadOldApps(); GUI_ClearTrash(); if(event.type == SDL_QUIT) { break; } } ShutdownDS(); return 0; } <file_sep>/firmware/isoldr/loader/kos/dc/vmu.h /* This file is part of the libdream Dreamcast function library. * Please see libdream.c for further details. * * (c)2000 <NAME> Ported from KallistiOS (Dreamcast OS) for libdream by <NAME> */ #include <sys/cdefs.h> #include <arch/types.h> #ifndef __VMU_H #define __VMU_H int vmu_draw_lcd(uint8 addr, void *bitmap); int vmu_block_read(uint8 addr, uint16 blocknum, uint8 *buffer); int vmu_block_write(uint8 addr, uint16 blocknum, uint8 *buffer); #endif <file_sep>/modules/mp3/libmp3/libmp3/Makefile # KallistiOS ##version## # # libmp3/Makefile # (c)2001 <NAME> OBJS = main.o mpg123_snddrv.o snddrv.o BUILD_TARGET = addons/libmp3 #KOS_CFLAGS += -I../xingmp3 KOS_CFLAGS += -I../mpg123/src -I../mpg123/src/libmpg123 -I../../../../include/audio all: $(OBJS) cp $(OBJS) ../build/ include $(KOS_BASE)/Makefile.prefab <file_sep>/firmware/isoldr/loader/kos/net/net.h /* net/net.h Copyright (C)2004 <NAME> */ #ifndef __NET_NET_H #define __NET_NET_H #include <sys/cdefs.h> __BEGIN_DECLS #include <arch/types.h> #include <kos/net.h> /* Thanks to AndrewK for these IP structures and the code which I studied to create this (dc-load-ip). */ #define packed //__attribute__((packed)) // Prepended to all ethernet packets typedef struct { uint8 dest[6] packed; uint8 src[6] packed; uint8 type[2] packed; } eth_hdr_t; // Prepended to all IP packets typedef struct { uint8 version_ihl packed; uint8 tos packed; uint16 length packed; uint16 packet_id packed; uint16 flags_frag_offs packed; uint8 ttl packed; uint8 protocol packed; uint16 checksum packed; uint32 src packed; uint32 dest packed; } ip_hdr_t; // Prepended to all ICMP packets typedef struct { uint8 type packed; uint8 code packed; uint16 checksum packed; uint32 misc packed; } icmp_hdr_t; // ARP packet typedef struct { uint16 hw_space packed; uint16 proto_space packed; uint8 hw_len packed; uint8 proto_len packed; uint16 opcode packed; uint8 hw_src[6] packed; uint8 proto_src[4] packed; uint8 hw_dest[6] packed; uint8 proto_dest[4] packed; } arp_pkt_t; // UDP packet typedef struct { uint16 src_port packed; uint16 dest_port packed; uint16 length packed; uint16 checksum packed; uint8 data[0] packed; } udp_pkt_t; // UDP pseudo packet. This is used for checksum calculation. typedef struct { uint32 src_ip packed; uint32 dest_ip packed; uint8 zero packed; uint8 protocol packed; uint16 udp_length packed; uint16 src_port packed; uint16 dest_port packed; uint16 length packed; uint16 checksum packed; uint8 data[0] packed; } udp_pseudo_pkt_t; // PC->DC and response packets typedef struct { uint8 tag[4] packed; uint32 addr packed; uint32 size packed; uint8 data[0] packed; } pkt_tas_t; // DC->PC 3i packet typedef struct { uint8 tag[4] packed; uint32 value0 packed; uint32 value1 packed; uint32 value2 packed; uint32 value3 packed; // serial for 3i } pkt_3i_t; // DC->PC 2is packet typedef struct { uint8 tag[4] packed; uint32 value0 packed; uint32 value1 packed; uint8 data[0] packed; } pkt_2is_t; // DC->PC i packet typedef struct { uint8 tag[4] packed; uint32 value0 packed; } pkt_i_t; // DC->PC s packet typedef struct { uint8 tag[4] packed; uint8 data[0] packed; } pkt_s_t; #undef packed uint16 net_checksum(uint16 *data, int words); uint16 ntohs(uint16 n); uint32 ntohl(uint32 n); #define htons ntohs #define htonl ntohl // Packet buffers all drivers can use extern uint8 net_rxbuf[1514], net_txbuf[1514]; // Active network device extern netif_t * nif; // Our IP, if we know it extern uint32 net_ip; // Host PC's IP, MAC address, and port, if we know it. extern uint32 net_host_ip; extern uint16 net_host_port; extern uint8 net_host_mac[6]; // When a command is initiated, this value is set to zero. When the command // is completed, the value is set to non-zero. This is used in exclusive // mode (to quit) or in immediate mode to exit back to the calling program. extern volatile int net_exit_loop; // When an RPC call is completed, this variable will hold the return // value of the call. extern volatile int net_rpc_ret; // Network loop for immediate and exclusive modes. Returns when net_exit_loop // is set to non-zero. int net_loop(); // Packet input functions int net_arp_input(netif_t * src, uint8 * pkt, int pktsize); int net_icmp_input(netif_t * src, uint8 * pkt, int pktsize); int net_udp_input(netif_t * src, uint8 * pkt, int pktsize); // This helper function will create a response packet to the one sitting // in net_rxbuf in net_txbuf and return a pointer to the UDP payload part // of the packet. uint8 * net_resp_build(); // Same as net_resp_build, but assumes there is no packet in net_rxbuf to // model this one after. This requires that we have received at least one // packet from the host PC. uint8 * net_tx_build(); // This helper function completes the response by finishing the packet in // net_txbuf (calc checksum, etc) and sending it out the ethernet driver. void net_resp_complete(int size); __END_DECLS #endif /* __NET_NET_H */ <file_sep>/lib/SDL_gui/Button.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_Button::GUI_Button(const char *aname, int x, int y, int w, int h) : GUI_AbstractButton(aname, x, y, w, h) { SDL_Rect in; in.x = 4; in.y = 4; in.w = area.w-8; in.h = area.h-8; disabled = new GUI_Surface("disabled", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); normal = new GUI_Surface("normal", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); highlight = new GUI_Surface("highlight", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); pressed = new GUI_Surface("pressed", SDL_HWSURFACE, w, h, 16, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); disabled->Fill(NULL, 0xFF000000); normal->Fill(NULL, 0xFF000000); highlight->Fill(NULL, 0x00FFFFFF); highlight->Fill(&in, 0xFF000000); pressed->Fill(NULL, 0x00FFFFFF); pressed->Fill(&in, 0x005050C0); } GUI_Button::~GUI_Button() { normal->DecRef(); highlight->DecRef(); pressed->DecRef(); disabled->DecRef(); } GUI_Surface *GUI_Button::GetCurrentImage() { if (flags & WIDGET_DISABLED) return disabled; if (flags & WIDGET_INSIDE) { if (flags & WIDGET_PRESSED) return pressed; return highlight; } return normal; } void GUI_Button::SetNormalImage(GUI_Surface *surface) { if (GUI_ObjectKeep((GUI_Object **) &normal, surface)) MarkChanged(); } void GUI_Button::SetHighlightImage(GUI_Surface *surface) { if (GUI_ObjectKeep((GUI_Object **) &highlight, surface)) MarkChanged(); } void GUI_Button::SetPressedImage(GUI_Surface *surface) { if (GUI_ObjectKeep((GUI_Object **) &pressed, surface)) MarkChanged(); } void GUI_Button::SetDisabledImage(GUI_Surface *surface) { if (GUI_ObjectKeep((GUI_Object **) &disabled, surface)) MarkChanged(); } extern "C" { GUI_Widget *GUI_ButtonCreate(const char *name, int x, int y, int w, int h) { return new GUI_Button(name, x, y, w, h); } int GUI_ButtonCheck(GUI_Widget *widget) { // FIXME not implemented return 0; } void GUI_ButtonSetNormalImage(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_Button *) widget)->SetNormalImage(surface); } void GUI_ButtonSetHighlightImage(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_Button *) widget)->SetHighlightImage(surface); } void GUI_ButtonSetPressedImage(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_Button *) widget)->SetPressedImage(surface); } void GUI_ButtonSetDisabledImage(GUI_Widget *widget, GUI_Surface *surface) { ((GUI_Button *) widget)->SetDisabledImage(surface); } void GUI_ButtonSetCaption(GUI_Widget *widget, GUI_Widget *caption) { ((GUI_Button *) widget)->SetCaption(caption); } void GUI_ButtonSetCaption2(GUI_Widget *widget, GUI_Widget *caption) { ((GUI_Button *) widget)->SetCaption2(caption); } GUI_Widget *GUI_ButtonGetCaption(GUI_Widget *widget) { return ((GUI_Button *) widget)->GetCaption(); } GUI_Widget *GUI_ButtonGetCaption2(GUI_Widget *widget) { return ((GUI_Button *) widget)->GetCaption(); } void GUI_ButtonSetClick(GUI_Widget *widget, GUI_Callback *callback) { ((GUI_Button *) widget)->SetClick(callback); } void GUI_ButtonSetContextClick(GUI_Widget *widget, GUI_Callback *callback) { ((GUI_Button *) widget)->SetContextClick(callback); } void GUI_ButtonSetMouseover(GUI_Widget *widget, GUI_Callback *callback) { ((GUI_Button *) widget)->SetMouseover(callback); } void GUI_ButtonSetMouseout(GUI_Widget *widget, GUI_Callback *callback) { ((GUI_Button *) widget)->SetMouseout(callback); } } <file_sep>/lib/SDL_gui/TrueTypeFont.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_TrueTypeFont::GUI_TrueTypeFont(const char *fn, int size) : GUI_Font(fn) { /* FIXME include the size in the name for caching */ ttf = TTF_OpenFont(fn, size); if (ttf == NULL) /*throw*/ GUI_Exception("TTF_OpenFont failed name='%s' size=%d", fn, size); } GUI_TrueTypeFont::~GUI_TrueTypeFont(void) { if (ttf) TTF_CloseFont(ttf); } GUI_Surface *GUI_TrueTypeFont::RenderFast(const char *s, SDL_Color fg) { assert(s != NULL); if (strlen(s) == 0) return NULL; return new GUI_Surface("text", TTF_RenderText_Solid(ttf, s, fg)); } GUI_Surface *GUI_TrueTypeFont::RenderQuality(const char *s, SDL_Color fg) { assert(s != NULL); if (strlen(s) == 0) return NULL; return new GUI_Surface("text", TTF_RenderText_Blended(ttf, s, fg)); } SDL_Rect GUI_TrueTypeFont::GetTextSize(const char *s) { SDL_Rect r = { 0, 0, 0, 0 }; int w, h; assert(s != NULL); if (strlen(s) != 0) { if (TTF_SizeText(ttf, s, &w, &h) == 0) { r.w = w; r.h = h; } } return r; } extern "C" GUI_Font *GUI_FontLoadTrueType(char *fn, int size) { return new GUI_TrueTypeFont(fn, size); } <file_sep>/lib/libparallax/include/texture.h /* Parallax for KallistiOS ##version## texture.h (c)2002 <NAME> */ #ifndef __PARALLAX_TEXTURE #define __PARALLAX_TEXTURE #include <sys/cdefs.h> __BEGIN_DECLS /** \file Higher-level texture management routines. This module goes beyond what the hardware routines themselves provide by wrapping the texture information into a convienent struct. This struct contains information such as the hardware VRAM pointer, width and height, format information, etc. We also provide a texture loading facility, and another for creating "canvas" textures which can be written to in real-time to produce interesting effects. WARNING: The internal members of plx_texture_t may change from platform to platform below the "ARCH" line. So be wary of using that stuff directly. */ #include <dc/pvr.h> /** Texture structure */ typedef struct plx_texture { pvr_ptr_t ptr; /**< Pointer to the PVR memory */ int w; /**< Texture width */ int h; /**< Texture height */ int fmt; /**< PVR texture format (e.g., PVR_TXRFMT_ARGB4444) */ /*** ARCH ***/ pvr_poly_cxt_t cxt_opaque, cxt_trans, cxt_pt; /**< PVR polygon contexts for each list for this texture */ pvr_poly_hdr_t hdr_opaque, hdr_trans, hdr_pt; /**< PVR polygon headers for each list for this texture */ } plx_texture_t; /** Load a texture from the VFS and return a plx_texture_t structure. The file type will be autodetected (eventually). If you want the texture loader to create a texture with an alpha channel, then specify a non-zero value for use_alpha. The value for txrload_flags will be passed directly to pvr_txr_load_kimg(). */ plx_texture_t * plx_txr_load(const char * fn, int use_alpha, int txrload_flags); /** Create a texture from raw PVR memory as a "canvas" for the application to draw into. Specify all the relevant parameters. */ plx_texture_t * plx_txr_canvas(int w, int h, int fmt); /** Destroy a previously created texture. */ void plx_txr_destroy(plx_texture_t * txr); /** Edit the texture's header bits to specify the filtering type during scaling and perspective operations. All cached values will be updated. If you've already called send_hdr, you'll need to call it again. */ void plx_txr_setfilter(plx_texture_t * txr, int mode); /* Constants for plx_txr_setfilter */ #define PLX_FILTER_NONE PVR_FILTER_NONE #define PLX_FILTER_BILINEAR PVR_FILTER_BILINEAR /** Edit the texture's header bits to specify the UV clamp types. All cached values will be updated. If you've already called send_hdr, you'll need to call it again. */ void plx_txr_setuvclamp(plx_texture_t * txr, int umode, int vmode); /* Constants for plx_txr_setuvclamp */ #define PLX_UV_REPEAT 0 #define PLX_UV_CLAMP 1 /** Re-create the cached pvr_poly_hdr_t's from the struct's pvr_poly_cxt_t's. This is helpful if you want to manually tweak the parameters in the user friendly context structs. */ void plx_txr_flush_hdrs(plx_texture_t * txr); /** Submit the polygon header for the given texture to the TA. If you specify a non-zero value for the flush parameter, it will call plx_txr_flush_hdrs() for you before sending the values. */ void plx_txr_send_hdr(plx_texture_t * txr, int list, int flush); __END_DECLS #endif /* __PARALLAX_TEXTURE */ <file_sep>/firmware/isoldr/loader/dev/sd/sd.c /** * Copyright (c) 2011-2023 SWAT <http://www.dc-swat.ru> * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <arch/types.h> #include <arch/cache.h> #include "spi.h" #include "sd.h" //#define SD_DEBUG 1 #define DISCARD_CRC16 1 #define MAX_RETRIES 500000 #define READ_RETRIES 50000 #define WRITE_RETRIES 150000 #define MAX_RETRY 10 /* MMC/SD command (in SPI) */ #define CMD(n) (n | 0x40) #define CMD0 (0x40+0) /* GO_IDLE_STATE */ #define CMD1 (0x40+1) /* SEND_OP_COND */ #define CMD8 (0x40+8) /* SEND_IF_COND */ #define CMD9 (0x40+9) /* SEND_CSD */ #define CMD10 (0x40+10) /* SEND_CID */ #define CMD12 (0x40+12) /* STOP_TRANSMISSION */ #define CMD16 (0x40+16) /* SET_BLOCKLEN */ #define CMD17 (0x40+17) /* READ_SINGLE_BLOCK */ #define CMD18 (0x40+18) /* READ_MULTIPLE_BLOCK */ #define CMD23 (0x40+23) /* SET_BLOCK_COUNT */ #define CMD24 (0x40+24) /* WRITE_BLOCK */ #define CMD25 (0x40+25) /* WRITE_MULTIPLE_BLOCK */ #define CMD41 (0x40+41) /* SEND_OP_COND (ACMD) */ #define CMD55 (0x40+55) /* APP_CMD */ #define CMD58 (0x40+58) /* READ_OCR */ #define CMD59 (0x40+59) /* CRC_ON_OFF */ /* Table/algorithm generated by pycrc. I really wanted to have a much smaller table here, but unfortunately, the code pycrc generated just did not work. */ static const uint8 crc7_table[256] = { 0x00, 0x12, 0x24, 0x36, 0x48, 0x5a, 0x6c, 0x7e, 0x90, 0x82, 0xb4, 0xa6, 0xd8, 0xca, 0xfc, 0xee, 0x32, 0x20, 0x16, 0x04, 0x7a, 0x68, 0x5e, 0x4c, 0xa2, 0xb0, 0x86, 0x94, 0xea, 0xf8, 0xce, 0xdc, 0x64, 0x76, 0x40, 0x52, 0x2c, 0x3e, 0x08, 0x1a, 0xf4, 0xe6, 0xd0, 0xc2, 0xbc, 0xae, 0x98, 0x8a, 0x56, 0x44, 0x72, 0x60, 0x1e, 0x0c, 0x3a, 0x28, 0xc6, 0xd4, 0xe2, 0xf0, 0x8e, 0x9c, 0xaa, 0xb8, 0xc8, 0xda, 0xec, 0xfe, 0x80, 0x92, 0xa4, 0xb6, 0x58, 0x4a, 0x7c, 0x6e, 0x10, 0x02, 0x34, 0x26, 0xfa, 0xe8, 0xde, 0xcc, 0xb2, 0xa0, 0x96, 0x84, 0x6a, 0x78, 0x4e, 0x5c, 0x22, 0x30, 0x06, 0x14, 0xac, 0xbe, 0x88, 0x9a, 0xe4, 0xf6, 0xc0, 0xd2, 0x3c, 0x2e, 0x18, 0x0a, 0x74, 0x66, 0x50, 0x42, 0x9e, 0x8c, 0xba, 0xa8, 0xd6, 0xc4, 0xf2, 0xe0, 0x0e, 0x1c, 0x2a, 0x38, 0x46, 0x54, 0x62, 0x70, 0x82, 0x90, 0xa6, 0xb4, 0xca, 0xd8, 0xee, 0xfc, 0x12, 0x00, 0x36, 0x24, 0x5a, 0x48, 0x7e, 0x6c, 0xb0, 0xa2, 0x94, 0x86, 0xf8, 0xea, 0xdc, 0xce, 0x20, 0x32, 0x04, 0x16, 0x68, 0x7a, 0x4c, 0x5e, 0xe6, 0xf4, 0xc2, 0xd0, 0xae, 0xbc, 0x8a, 0x98, 0x76, 0x64, 0x52, 0x40, 0x3e, 0x2c, 0x1a, 0x08, 0xd4, 0xc6, 0xf0, 0xe2, 0x9c, 0x8e, 0xb8, 0xaa, 0x44, 0x56, 0x60, 0x72, 0x0c, 0x1e, 0x28, 0x3a, 0x4a, 0x58, 0x6e, 0x7c, 0x02, 0x10, 0x26, 0x34, 0xda, 0xc8, 0xfe, 0xec, 0x92, 0x80, 0xb6, 0xa4, 0x78, 0x6a, 0x5c, 0x4e, 0x30, 0x22, 0x14, 0x06, 0xe8, 0xfa, 0xcc, 0xde, 0xa0, 0xb2, 0x84, 0x96, 0x2e, 0x3c, 0x0a, 0x18, 0x66, 0x74, 0x42, 0x50, 0xbe, 0xac, 0x9a, 0x88, 0xf6, 0xe4, 0xd2, 0xc0, 0x1c, 0x0e, 0x38, 0x2a, 0x54, 0x46, 0x70, 0x62, 0x8c, 0x9e, 0xa8, 0xba, 0xc4, 0xd6, 0xe0, 0xf2 }; uint8 sd_crc7(const uint8 *data, int size, uint8 crc) { int tbl_idx; while(size--) { tbl_idx = (crc ^ *data) & 0xff; crc = (crc7_table[tbl_idx] ^ (crc << 7)) & (0x7f << 1); data++; } return crc & (0x7f << 1); } #if _FS_READONLY == 0 || !defined(DISCARD_CRC16) uint16 sd_crc16(const uint8 *data, int size, uint16 start) { uint16 rv = start, tmp; while(size--) { tmp = (rv >> 8) ^ *data++; tmp ^= tmp >> 4; rv = (rv << 8) ^ (tmp << 12) ^ (tmp << 5) ^ tmp; } return rv; } #endif #ifndef NO_SD_INIT static int is_mmc = 0; #endif static int byte_mode = 0; static struct { uint32 block; size_t rcount; size_t count; uint8 *buff; } sds; #define SELECT() spi_cs_on() #define DESELECT() spi_cs_off() static uint8 wait_ready (void) { int i; uint8 res; (void)spi_sr_byte(0xFF); i = 0; do { res = spi_sr_byte(0xFF); i++; } while ((res != 0xFF) && i < MAX_RETRIES); return res; } static uint8 send_cmd ( uint8 cmd, /* Command byte */ uint32 arg /* Argument */ ) { uint8 n, res; uint8 cb[6]; if (wait_ready() != 0xFF) { #ifdef SD_DEBUG LOGFF("CMD 0x%02x wait ready error\n", cmd); #endif return 0xFF; } cb[0] = cmd; cb[1] = (uint8)(arg >> 24); cb[2] = (uint8)(arg >> 16); cb[3] = (uint8)(arg >> 8); cb[4] = (uint8)arg; cb[5] = sd_crc7(cb, 5, 0); /* Send command packet */ spi_send_byte(cmd); /* Command */ spi_send_byte(cb[1]); /* Argument[31..24] */ spi_send_byte(cb[2]); /* Argument[23..16] */ spi_send_byte(cb[3]); /* Argument[15..8] */ spi_send_byte(cb[4]); /* Argument[7..0] */ spi_send_byte(cb[5]); /* CRC7 */ /* Receive command response */ if (cmd == CMD12) (void)spi_rec_byte(); /* Skip a stuff byte when stop reading */ n = 20; /* Wait for a valid response in timeout of 10 attempts */ do { res = spi_rec_byte(); } while ((res & 0x80) && --n); #ifdef SD_DEBUG LOGFF("CMD 0x%02x response 0x%02x\n", cmd, res); #endif return res; /* Return with the response value */ } #ifndef NO_SD_INIT static uint8 send_slow_cmd ( uint8 cmd, /* Command byte */ uint32 arg /* Argument */ ) { uint8 n, res; uint8 cb[6]; int i; (void)spi_slow_sr_byte(0xff); i = 0; do { res = spi_slow_sr_byte(0xff); i++; } while ((res != 0xFF) && i < 100000); if (res != 0xff) { #ifdef SD_DEBUG LOGFF("CMD 0x%02x error\n", cmd); #endif return(0xff); } cb[0] = cmd; cb[1] = (uint8)(arg >> 24); cb[2] = (uint8)(arg >> 16); cb[3] = (uint8)(arg >> 8); cb[4] = (uint8)arg; cb[5] = sd_crc7(cb, 5, 0); /* Send command packet */ spi_slow_sr_byte(cmd); /* Command */ spi_slow_sr_byte(cb[1]); /* Argument[31..24] */ spi_slow_sr_byte(cb[2]); /* Argument[23..16] */ spi_slow_sr_byte(cb[3]); /* Argument[15..8] */ spi_slow_sr_byte(cb[4]); /* Argument[7..0] */ spi_slow_sr_byte(cb[5]); // CRC7 /* Receive command response */ if (cmd == CMD12) (void)spi_slow_sr_byte(0xff);/* Skip a stuff byte when stop reading */ n = 20; /* Wait for a valid response in timeout of 10 attempts */ do { res = spi_slow_sr_byte(0xff); } while ((res & 0x80) && --n); #ifdef SD_DEBUG LOGFF("CMD 0x%02x response 0x%02x\n", cmd, res); #endif return res; /* Return with the response value */ } int sd_init(void) { int i; uint8 n, ty = 0, ocr[4]; if(spi_init()) { return -1; } timer_spin_sleep_bios(20); SELECT(); /* 80 dummy clocks */ for (n = 10; n; n--) (void)spi_slow_sr_byte(0xff); if (send_slow_cmd(CMD0, 0) == 1) { /* Enter Idle state */ #ifdef SD_DEBUG LOGFF("Enter Idle state\n"); #endif timer_spin_sleep_bios(20); i = 0; if (send_slow_cmd(CMD8, 0x1AA) == 1) { /* SDC Ver2+ */ for (n = 0; n < 4; n++) ocr[n] = spi_slow_sr_byte(0xff); if (ocr[2] == 0x01 && ocr[3] == 0xAA) { /* The card can work at vdd range of 2.7-3.6V */ do { /* ACMD41 with HCS bit */ if (send_slow_cmd(CMD55, 0) <= 1 && send_slow_cmd(CMD41, 1UL << 30) == 0) break; ++i; } while (i < 300000); if (i < 300000 && send_slow_cmd(CMD58, 0) == 0) { /* Check CCS bit */ for (n = 0; n < 4; n++) ocr[n] = spi_slow_sr_byte(0xff); ty = (ocr[0] & 0x40) ? 6 : 2; } } } else { /* SDC Ver1 or MMC */ ty = (send_slow_cmd(CMD55, 0) <= 1 && send_slow_cmd(CMD41, 0) <= 1) ? 2 : 1; /* SDC : MMC */ do { if (ty == 2) { if (send_slow_cmd(CMD55, 0) <= 1 && send_slow_cmd(CMD41, 0) == 0) /* ACMD41 */ break; } else { if (send_slow_cmd(CMD1, 0) == 0) { /* CMD1 */ is_mmc = 1; break; } } ++i; } while (i < 300000); if (!(i < 300000) || send_slow_cmd(CMD16, 512) != 0) /* Select R/W block length */ ty = 0; } } send_slow_cmd(CMD59, 1); // crc check #ifdef SD_DEBUG LOGFF("card type = 0x%02x\n", ty & 0xff); #endif if(!(ty & 4)) { byte_mode = 1; } DESELECT(); (void)spi_slow_sr_byte(0xff); /* Idle (Release DO) */ if (ty) { /* Initialization succeded */ return 0; } /* Initialization failed */ // sd_shutdown(); return -1; } #else static int read_data(uint8 *buff, size_t len); int sd_init(void) { uint8 csd[16]; int rv = 0; if(spi_init()) { return -1; } // memset(&sds, 0, sizeof(sds)); SELECT(); if(send_cmd(CMD9, 0)) { rv = -1; goto out; } /* Read back the register */ if(read_data(csd, 16)) { rv = -1; goto out; } if((csd[0] >> 6) == 0) { byte_mode = 1; } else { byte_mode = 0; } out: DESELECT(); (void)spi_rec_byte(); return rv; } #endif /* int sd_shutdown(void) { if(!initted) return -1; SELECT(); wait_ready(); DESELECT(); (void)spi_rec_byte(); spi_shutdown(); initted = 0; return 0; } */ static int read_data ( uint8 *buff, /* Data buffer to store received data */ size_t len /* Byte count (must be even number) */ ) { uint8 token; int i = 0; #ifndef DISCARD_CRC16 uint16 crc, crc2; #endif do { /* Wait for data packet in timeout of 100ms */ token = spi_rec_byte(); } while (token == 0xFF && ++i < READ_RETRIES); if(token != 0xFE) { #ifdef SD_DEBUG LOGFF("not valid data token: %02x\n", token); #endif return -1; /* If not valid data token, return with error */ } spi_rec_data(buff, len); #ifndef DISCARD_CRC16 crc = (uint16)spi_rec_byte() << 8; crc |= (uint16)spi_rec_byte(); crc2 = sd_crc16(buff, len, 0); if(crc != crc2) { //errno = EIO; return -1; } #else (void)spi_rec_byte(); (void)spi_rec_byte(); #endif return 0; /* Return with success */ } int sd_read_blocks(uint32 block, size_t count, uint8 *buf, int blocked) { #ifdef SD_DEBUG LOGFF("block=%ld count=%d\n", block, count); #endif uint8 *p; int retry, cnt; if (byte_mode) block <<= 9; /* Convert to byte address if needed */ for (retry = 0; retry < MAX_RETRY; retry++) { p = buf; cnt = count; SELECT(); if (cnt == 1) { /* Single block read */ if ((send_cmd(CMD17, block) == 0) && !read_data(p, 512)) { cnt = 0; } } else { /* Multiple block read */ if (send_cmd(CMD18, block) == 0) { if(blocked) { do { if (read_data(p, 512)) break; p += 512; } while (--cnt); send_cmd(CMD12, 0); /* STOP_TRANSMISSION */ } else { sds.block = block; sds.count = sds.rcount = count; sds.buff = buf; DESELECT(); return 0; } } } DESELECT(); (void)spi_rec_byte(); /* Idle (Release DO) */ if (cnt == 0) break; } //#ifdef SD_DEBUG // LOGFF("retry = %d (MAX=%d) cnt = %d\n", retry, MAX_RETRY, cnt); //#endif if((retry >= MAX_RETRY || cnt > 0)) { //errno = EIO; return -1; } return 0; } #if _FS_READONLY == 0 static int write_data ( uint8 *buff, /* 512 byte data block to be transmitted */ uint8 token /* Data/Stop token */ ) { uint8 resp; uint16 crc; if (wait_ready() != 0xFF) return -1; spi_send_byte(token); /* Xmit data token */ if (token != 0xFD) { /* Is data token */ dcache_pref_range((uint32)buff, 512); crc = sd_crc16(buff, 512, 0); spi_send_data(buff, 512); spi_send_byte((uint8)(crc >> 8)); spi_send_byte((uint8)crc); resp = spi_rec_byte(); /* Reсeive data response */ if ((resp & 0x1F) != 0x05) { /* If not accepted, return with error */ #ifdef SD_DEBUG LOGFF("not accepted: %02x\n", resp); #endif //errno = EIO; return -1; } } return 0; } int sd_write_blocks(uint32 block, size_t count, const uint8 *buf, int blocked) { #ifdef SD_DEBUG LOGFF("block=%ld count=%d\n", block, count); #endif (void)blocked; uint8 cnt, *p; int retry; if (byte_mode) block <<= 9; /* Convert to byte address if needed */ for (retry = 0; retry < MAX_RETRY; retry++) { p = (uint8 *)buf; cnt = count; SELECT(); /* CS = L */ if (count == 1) { /* Single block write */ if ((send_cmd(CMD24, block) == 0) && !write_data(p, 0xFE)) cnt = 0; } else { /* Multiple block write */ // if (!is_mmc) { send_cmd(CMD55, 0); send_cmd(CMD23, cnt); /* ACMD23 */ // } if (send_cmd(CMD25, block) == 0) { do { if (write_data(p, 0xFC)) break; p += 512; } while (--cnt); if (write_data(0, 0xFD)) /* STOP_TRAN token */ cnt = 1; } } DESELECT(); /* CS = H */ (void)spi_rec_byte(); /* Idle (Release DO) */ if (cnt == 0) break; } //#ifdef SD_DEBUG // LOGFF("retry = %d (MAX=%d) cnt = %d\n", retry, MAX_RETRY, cnt); //#endif if((retry >= MAX_RETRY || cnt > 0)) { //errno = EIO; return -1; } return 0; } #endif static void sd_stop_trans() { send_cmd(CMD12, 0); /* STOP_TRANSMISSION */ DESELECT(); (void)spi_rec_byte(); /* Idle (Release DO) */ } /* For now only read supported (really write is not need) */ int sd_poll(size_t blocks) { if(sds.count > 0) { int cnt = sds.count > blocks ? blocks : sds.count; sds.count -= cnt; SELECT(); do { if(read_data(sds.buff, 512)) { DESELECT(); /* Restart the transfer from last position */ int rcnt = sds.rcount; sds.count += cnt; sds.block += (sds.rcount - sds.count); if(!sd_read_blocks(sds.block, sds.count, sds.buff, 0)) { sds.rcount = rcnt; return sds.rcount - sds.count; } else { sds.count = 0; sd_stop_trans(); return -1; } } sds.buff += 512; } while (--cnt); if(sds.count <= 0) { sd_stop_trans(); } else { DESELECT(); return sds.rcount - sds.count; } } return 0; } int sd_abort() { if(sds.count > 0) { SELECT(); sd_stop_trans(); } sds.count = 0; return 0; } #if _USE_MKFS && !_FS_READONLY uint64 sd_get_size(void) { uint8 csd[16]; int exponent; uint64 rv = 0; SELECT(); if(send_cmd(CMD9, 0)) { rv = (uint64)-1; //errno = EIO; goto out; } /* Read back the register */ if(read_data(csd, 16)) { rv = (uint64)-1; //errno = EIO; goto out; } /* Figure out what version of the CSD register we're looking at */ switch(csd[0] >> 6) { case 0: /* CSD version 1.0 (SD) C_SIZE is bits 62-73 of the CSD, C_SIZE_MULT is bits 47-49, READ_BL_LEN is bits 80-83. Card size is calculated as follows: (C_SIZE + 1) * 2^(C_SIZE_MULT + 2) * 2^(READ_BL_LEN) */ exponent = (csd[5] & 0x0F) + ((csd[9] & 0x03) << 1) + (csd[10] >> 7) + 2; rv = ((csd[8] >> 6) | (csd[7] << 2) | ((csd[6] & 0x03) << 10)) + 1; rv <<= exponent; break; case 1: /* CSD version 2.0 (SDHC/SDXC) C_SIZE is bits 48-69 of the CSD, card size is calculated as (C_SIZE + 1) * 512KiB */ rv = ((((uint64)csd[9]) | (uint64)(csd[8] << 8) | ((uint64)(csd[7] & 0x3F) << 16)) + 1) << 19; break; default: /* Unknown version, punt. */ rv = (uint64)-1; //errno = ENODEV; goto out; } out: DESELECT(); (void)spi_rec_byte(); return rv; } #endif <file_sep>/firmware/isoldr/loader/include/asic.h /** * DreamShell ISO Loader * ASIC interrupts handling * (c)2014-2020 SWAT <http://www.dc-swat.ru> * Based on Netplay VOOT code by <NAME> <<EMAIL>> */ #ifndef __ASIC_H__ #define __ASIC_H__ #include <main.h> #include <exception-lowlevel.h> #define ASIC_TABLE_SIZE 1 #define ASIC_BASE (0xa05f6900) #define ASIC_IRQ_STATUS (REGISTER(vuint32) (ASIC_BASE + 0x00)) #define ASIC_IRQ13_MASK (REGISTER(vuint32) (ASIC_BASE + 0x10)) #define ASIC_IRQ11_MASK (REGISTER(vuint32) (ASIC_BASE + 0x20)) #define ASIC_IRQ9_MASK (REGISTER(vuint32) (ASIC_BASE + 0x30)) #define ASIC_MASK_NRM_INT 0 #define ASIC_MASK_EXT_INT 1 #define ASIC_MASK_ERR_INT 2 /* Errors bit 31 = SH4 i/f: accessing to Inhibited area bit 30 = Reserved bit 29 = Reserved bit 28 = DDT i/f : Sort-DMA Command Error bit 27 = G2 : Time out in CPU accessing bit 26 = G2 : Dev-DMA Time out bit 25 = G2 : Ext-DMA2 Time out bit 24 = G2 : Ext-DMA1 Time out bit 23 = G2 : AICA-DMA Time out bit 22 = G2 : Dev-DMA over run bit 21 = G2 : Ext-DMA2 over run bit 20 = G2 : Ext-DMA1 over run bit 19 = G2 : AICA-DMA over run bit 18 = G2 : Dev-DMA Illegal Address set bit 17 = G2 : Ext-DMA2 Illegal Address set bit 16 = G2 : Ext-DMA1 Illegal Address set bit 15 = G2 : AICA-DMA Illegal Address set bit 14 = G1 : ROM/FLASH access at GD-DMA bit 13 = G1 : GD-DMA over run bit 12 = G1 : Illegal Address set bit 11 = MAPLE : Illegal command bit 10 = MAPLE : Write FIFO over flow bit 9 = MAPLE : DMA over run bit 8 = MAPLE : Illegal Address set bit 7 = PVRIF : DMA over run bit 6 = PVRIF : Illegal Address set bit 5 = TA : FIFO Overflow bit 4 = TA : Illegal Parameter bit 3 = TA : Object List Pointer Overflow bit 2 = TA : ISP/TSP Parameter Overflow bit 1 = RENDER : Hazard Processing of Strip Buffer bit 0 = RENDER : ISP out of Cache(Buffer over flow) */ /* Interrupts bit 31 = Error interrupt ‘OR’ status bit 30 = G1,G2,External interrupt ‘OR’ status bit 21 = End of Transferring interrupt : Punch Through List bit 20 = End of DMA interrupt : Sort-DMA (Transferring for alpha sorting) bit 19 = End of DMA interrupt : ch2-DMA bit 18 = End of DMA interrupt : Dev-DMA(Development tool DMA) bit 17 = End of DMA interrupt : Ext-DMA2(External 2) bit 16 = End of DMA interrupt : Ext-DMA1(External 1) bit 15 = End of DMA interrupt : AICA-DMA bit 14 = End of DMA interrupt : GD-DMA bit 13 = Maple V blank over interrupt bit 12 = End of DMA interrupt : Maple-DMA bit 11 = End of DMA interrupt : PVR-DMA bit 10 = End of Transferring interrupt : Translucent Modifier Volume List bit 9 = End of Transferring interrupt : Translucent List bit 8 = End of Transferring interrupt : Opaque Modifier Volume List bit 7 = End of Transferring interrupt : Opaque List bit 6 = End of Transferring interrupt : YUV bit 5 = H Blank-in interrupt bit 4 = V Blank-out interrupt bit 3 = V Blank-in interrupt bit 2 = End of Render interrupt : TSP bit 1 = End of Render interrupt : ISP bit 0 = End of Render interrupt : Video */ #define ASIC_NRM_TADONE 0x04 /* Rendering complete */ #define ASIC_NRM_RASTER_BOTTOM 0x08 /* Bottom raster event */ #define ASIC_NRM_RASTER_TOP 0x10 /* Top raster event */ #define ASIC_NRM_VSYNC 0x20 /* Vsync event */ #define ASIC_NRM_OPAQUE_POLY 0x080 /* Opaque polygon binning complete */ #define ASIC_NRM_OPAQUE_MOD 0x100 /* Opaque modifier binning complete */ #define ASIC_NRM_TRANS_POLY 0x200 /* Transparent polygon binning complete */ #define ASIC_NRM_TRANS_MOD 0x400 /* Transparent modifier binning complete */ #define ASIC_NRM_MAPLE_DMA 0x01000 /* Maple DMA complete */ #define ASIC_NRM_MAPLE_ERROR 0x02000 /* Maple V blank over interrupt */ #define ASIC_NRM_GD_DMA 0x04000 /* GD-ROM DMA complete */ #define ASIC_NRM_AICA_DMA 0x08000 /* AICA DMA complete */ #define ASIC_NRM_EXT1_DMA 0x10000 /* External DMA 1 complete */ #define ASIC_NRM_EXT2_DMA 0x20000 /* External DMA 2 complete */ #define ASIC_NRM_DEV_DMA 0x40000 /* Dev DMA complete */ #define ASIC_NRM_PVR_DMA 0x80000 /* PVR (CH2) DMA complete */ #define ASIC_NRM_SORT_DMA 0x100000 /* Sort-DMA complete */ #define ASIC_NRM_PUNCHPOLY 0x200000 /* Punchthrough polygon binning complete */ #define ASIC_NRM_EXTERNAL 0x40000000 /* There are external interrupts */ #define ASIC_NRM_ERROR 0x80000000 /* There are error interrupts */ #define ASIC_EXT_GD_CMD 0x01 /* GD-ROM command status */ #define ASIC_EXT_AICA 0x02 /* AICA */ #define ASIC_EXT_MODEM 0x04 /* Modem ? */ #define ASIC_EXT_PCI 0x08 /* Expansion port (PCI Bridge) */ #define ASIC_ERR_G1DMA_ILLEGAL 0x01000 #define ASIC_ERR_G1DMA_OVERRUN 0x02000 #define ASIC_ERR_G1DMA_ROM_FLASH 0x04000 typedef void *(*asic_handler_f) (void *, register_stack *, void *); typedef struct { uint32 mask[3]; uint32 irq; asic_handler_f handler; int clear_irq; } asic_lookup_table_entry; typedef struct { int inited; #ifndef NO_ASIC_LT asic_lookup_table_entry table[ASIC_TABLE_SIZE]; #endif } asic_lookup_table; void asic_init(void); int asic_add_handler(const asic_lookup_table_entry *new_entry, asic_handler_f *parent_handler, int enable_irq); void asic_enable_irq(const asic_lookup_table_entry *entry); #ifdef DEV_TYPE_IDE /* Initialize DMA interrupt handling for IDE and GD */ int g1_dma_init_irq(); #endif int irq_disabled(); #endif <file_sep>/applications/vmu_manager/modules/module.c /* DreamShell ##version## module.c - VMU Manager app module Copyright (C)2014-2015 megavolt85 */ #include "ds.h" #include "fs_vmd.h" DEFAULT_MODULE_EXPORTS(app_vmu_manager); #define MAPLE_FUNC_GUN 0x81000000 #define PACK_NYBBLE_RGB565(nybble) ((((nybble & 0x0f00)>>8)*2)<<11) + ((((nybble & 0x00f0)>>4)*4)<<5) + ((((nybble & 0x000f)>>0)*2)<<0) kthread_t * t0; #define VMU_ICON_WIDTH 32 #define VMU_ICON_HEIGHT 32 #define VMU_ICON_SIZE (VMU_ICON_WIDTH * VMU_ICON_HEIGHT * 2) #define LEFT_FM 0 #define RIGHT_FM 1 void VMU_Manager_ItemContextClick(dirent_fm_t *fm_ent); int VMU_Manager_Dump(GUI_Widget *widget); void VMU_Manager_addfileman(GUI_Widget *widget); static struct { App_t* m_App; GUI_Widget *pages; GUI_Widget *button_dump; GUI_Widget *button_home; GUI_Widget *cd_c; GUI_Widget *sd_c; GUI_Widget *hdd_c; GUI_Widget *pc_c; GUI_Widget *format_c; GUI_Widget *dst_vmu; GUI_Widget *vmu[4][2]; GUI_Widget *img_cont[4]; GUI_Widget *name_device; GUI_Widget *free_mem; GUI_Widget *filebrowser; GUI_Widget *filebrowser2; GUI_Widget *sicon; GUI_Widget *save_name; GUI_Widget *save_size; GUI_Widget *save_descshort; GUI_Widget *save_desclong; GUI_Widget *progressbar_container; GUI_Widget *progressbar; GUI_Widget *folder_name; GUI_Surface *progres_img; GUI_Surface *progres_img_b; GUI_Surface *confirmimg[3]; GUI_Surface *m_ItemNormal; GUI_Surface *m_ItemSelected; GUI_Surface *m_ItemNormal2; GUI_Surface *m_ItemSelected2; GUI_Surface *logo; GUI_Surface *dump_icon; GUI_Surface *vmuicon; SDL_Surface *vmu_icon; GUI_Surface *controller; GUI_Surface *lightgun; GUI_Surface *keyboard; GUI_Surface *mouse; GUI_Widget *vmu_page; GUI_Widget *vmu_container; GUI_Widget *confirm; GUI_Widget *image_confirm; GUI_Widget *confirm_text; GUI_Widget *drection; volatile int thread_kill; int vmu_freeblock , vmu_freeblock2 , direction_flag; const char* home_path; char* m_SelectedFile; char* m_SelectedPath; char desc_short[17]; char desc_long[33]; } self; static struct { uint32 checksum; char title[32]; char creator[32]; char date[8]; char version[2]; char numfiles[2]; char source[8]; char name[12]; uint16 type; char reserved[2]; uint32 size; } vmi_t; static struct { char type[1]; uint8 copyprotect; uint16 firstblock; char name[12]; uint16 year; uint8 month; uint8 day; uint8 hours; uint8 mins; uint8 secs; char weekday[1]; uint16 size; // size in blocks uint16 headeroffset; uint32 unused; uint8 vmsheader[1024]; } dci_t; static void* vmu_dev(const char* path){ maple_device_t *device = NULL; if (strncmp(path,"/vmu/A1",7) == 0) { device = maple_enum_dev(0, 1); }else if (strncmp(path,"/vmu/A2",7) == 0) { device = maple_enum_dev(0, 2); }else if (strncmp(path,"/vmu/B1",7) == 0) { device = maple_enum_dev(1, 1); }else if (strncmp(path,"/vmu/B2",7) == 0) { device = maple_enum_dev(1, 2); }else if (strncmp(path,"/vmu/C1",7) == 0) { device = maple_enum_dev(2, 1); }else if (strncmp(path,"/vmu/C2",7) == 0) { device = maple_enum_dev(2, 2); }else if (strncmp(path,"/vmu/D1",7) == 0) { device = maple_enum_dev(3, 1); }else if (strncmp(path,"/vmu/D2",7) == 0) { device = maple_enum_dev(3, 2); }else{ return NULL; } return device; } static void* rmdir_recursive(const char* folder){ file_t d; dirent_t *de; char dst[NAME_MAX]; d = fs_open(folder, O_DIR); while ((de = fs_readdir(d))){ if (strcmp(de->name ,".") == 0 || strcmp(de->name ,"..") == 0) continue; sprintf(dst,"%s/%s",folder,de->name); thd_sleep(200); if (de->attr == 4096) rmdir_recursive(dst); else fs_unlink (dst); } fs_close(d); fs_rmdir (folder); thd_sleep(200); return NULL; } static void free_blocks(const char *path , int n) { maple_device_t *vmucur = NULL; if((vmucur = vmu_dev(path)) == NULL) return; if(n == 0){ self.vmu_freeblock = vmufs_free_blocks(vmucur); }else self.vmu_freeblock2 = vmufs_free_blocks(vmucur); return; } static void addbutton() { GUI_WidgetSetEnabled(self.button_dump, 0); GUI_ContainerRemove(self.vmu_page, self.filebrowser2); if(!DirExists("/pc")) GUI_WidgetSetEnabled(self.pc_c, 0); if(!DirExists("/sd")) GUI_WidgetSetEnabled(self.sd_c, 0); if(!DirExists("/ide")) GUI_WidgetSetEnabled(self.hdd_c, 0); self.direction_flag = 0; GUI_ContainerAdd(self.vmu_page, self.sd_c); GUI_ContainerAdd(self.vmu_page, self.hdd_c); GUI_ContainerAdd(self.vmu_page, self.cd_c); GUI_ContainerAdd(self.vmu_page, self.pc_c); GUI_ContainerAdd(self.vmu_page, self.dst_vmu); GUI_ContainerAdd(self.vmu_page, self.format_c); GUI_WidgetMarkChanged(self.m_App->body); } static void disable_high(int fm) { int i; GUI_Widget *panel, *w; if(fm == RIGHT_FM){ panel = GUI_FileManagerGetItemPanel(self.filebrowser2); for(i = 0; i < GUI_ContainerGetCount(panel); i++) { w = GUI_FileManagerGetItem(self.filebrowser2, i); GUI_ButtonSetNormalImage(w, self.m_ItemNormal2); GUI_ButtonSetHighlightImage(w, self.m_ItemNormal2); } }else{ panel = GUI_FileManagerGetItemPanel(self.filebrowser); for(i = 0; i < GUI_ContainerGetCount(panel); i++) { w = GUI_FileManagerGetItem(self.filebrowser, i); GUI_ButtonSetNormalImage(w, self.m_ItemNormal); GUI_ButtonSetHighlightImage(w, self.m_ItemNormal); } } } static void clr_statusbar() { GUI_PictureSetImage(self.sicon, self.logo); GUI_LabelSetText(self.save_name, " "); GUI_LabelSetText(self.save_size, " "); GUI_LabelSetText(self.save_descshort, " "); GUI_LabelSetText(self.save_desclong, " "); return; } static int Confirm_Window() { maple_device_t *cont; cont_state_t *state; int y, flag = CMD_ERROR; SDL_GetMouseState(NULL, &y); SDL_WarpMouse(0,0); /* GUI_WidgetSetEnabled(self.filebrowser, 0); GUI_WidgetSetEnabled(self.filebrowser2, 0); GUI_WidgetSetEnabled(self.sd_c, 0); GUI_WidgetSetEnabled(self.cd_c, 0); GUI_WidgetSetEnabled(self.hdd_c, 0); GUI_WidgetSetEnabled(self.pc_c, 0); GUI_WidgetSetEnabled(self.pc_c, 0); GUI_WidgetSetEnabled(self.format_c, 0); GUI_WidgetSetEnabled(self.dst_vmu, 0); */ GUI_ContainerAdd(self.vmu_page, self.confirm); GUI_WidgetMarkChanged(self.vmu_page); LockVideo(); while(1) { if(!(cont = maple_enum_type(0, MAPLE_FUNC_MOUSE))){ cont = maple_enum_type(0, MAPLE_FUNC_CONTROLLER); } if(!cont) continue; state = (cont_state_t *)maple_dev_status(cont); if(!state) continue; if(state->buttons & CONT_A) { flag = CMD_OK; break; } else if(state->buttons & CONT_B) { break; } else if(state->buttons & CONT_X){ flag = CMD_NO_ARG; break; } else thd_pass(); } GUI_ContainerRemove(self.vmu_page, self.confirm); /* GUI_WidgetSetEnabled(self.filebrowser, 1); GUI_WidgetSetEnabled(self.filebrowser2, 1); if(DirExists("/pc")) GUI_WidgetSetEnabled(self.pc_c, 1); if(DirExists("/sd")) GUI_WidgetSetEnabled(self.sd_c, 1); GUI_WidgetSetEnabled(self.cd_c, 1); if(DirExists("/ide")) GUI_WidgetSetEnabled(self.hdd_c, 1); GUI_WidgetSetEnabled(self.format_c, 1); GUI_WidgetSetEnabled(self.dst_vmu, 1); */ GUI_WidgetMarkChanged(self.m_App->body); if (y > 320) y = 300; SDL_WarpMouse(270,y); UnlockVideo(); return flag; } static void *maple_scan() { self.thread_kill = 0; int a, b; maple_device_t *maple_dev[4][3]; while(1) { for(a=0;a<4;a++){ maple_dev[a][0] = maple_enum_dev(a, 0); if(maple_dev[a][0] == NULL) { GUI_ProgressBarSetPosition(self.img_cont[a], 0.0); GUI_WidgetSetEnabled(self.vmu[a][0], 0); GUI_WidgetSetEnabled(self.vmu[a][1], 0); continue; } switch(maple_dev[a][0]->info.functions) { case MAPLE_FUNC_CONTROLLER: GUI_ProgressBarSetImage2(self.img_cont[a], self.controller); GUI_ProgressBarSetPosition(self.img_cont[a], 1.0); for(b=1;b<3;b++){ maple_dev[a][b] = maple_enum_dev(a, b); if (maple_dev[a][b] == NULL || !(maple_dev[a][b]->info.functions & MAPLE_FUNC_MEMCARD)) { GUI_WidgetSetEnabled(self.vmu[a][b-1], 0); } else { GUI_WidgetSetEnabled(self.vmu[a][b-1], 1); } } break; case MAPLE_FUNC_GUN: case MAPLE_FUNC_LIGHTGUN: case MAPLE_FUNC_ARGUN: GUI_ProgressBarSetImage2(self.img_cont[a], self.lightgun); GUI_ProgressBarSetPosition(self.img_cont[a], 1.0); for(b=1;b<3;b++){ maple_dev[a][b] = maple_enum_dev(a, b); if (maple_dev[a][b] == NULL || !(maple_dev[a][b]->info.functions & MAPLE_FUNC_MEMCARD)) { GUI_WidgetSetEnabled(self.vmu[a][b-1], 0); } else { GUI_WidgetSetEnabled(self.vmu[a][b-1], 1); } } break; case MAPLE_FUNC_KEYBOARD: GUI_ProgressBarSetImage2(self.img_cont[a], self.keyboard); GUI_ProgressBarSetPosition(self.img_cont[a], 1.0); break; case MAPLE_FUNC_MOUSE: GUI_ProgressBarSetImage2(self.img_cont[a], self.mouse); GUI_ProgressBarSetPosition(self.img_cont[a], 1.0); break; default: GUI_ProgressBarSetPosition(self.img_cont[a], 0.0); GUI_WidgetSetEnabled(self.vmu[a][0], 0); GUI_WidgetSetEnabled(self.vmu[a][1], 0); } } if (self.thread_kill != 0 || GUI_CardStackGetIndex(self.pages) != 0) break; } return NULL; } static void* GetElement(const char *name, ListItemType type, int from) { Item_t *item; item = listGetItemByName(from ? self.m_App->elements : self.m_App->resources, name); if(item != NULL && item->type == type) { return item->data; } dbgio_printf("Resource not found: %s\n", name); return NULL; } void Vmu_Manager_Init(App_t* app) { self.m_App = app; if (self.m_App != 0){ int x,y; self.direction_flag = 0; self.pages = (GUI_Widget *) GetElement("pages", LIST_ITEM_GUI_WIDGET, 1); self.button_home = (GUI_Widget *) GetElement("home_but", LIST_ITEM_GUI_WIDGET, 1); self.cd_c = (GUI_Widget *) GetElement("/cd", LIST_ITEM_GUI_WIDGET, 1); self.sd_c = (GUI_Widget *) GetElement("/sd/vmu", LIST_ITEM_GUI_WIDGET, 1); self.hdd_c = (GUI_Widget *) GetElement("/ide/vmu", LIST_ITEM_GUI_WIDGET, 1); self.pc_c = (GUI_Widget *) GetElement("/pc", LIST_ITEM_GUI_WIDGET, 1); self.format_c = (GUI_Widget *) GetElement("format-c", LIST_ITEM_GUI_WIDGET, 1); self.dst_vmu = (GUI_Widget *) GetElement("dst-vmu", LIST_ITEM_GUI_WIDGET, 1); self.vmu_container = (GUI_Widget *) GetElement("vmu-container", LIST_ITEM_GUI_WIDGET, 1); self.folder_name = (GUI_Widget *) GetElement("folder-name", LIST_ITEM_GUI_WIDGET, 1); self.vmu[0][0] = (GUI_Widget *) GetElement("A1", LIST_ITEM_GUI_WIDGET, 1); self.vmu[0][1] = (GUI_Widget *) GetElement("A2", LIST_ITEM_GUI_WIDGET, 1); self.vmu[1][0] = (GUI_Widget *) GetElement("B1", LIST_ITEM_GUI_WIDGET, 1); self.vmu[1][1] = (GUI_Widget *) GetElement("B2", LIST_ITEM_GUI_WIDGET, 1); self.vmu[2][0] = (GUI_Widget *) GetElement("C1", LIST_ITEM_GUI_WIDGET, 1); self.vmu[2][1] = (GUI_Widget *) GetElement("C2", LIST_ITEM_GUI_WIDGET, 1); self.vmu[3][0] = (GUI_Widget *) GetElement("D1", LIST_ITEM_GUI_WIDGET, 1); self.vmu[3][1] = (GUI_Widget *) GetElement("D2", LIST_ITEM_GUI_WIDGET, 1); self.img_cont[0] = (GUI_Widget *) GetElement("contA", LIST_ITEM_GUI_WIDGET, 1); self.img_cont[1] = (GUI_Widget *) GetElement("contB", LIST_ITEM_GUI_WIDGET, 1); self.img_cont[2] = (GUI_Widget *) GetElement("contC", LIST_ITEM_GUI_WIDGET, 1); self.img_cont[3] = (GUI_Widget *) GetElement("contD", LIST_ITEM_GUI_WIDGET, 1); self.save_name = (GUI_Widget *) GetElement("save-name", LIST_ITEM_GUI_WIDGET, 1); self.save_size = (GUI_Widget *) GetElement("save-size", LIST_ITEM_GUI_WIDGET, 1); self.save_descshort = (GUI_Widget *) GetElement("desc-short", LIST_ITEM_GUI_WIDGET, 1); self.save_desclong = (GUI_Widget *) GetElement("desc-long", LIST_ITEM_GUI_WIDGET, 1); self.name_device = (GUI_Widget *) GetElement("name-device", LIST_ITEM_GUI_WIDGET, 1); self.free_mem = (GUI_Widget *) GetElement("free-mem", LIST_ITEM_GUI_WIDGET, 1); self.sicon = (GUI_Widget *) GetElement("vmu-icon", LIST_ITEM_GUI_WIDGET, 1); self.button_dump = (GUI_Widget *) GetElement("dump-button", LIST_ITEM_GUI_WIDGET, 1); self.filebrowser = (GUI_Widget *) GetElement("file_browser", LIST_ITEM_GUI_WIDGET, 1); self.filebrowser2 = (GUI_Widget *) GetElement("file_browser2", LIST_ITEM_GUI_WIDGET, 1); self.m_ItemNormal = (GUI_Surface *) GetElement("item-normal", LIST_ITEM_GUI_SURFACE, 0); self.m_ItemSelected = (GUI_Surface *) GetElement("item-selected", LIST_ITEM_GUI_SURFACE, 0); self.m_ItemNormal2 = (GUI_Surface *) GetElement("item-normal2", LIST_ITEM_GUI_SURFACE, 0); self.m_ItemSelected2 = (GUI_Surface *) GetElement("item-selected2", LIST_ITEM_GUI_SURFACE, 0); self.logo = (GUI_Surface *) GetElement("logo", LIST_ITEM_GUI_SURFACE, 0); self.dump_icon = (GUI_Surface *) GetElement("dump_icon", LIST_ITEM_GUI_SURFACE, 0); self.controller = (GUI_Surface *) GetElement("controller", LIST_ITEM_GUI_SURFACE, 0); self.lightgun = (GUI_Surface *) GetElement("lightgun", LIST_ITEM_GUI_SURFACE, 0); self.keyboard = (GUI_Surface *) GetElement("keyboard", LIST_ITEM_GUI_SURFACE, 0); self.mouse = (GUI_Surface *) GetElement("mouse", LIST_ITEM_GUI_SURFACE, 0); self.progres_img = (GUI_Surface *) GetElement("progressbar", LIST_ITEM_GUI_SURFACE, 0); self.progres_img_b = (GUI_Surface *) GetElement("progressbar_back", LIST_ITEM_GUI_SURFACE, 0); self.confirmimg[0] = (GUI_Surface *) GetElement("confirmimg", LIST_ITEM_GUI_SURFACE, 0); self.confirmimg[1] = (GUI_Surface *) GetElement("confirmimg0", LIST_ITEM_GUI_SURFACE, 0); self.image_confirm = (GUI_Widget *) GetElement("image-confirm", LIST_ITEM_GUI_WIDGET, 1); self.confirm = (GUI_Widget *) GetElement("confirm", LIST_ITEM_GUI_WIDGET, 1); self.confirm_text = (GUI_Widget *) GetElement("confirm-text", LIST_ITEM_GUI_WIDGET, 1); self.drection = (GUI_Widget *) GetElement("drection", LIST_ITEM_GUI_WIDGET, 1); self.progressbar = (GUI_Widget *) GetElement("progressbar", LIST_ITEM_GUI_WIDGET, 1); self.progressbar_container = (GUI_Widget *) GetElement("progressbar_container", LIST_ITEM_GUI_WIDGET, 1); Item_t *i; i = listGetItemByName(self.m_App->elements, "vmu_page"); self.vmu_page = (GUI_Widget*) i->data; GUI_FileManagerSetItemContextClick(self.filebrowser, (GUI_CallbackFunction*) VMU_Manager_ItemContextClick); GUI_FileManagerSetItemContextClick(self.filebrowser2, (GUI_CallbackFunction*) VMU_Manager_ItemContextClick); GUI_ContainerRemove(self.vmu_page, self.progressbar_container); GUI_ContainerRemove(self.vmu_page, self.filebrowser2); GUI_ContainerRemove(self.vmu_page, self.confirm); if(!DirExists("/pc")) GUI_WidgetSetEnabled(self.pc_c, 0); if(!DirExists("/sd")) GUI_WidgetSetEnabled(self.sd_c, 0); if(!DirExists("/ide")) GUI_WidgetSetEnabled(self.hdd_c, 0); GUI_WidgetSetEnabled(self.button_dump, 0); for(x=0;x<4;x++) { for(y=0;y<2;y++) { GUI_WidgetSetEnabled(self.vmu[x][y], 0); } } /* Disabling scrollbar on filemanager */ for(x = 3; x > 0; x--) { GUI_Widget *w = GUI_ContainerGetChild(self.filebrowser, x); GUI_ContainerRemove(self.filebrowser, w); } /* Disabling scrollbar on filemanager2 */ for(x = 3; x > 0; x--) { GUI_Widget *w = GUI_ContainerGetChild(self.filebrowser2, x); GUI_ContainerRemove(self.filebrowser, w); } if (GUI_CardStackGetIndex(self.pages) == 0) GUI_WidgetSetEnabled(self.button_home, 0); t0 = thd_create(1, maple_scan, NULL); dbgio_printf("APP Init\n"); fs_vmd_init(); } else dbgio_printf("DS_ERROR: Can't find app named: %s\n", "Vmu Manager"); } void VMU_Manager_EnableMainPage() { self.thread_kill = 1; int x,y; for(x=0;x<4;x++) { for(y=0;y<2;y++) { if(GUI_ContainerContains(self.vmu_container, self.vmu[x][y]) == 0){ GUI_ContainerAdd(self.vmu_container,self.vmu[x][y]); } } } self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; disable_high(RIGHT_FM); disable_high(LEFT_FM); clr_statusbar(); self.direction_flag = 0; GUI_LabelSetText(self.drection, "SELECT SOURCE VMU"); GUI_WidgetSetEnabled(self.button_home, 0); ScreenFadeOut(); thd_sleep(200); GUI_CardStackShowIndex(self.pages, 0); ScreenFadeIn(); t0 = thd_create(1, maple_scan, NULL); } void VMU_Manager_vmu(GUI_Widget *widget) { char vpath[NAME_MAX]; GUI_WidgetSetEnabled(self.button_home, 1); ScreenFadeOut(); thd_sleep(200); GUI_CardStackShowIndex(self.pages, 1); snprintf(vpath, NAME_MAX, "/vmu/%s", GUI_ObjectGetName(widget)); if(self.direction_flag == 0){ GUI_FileManagerSetPath(self.filebrowser, vpath); GUI_ContainerRemove(self.vmu_container, widget); addbutton(); }else{ GUI_WidgetSetEnabled(self.button_dump, 0); VMU_Manager_addfileman(widget); } ScreenFadeIn(); } void VMU_Manager_info_bar(GUI_Widget *widget) { char str[16], path[8]; GUI_LabelSetText(self.name_device, GUI_ObjectGetName( (GUI_Object *)widget)); sprintf(path,"/vmu/%s", GUI_ObjectGetName((GUI_Object *) widget)); if(self.direction_flag == 0){ self.vmu_freeblock = vmufs_free_blocks(vmu_dev(path)); sprintf (str, "%s %d %s", "free", self.vmu_freeblock, "blocks"); }else{ self.vmu_freeblock2 = vmufs_free_blocks(vmu_dev(path)); sprintf (str, "%s %d %s", "free", self.vmu_freeblock2, "blocks"); } if (self.vmu_freeblock >= 0) GUI_LabelSetText(self.free_mem, str); } void VMU_Manager_info_bar_clr(GUI_Widget *widget) { GUI_LabelSetText(self.name_device, ""); GUI_LabelSetText(self.free_mem, ""); #ifdef VMDEBUR dbgio_printf("onmouseout"); #endif } void VMU_Manager_Exit(GUI_Widget *widget) { fs_vmd_shutdown(); self.thread_kill = 1; thd_join(t0, NULL); (void)widget; self.m_App = NULL; self.m_App = GetAppByName("Main"); OpenApp(self.m_App, NULL); } void VMU_Manager_ItemClick(dirent_fm_t *fm_ent) { dirent_t *ent = &fm_ent->ent; file_t f; int xx, yy; int flag = CMD_ERROR; int flag_type = 0; // vms 0 ; vmd 1 ; vmi 2 ; dci 3 uint8 nyb; char tmp[64]; char src[NAME_MAX]; char dst[NAME_MAX]; char size[64]; char text[1024]; uint16 *tmpbuf = NULL; uint8 buf[1024]; uint8 icon[512]; uint16 pal[16]; GUI_Widget *fmw = (GUI_Widget*)fm_ent->obj; int i; GUI_Widget *panel, *w; if(ent->attr == O_DIR){ // This is FOLDER if (strcmp(GUI_ObjectGetName(fmw), "file_browser") == 0 && fm_ent->index == 0) { GUI_ContainerContains(self.vmu_page, self.filebrowser2); self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; disable_high(RIGHT_FM); disable_high(LEFT_FM); clr_statusbar(); GUI_FileManagerScan(self.filebrowser); return; } if(fm_ent->index == 0 && strlen(self.home_path) >= strlen(GUI_FileManagerGetPath(self.filebrowser2))){ self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; self.home_path = NULL; clr_statusbar(); addbutton(); return; } disable_high(RIGHT_FM); disable_high(LEFT_FM); self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; clr_statusbar(); GUI_FileManagerChangeDir(fmw, ent->name, ent->size); return; } if(strcmp(self.m_SelectedFile,ent->name) == 0 && strcmp(self.m_SelectedPath,GUI_FileManagerGetPath(fmw)) == 0){ // file selected if((ent->size/512) == 256 && (strcmp(GUI_ObjectGetName(fmw), "file_browser2") == 0 && ent->name[strlen(ent->name) - 3] == 'v' && ent->name[strlen(ent->name) - 2] == 'm' && ent->name[strlen(ent->name) - 1] == 'd')&& strcmp(self.m_SelectedFile,ent->name) == 0 && strcmp(self.m_SelectedPath,GUI_FileManagerGetPath(fmw)) == 0){ /* RESTORE DUMP*/ GUI_LabelSetText(self.confirm_text, "Restore dump. WARNING all data on VMU lost"); GUI_PictureSetImage(self.image_confirm, self.confirmimg[1]); flag = Confirm_Window(); GUI_PictureSetImage(self.image_confirm, self.confirmimg[0]); if (flag == CMD_OK){ if ( VMU_Manager_Dump(GUI_FileManagerGetItem(self.filebrowser2, fm_ent->index)) == CMD_OK){ free_blocks(GUI_FileManagerGetPath(self.filebrowser) , 0); GUI_FileManagerScan(self.filebrowser); } } else if (flag == CMD_NO_ARG){ self.home_path = (const char *) "/vmd"; sprintf(src,"%s/%s",GUI_FileManagerGetPath(fmw),ent->name); fs_vmd_vmdfile(src); GUI_WidgetSetEnabled(self.button_dump, 0); GUI_FileManagerSetPath(self.filebrowser2, self.home_path); GUI_FileManagerScan(self.filebrowser2); } self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; clr_statusbar(); return; } else if(strcmp(self.m_SelectedFile,ent->name) == 0 && strcmp(self.m_SelectedPath,GUI_FileManagerGetPath(fmw)) == 0 && GUI_ContainerContains(self.vmu_page, self.filebrowser2) == 1){ // copy file if(strcmp(GUI_ObjectGetName(fmw), "file_browser2") == 0){ // copy file to vmu if ((ent->name[strlen(ent->name) - 3] == 'v' || ent->name[strlen(ent->name) - 3] == 'V') && (ent->name[strlen(ent->name) - 2] == 'm' || ent->name[strlen(ent->name) - 2] == 'M') && (ent->name[strlen(ent->name) - 1] == 'i' || ent->name[strlen(ent->name) - 1] == 'I')){ if((vmi_t.size/512) > self.vmu_freeblock){ return; } sprintf(src, "%s/%1.8s.vms", GUI_FileManagerGetPath(fmw), vmi_t.source); if(!FileExists(src)) sprintf(src, "%s/%1.8s.VMS", GUI_FileManagerGetPath(fmw), vmi_t.source); if(!FileExists(src)){ self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; disable_high(RIGHT_FM); clr_statusbar(); return; } sprintf(dst, "%s/%12.12s", GUI_FileManagerGetPath(self.filebrowser), vmi_t.name); } else if ((ent->name[strlen(ent->name) - 3] == 'd' || ent->name[strlen(ent->name) - 3] == 'D') && (ent->name[strlen(ent->name) - 2] == 'c' || ent->name[strlen(ent->name) - 2] == 'C') && (ent->name[strlen(ent->name) - 1] == 'i' || ent->name[strlen(ent->name) - 1] == 'I')){ if(((ent->size-32)/512) > self.vmu_freeblock){ return; } sprintf(src, "%s/%s", GUI_FileManagerGetPath(fmw), ent->name); sprintf(dst, "%s/%12.12s", GUI_FileManagerGetPath(self.filebrowser), dci_t.name); flag_type = 3; } else{ if((ent->size/512) > self.vmu_freeblock){ return; } sprintf(src, "%s/%s", GUI_FileManagerGetPath(fmw), ent->name); sprintf(dst, "%s/%12.12s", GUI_FileManagerGetPath(self.filebrowser), ent->name); } if (FileExists(dst) != 0){ sprintf(text, "Overwrite %s", dst); GUI_LabelSetText(self.confirm_text, text); flag = Confirm_Window(); } else flag = CMD_OK; if (flag == CMD_OK){ GUI_ProgressBarSetImage1(self.progressbar, self.progres_img_b); GUI_ProgressBarSetImage2(self.progressbar, self.progres_img); GUI_ProgressBarSetPosition(self.progressbar, 1.0); GUI_ContainerAdd(self.vmu_page, self.progressbar_container); GUI_WidgetMarkChanged(self.vmu_page); LockVideo(); #ifdef VMDEBUG dbgio_printf("src: %s\ndst: %s\n", src, dst); thd_sleep(2000); #else if(flag_type == 3){ uint8 *tmpvmsbuf = NULL, *vmsbuf = NULL; uint32 cursize = ent->size - 32; tmpvmsbuf = (uint8* )calloc(1,cursize); vmsbuf = (uint8* )calloc(1,cursize); if((f=fs_open(src, O_RDONLY)) == FILEHND_INVALID){ GUI_ContainerRemove(self.vmu_page, self.progressbar_container); GUI_WidgetMarkChanged(self.vmu_page); UnlockVideo(); return; } fs_seek(f,32,SEEK_SET); fs_read(f, tmpvmsbuf, cursize); fs_close(f); for (xx = 0; xx < cursize; xx += 4){ for (yy = 3; yy >= 0; yy--) vmsbuf[xx + (3-yy)] = tmpvmsbuf[xx + yy]; } if((f=fs_open(dst, O_WRONLY)) == FILEHND_INVALID){ GUI_ContainerRemove(self.vmu_page, self.progressbar_container); GUI_WidgetMarkChanged(self.vmu_page); UnlockVideo(); return; } fs_write(f, vmsbuf, cursize); fs_close(f); free(tmpvmsbuf); free(vmsbuf); } else CopyFile(src, dst, 0); #endif free_blocks(GUI_FileManagerGetPath(self.filebrowser),0); GUI_FileManagerScan(self.filebrowser); } } else if(strncmp(self.m_SelectedPath, "/cd",3) != 0 || strncmp(self.m_SelectedPath, "/vmd",4) != 0){ // copy file from vmu sprintf(src, "%s/%s", GUI_FileManagerGetPath(fmw), ent->name); if(strncmp(GUI_FileManagerGetPath(self.filebrowser2), "/vmu",4) == 0){ if((ent->size/512) > self.vmu_freeblock2) return; sprintf(dst, "%s/%s", GUI_FileManagerGetPath(self.filebrowser2), ent->name); if (FileExists(dst) != 0) { sprintf(text, "Overwrite %s", dst); GUI_LabelSetText(self.confirm_text, text); if(Confirm_Window() == CMD_ERROR){ self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; clr_statusbar(); return; } } } else{ sprintf(dst, "%s/%12.12s.vms", GUI_FileManagerGetPath(self.filebrowser2), ent->name); for(i=1;i<99;i++){ if(!FileExists(dst)) break; sprintf(dst, "%s/%12.12s.%02d.vms", GUI_FileManagerGetPath(self.filebrowser2), ent->name, i); } } GUI_ProgressBarSetImage1(self.progressbar, self.progres_img_b); GUI_ProgressBarSetImage2(self.progressbar, self.progres_img); GUI_ProgressBarSetPosition(self.progressbar, 1.0); GUI_ContainerAdd(self.vmu_page, self.progressbar_container); GUI_WidgetMarkChanged(self.vmu_page); LockVideo(); #ifdef VMDEBUG dbgio_printf("src: %s\ndst: %s\n", src, dst); thd_sleep(2000); #else CopyFile(src, dst, 0); #endif if(strncmp(GUI_FileManagerGetPath(self.filebrowser2), "/vmu",4) == 0) free_blocks(GUI_FileManagerGetPath(self.filebrowser2),1); //GUI_FileManagerScan(self.filebrowser2); disable_high(LEFT_FM); } } self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; GUI_ContainerRemove(self.vmu_page, self.progressbar_container); GUI_WidgetMarkChanged(self.vmu_page); clr_statusbar(); if (VideoIsLocked()) UnlockVideo(); return; } if((ent->size/512) == 256 && (strcmp(GUI_ObjectGetName(fmw), "file_browser2") == 0 && ent->name[strlen(ent->name) - 3] == 'v' && ent->name[strlen(ent->name) - 2] == 'm' && ent->name[strlen(ent->name) - 1] == 'd')) { // This is VMD file flag_type = 1; } else if(ent->size == 108 && (strcmp(GUI_ObjectGetName(fmw), "file_browser2") == 0 && (ent->name[strlen(ent->name) - 3] == 'v' || ent->name[strlen(ent->name) - 3] == 'V') && (ent->name[strlen(ent->name) - 2] == 'm' || ent->name[strlen(ent->name) - 2] == 'M') && (ent->name[strlen(ent->name) - 1] == 'i' || ent->name[strlen(ent->name) - 1] == 'I'))){ // This is VMI file flag_type = 2; } else if(strcmp(GUI_ObjectGetName(fmw), "file_browser2") == 0 && (ent->name[strlen(ent->name) - 3] == 'd' || ent->name[strlen(ent->name) - 3] == 'D') && (ent->name[strlen(ent->name) - 2] == 'c' || ent->name[strlen(ent->name) - 2] == 'C') && (ent->name[strlen(ent->name) - 1] == 'i' || ent->name[strlen(ent->name) - 1] == 'I')){ // This is DCI file flag_type = 3; } else if((ent->size/512) > 199 || (strcmp(GUI_ObjectGetName(fmw), "file_browser2") == 0 && ent->name[strlen(ent->name) - 3] != 'v' && ent->name[strlen(ent->name) - 2] != 'm' && ent->name[strlen(ent->name) - 1] != 's' && strncmp(GUI_FileManagerGetPath(self.filebrowser2), "/vm",3) != 0)) { // This is VMS file and not vmd folder disable_high(RIGHT_FM); return; } /* file not selected */ self.m_SelectedFile = strdup(ent->name); self.m_SelectedPath = strdup(GUI_FileManagerGetPath(fmw)); panel = GUI_FileManagerGetItemPanel(fmw); for(i = 0; i < GUI_ContainerGetCount(panel); i++) { w = GUI_FileManagerGetItem(fmw, i); if(strcmp(GUI_ObjectGetName(fmw), "file_browser") == 0){ if(i != fm_ent->index) { GUI_ButtonSetNormalImage(w, self.m_ItemNormal); GUI_ButtonSetHighlightImage(w, self.m_ItemNormal); } else { GUI_ButtonSetNormalImage(w, self.m_ItemSelected); GUI_ButtonSetHighlightImage(w, self.m_ItemSelected); } } else { if(i != fm_ent->index) { GUI_ButtonSetNormalImage(w, self.m_ItemNormal2); GUI_ButtonSetHighlightImage(w, self.m_ItemNormal2); } else { GUI_ButtonSetNormalImage(w, self.m_ItemSelected2); GUI_ButtonSetHighlightImage(w, self.m_ItemSelected2); } } } if(strcmp(GUI_ObjectGetName(fmw), "file_browser") == 0){ disable_high(RIGHT_FM); } else { disable_high(LEFT_FM); } if(flag_type != 1){ tmpbuf = (uint16* )calloc(1, 2048); if(!tmpbuf) return; sprintf(tmp, "%s/%s", GUI_FileManagerGetPath(fmw), ent->name); if(flag_type == 2){ f=fs_open(tmp, O_RDONLY); fs_read(f, &vmi_t, 108); fs_close(f); sprintf(tmp, "%s/%1.8s.vms", GUI_FileManagerGetPath(fmw), vmi_t.source); if(!FileExists(tmp)) sprintf(tmp, "%s/%1.8s.VMS", GUI_FileManagerGetPath(fmw), vmi_t.source); } #ifdef VMDEBUG dbgio_printf("VMS filename: %s flag_type: %d\n", tmp, flag_type); #endif if(flag_type != 3){ if((f=fs_open(tmp, O_RDONLY)) == FILEHND_INVALID){ dbgio_printf("flag_type != 3 FILEHND_INVALID\n"); self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; disable_high(RIGHT_FM); if(tmpbuf) free(tmpbuf); return; } fs_read(f, buf, 1024); fs_close(f); } else { f=fs_open(tmp, O_RDONLY); fs_read(f, &dci_t, 1056); fs_close(f); for (xx = 0; xx < 1024; xx += 4){ for (yy = 3; yy >= 0; yy--) buf[xx + (3-yy)] = dci_t.vmsheader[xx + yy]; } } memcpy(self.desc_short, buf, 16); self.desc_short[16]=0; memcpy(self.desc_long, buf+0x10, 32); self.desc_long[32]=0; if (strcmp(ent->name, "ICONDATA_VMS") == 0) { if(tmpbuf) free(tmpbuf); return; } else { memcpy(pal, buf+0x60, 32); memcpy(icon, buf+0x80, 512); } for (yy=0; yy<VMU_ICON_WIDTH; yy++){ for (xx=0; xx<VMU_ICON_HEIGHT; xx+=2) { nyb=(icon[yy*16 + xx/2] & 0xf0) >> 4; tmpbuf[xx+yy*32]=PACK_NYBBLE_RGB565(pal[nyb]); nyb=(icon[yy*16 + xx/2] & 0x0f) >> 0; tmpbuf[xx+1+yy*32]=PACK_NYBBLE_RGB565(pal[nyb]); } } self.vmu_icon = SDL_CreateRGBSurfaceFrom(tmpbuf,32, 32, 16, 64,0, 0, 0, 0); self.vmuicon = GUI_SurfaceFrom("vmuicon", self.vmu_icon); free(tmpbuf); } else { sprintf(self.desc_short,"VMU Dump"); sprintf(self.desc_long,"Dreamshell VMU Dump file"); } if(flag_type == 2) sprintf(size, "%ld Block(s)",vmi_t.size/512); else if(flag_type == 3) sprintf(size, "%d Block(s)",(ent->size-32)/512); else sprintf(size, "%d Block(s)",ent->size/512 ); #ifdef VMDEBUG dbgio_printf("name: %s\n", ent->name); dbgio_printf("size: %s\n", size); dbgio_printf("descshort: %s\n", self.desc_short); dbgio_printf("desclong: %s\n", self.desc_long); #endif if(flag_type == 1) GUI_PictureSetImage(self.sicon, self.dump_icon); else GUI_PictureSetImage(self.sicon, self.vmuicon); GUI_LabelSetText(self.save_name, ent->name); GUI_LabelSetText(self.save_size, size); GUI_LabelSetText(self.save_descshort, self.desc_short); GUI_LabelSetText(self.save_desclong, self.desc_long); } void VMU_Manager_addfileman(GUI_Widget *widget) { file_t f; char path[NAME_MAX]; if(strcmp(GUI_ObjectGetName(widget),"/cd") != 0 && strlen(GUI_ObjectGetName(widget)) > 2){ if((f = fs_open(GUI_ObjectGetName(widget),O_DIR)) == FILEHND_INVALID) { fs_mkdir(GUI_ObjectGetName(widget)); }else fs_close(f); GUI_WidgetSetEnabled(self.button_dump, 1); }else if(strlen(GUI_ObjectGetName(widget)) != 2){ if(!DirExists("/cd")) { GUI_WidgetSetEnabled(self.cd_c, 0); return; } } if(self.direction_flag == 1){ sprintf(path,"/vmu/%s", GUI_ObjectGetName(widget)); self.home_path = (const char *) path; }else self.home_path = GUI_ObjectGetName(widget); self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; disable_high(RIGHT_FM); disable_high(LEFT_FM); clr_statusbar(); GUI_ContainerRemove(self.vmu_page, self.sd_c); GUI_ContainerRemove(self.vmu_page, self.hdd_c); GUI_ContainerRemove(self.vmu_page, self.cd_c); GUI_ContainerRemove(self.vmu_page, self.pc_c); GUI_ContainerRemove(self.vmu_page, self.format_c); GUI_ContainerRemove(self.vmu_page, self.dst_vmu); GUI_FileManagerSetPath(self.filebrowser2, self.home_path); GUI_ContainerAdd(self.vmu_page, self.filebrowser2); GUI_WidgetMarkChanged(self.vmu_page); } void VMU_Manager_ItemContextClick(dirent_fm_t *fm_ent) { dirent_t *ent = &fm_ent->ent; GUI_Widget *fmw = (GUI_Widget*)fm_ent->obj; char text[1024]; char path[NAME_MAX]; if(ent->attr == O_DIR){ if (strcmp(GUI_ObjectGetName(fmw), "file_browser") == 0){ VMU_Manager_ItemClick(fm_ent); return; }else if(strncmp(GUI_FileManagerGetPath(fmw),"/cd",3) == 0 || strncmp(GUI_FileManagerGetPath(fmw),"/vm",3) == 0){ self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; disable_high(RIGHT_FM); clr_statusbar(); return; }else{ self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; disable_high(RIGHT_FM); clr_statusbar(); if (fm_ent->index == 0) GUI_CardStackShowIndex(self.pages, 2); else{ sprintf(text, "Delete folder: %s ?", ent->name); sprintf(path, "%s/%s",GUI_FileManagerGetPath(self.filebrowser2), ent->name); GUI_LabelSetText(self.confirm_text, text); if(Confirm_Window() == CMD_OK){ rmdir_recursive(path); //fs_rmdir(path); GUI_FileManagerScan(fmw); } } } return; }else if(!self.m_SelectedFile){ VMU_Manager_ItemClick(fm_ent); }else if(strcmp(self.m_SelectedFile,ent->name) != 0 || strcmp(self.m_SelectedPath,GUI_FileManagerGetPath(fmw)) != 0){ VMU_Manager_ItemClick(fm_ent); }else if(strncmp(self.m_SelectedPath,"/vmd",4) != 0 || !strncmp(self.m_SelectedPath,"/cd",3) != 0){ /* Delete file */ sprintf(text, "Delete %s/%s", GUI_FileManagerGetPath(fmw), ent->name); GUI_LabelSetText(self.confirm_text, text); if(Confirm_Window() == CMD_OK) { sprintf(text, "%s/%s", GUI_FileManagerGetPath(fmw), ent->name); fs_unlink(text); if(strncmp(GUI_FileManagerGetPath(fmw) , "/vmu", 4) == 0) { if(strcmp(GUI_ObjectGetName(fmw), "file_browser") == 0){ free_blocks(text,0); }else free_blocks(text,1); } } self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; clr_statusbar(); GUI_WidgetMarkChanged(self.vmu_page); } return; } int VMU_Manager_Dump(GUI_Widget *widget) { maple_device_t *dev = NULL; uint8 *vmdata; file_t f; char src[NAME_MAX] , dst[NAME_MAX], addr[NAME_MAX]; int i,dumpflg; double progress = 0.0; strcpy(addr,GUI_FileManagerGetPath(self.filebrowser)); if((dev = vmu_dev(addr)) == NULL) return CMD_ERROR; dumpflg = strcmp(GUI_ObjectGetName(widget),"dump-button"); if(dumpflg == 0){ /*DUMP*/ GUI_ProgressBarSetImage1(self.progressbar, self.progres_img_b); GUI_ProgressBarSetImage2(self.progressbar, self.progres_img); GUI_ProgressBarSetPosition(self.progressbar, progress); GUI_ContainerAdd(self.vmu_page, self.progressbar_container); sprintf(dst, "%s/vmu001.vmd", GUI_FileManagerGetPath(self.filebrowser2)); for(i=2;i<999;i++){ if(!FileExists(dst)) break; sprintf(dst, "%s/vmu%03d.vmd", GUI_FileManagerGetPath(self.filebrowser2), i); } #ifdef VMDEBUG dbgio_printf("dst name: %s\n", dst); #endif f = fs_open(dst, O_WRONLY | O_CREAT | O_TRUNC); if(f < 0) { dbgio_printf("DS_ERROR: Can't open %s\n", dst); return CMD_ERROR; } vmdata = (uint8 *) calloc(1,512); for (i = 0; i < 256; i++) { if (vmu_block_read(dev, i, vmdata) < 0) { dbgio_printf("DS_ERROR: Failed to read block %d\n", i); fs_close(f); free(vmdata); GUI_ContainerRemove(self.vmu_page, self.progressbar_container); GUI_WidgetMarkChanged(self.vmu_page); return CMD_ERROR; } fs_write(f, vmdata, 512); progress = (double) ceil(i*10/256)/10 + 0.1; GUI_ProgressBarSetPosition(self.progressbar, progress); GUI_WidgetMarkChanged(self.progressbar_container); } fs_close(f); free(vmdata); GUI_ContainerRemove(self.vmu_page, self.progressbar_container); GUI_FileManagerScan(self.filebrowser2); }else{ /*RESTORE*/ progress = 1.0; GUI_ProgressBarSetImage1(self.progressbar, self.progres_img); GUI_ProgressBarSetImage2(self.progressbar, self.progres_img_b); GUI_ProgressBarSetPosition(self.progressbar, progress); GUI_ContainerAdd(self.vmu_page, self.progressbar_container); sprintf(src, "%s/%s", self.m_SelectedPath , self.m_SelectedFile); #ifdef VMDEBUG dbgio_printf("src name: %s\n", src); dbgio_printf("SelectedPath: %s\nSelectedFile: %s\n", self.m_SelectedPath,self.m_SelectedFile); /* GUI_ContainerRemove(self.vmu_page, self.progressbar_container); GUI_WidgetMarkChanged(self.vmu_page); return CMD_OK; */ #endif f = fs_open(src, O_RDONLY); if(f < 0) { dbgio_printf("DS_ERROR: Can't open %s\n", src); return CMD_ERROR; } vmdata = (uint8 *) calloc(1,512); i = 0; while(fs_read(f, vmdata, 512) > 0) { #ifdef VMDEBUG thd_sleep(10); #else if(vmu_block_write(dev, i, vmdata) < 0) { dbgio_printf("DS_ERROR: Failed to write block %d\n", i); fs_close(f); free(vmdata); GUI_ContainerRemove(self.vmu_page, self.progressbar_container); GUI_WidgetMarkChanged(self.vmu_page); return CMD_ERROR; } #endif i++; progress = (double) ceil((255-i)*10/256)/10 + 0.1; GUI_ProgressBarSetPosition(self.progressbar, progress); GUI_WidgetMarkChanged(self.progressbar_container); } fs_close(f); free(vmdata); GUI_ContainerRemove(self.vmu_page, self.progressbar_container); } GUI_WidgetMarkChanged(self.vmu_page); return CMD_OK; } void VMU_Manager_format(GUI_Widget *widget) { file_t d; dirent_t *de; int num_files = 0, i = 0; double progress = 0.0; char path[NAME_MAX],del_file[NAME_MAX]; GUI_LabelSetText(self.confirm_text, "ERASE VMU. WARNING all data on VMU lost"); if(Confirm_Window() == CMD_ERROR) return; self.m_SelectedFile = NULL; self.m_SelectedPath = NULL; disable_high(LEFT_FM); clr_statusbar(); sprintf(path, "%s", GUI_FileManagerGetPath(self.filebrowser)); d = fs_open(path, O_DIR); GUI_ProgressBarSetImage1(self.progressbar, self.progres_img_b); GUI_ProgressBarSetImage2(self.progressbar, self.progres_img); GUI_ProgressBarSetPosition(self.progressbar, progress); GUI_ContainerAdd(self.vmu_page, self.progressbar_container); GUI_WidgetMarkChanged(self.vmu_page); while (fs_readdir(d)) num_files++; fs_close(d); d = fs_open(path, O_DIR); while ((de = fs_readdir(d)) ) { sprintf(del_file, "%s/%s", path, de->name); #ifdef VMDEBUG dbgio_printf("Delete: %s\n", del_file); thd_sleep(500); #else if(fs_unlink(del_file) < 0) break; #endif i++; progress = (double) ceil(i*10/num_files)/10 + 0.1; GUI_ProgressBarSetPosition(self.progressbar, progress); GUI_WidgetMarkChanged(self.progressbar_container); } GUI_ContainerRemove(self.vmu_page, self.progressbar_container); fs_close(d); free_blocks(GUI_FileManagerGetPath(self.filebrowser),0); GUI_FileManagerScan(self.filebrowser); GUI_WidgetMarkChanged(self.vmu_page); } void VMU_Manager_sel_dst_vmu(GUI_Widget *widget) { self.direction_flag = 1; GUI_LabelSetText(self.drection, "SELECT DESTINATION VMU"); ScreenFadeOut(); thd_sleep(200); GUI_CardStackShowIndex(self.pages, 0); ScreenFadeIn(); t0 = thd_create(1, maple_scan, NULL); } void VMU_Manager_make_folder(GUI_Widget *widget){ char newfolder[NAME_MAX]; char textentry[NAME_MAX]; if (strcmp(GUI_ObjectGetName(widget),"confirm-no") == 0) GUI_CardStackShowIndex(self.pages, 1); strcpy(textentry,GUI_TextEntryGetText(self.folder_name)); if (strlen(textentry) < 1) return; sprintf(newfolder,"%s/%s",GUI_FileManagerGetPath(self.filebrowser2),textentry); fs_mkdir(newfolder); GUI_CardStackShowIndex(self.pages, 1); } void VMU_Manager_clr_name(GUI_Widget *widget){ GUI_TextEntrySetText(widget, ""); } <file_sep>/firmware/bootloader/include/main.h #ifndef __MAIN_H #define __MAIN_H /* KOS */ #include <kos.h> #include <math.h> #include <assert.h> #include <kmg/kmg.h> #include <zlib/zlib.h> /* spiral.c */ int spiral_init(); void spiral_frame(); /* menu.c */ int menu_init(); void init_menu_txr(); void menu_frame(); void loading_core(int no_thd); int show_message(const char *fmt, ...); int FileSize(const char *fn); int FileExists(const char *fn); int DirExists(const char *dir); int flashrom_get_region_only(); void descramble(uint8 *source, uint8 *dest, uint32 size); extern const char title[28]; extern uint32 spiral_color; extern int start_pressed; #define RES_PATH "/brd" #endif /* __MAIN_H */ <file_sep>/lib/SDL_gui/Screen.cc // Modified by SWAT // http://www.dc-swat.ru #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" extern "C" { SDL_Surface *GetScreen(); void LockVideo(); void UnlockVideo(); int VideoMustLock(); } GUI_Screen::GUI_Screen(const char *aname, SDL_Surface *surface) : GUI_Drawable(aname, 0, 0, surface->w, surface->h) { screen_surface = new GUI_Surface("screen", surface); background = 0; contents = 0; focus_widget = 0; background_color = 0; //mouse = 0; joysel = new GUI_Widget *[64]; joysel_size = 0; joysel_cur = 0; joysel_enabled = 1; } GUI_Screen::~GUI_Screen(void) { if (background) background->DecRef(); if (focus_widget) focus_widget->DecRef(); if (contents) contents->DecRef(); if (screen_surface) screen_surface->DecRef(); } GUI_Surface *GUI_Screen::GetSurface(void) { return screen_surface; } void GUI_Screen::FlushUpdates(void) { } void GUI_Screen::UpdateRect(const SDL_Rect *r) { } void GUI_Screen::Draw(GUI_Surface *image, const SDL_Rect *src_r, const SDL_Rect *dst_r) { SDL_Rect sr, dr; SDL_Rect *srp, *drp; //assert( != 0); if(image == NULL) return; if (src_r) { sr = *src_r; srp = &sr; } else srp = NULL; if (dst_r) { dr = *dst_r; drp = &dr; } else drp = NULL; /* if (flags & SCREEN_DEBUG_BLIT) { printf("Screen_draw: %p:", image); if (src_r) printf("[%d,%d,%d,%d]", srp->x, srp->y, srp->w, srp->h); else printf("NULL"); printf(" -> %p:", screen_surface); if (drp) printf("[%d,%d,%d,%d] (%d,%d)\n", drp->x, drp->y, drp->w, drp->h, drp->x + drp->w, drp->y + drp->h); else printf("NULL\n"); } */ if(VideoMustLock()) { LockVideo(); image->Blit(srp, screen_surface, drp); UnlockVideo(); } else { image->Blit(srp, screen_surface, drp); } // if (!screen_surface->IsDoubleBuffered()) UpdateRect(drp); } void GUI_Screen::Fill(const SDL_Rect *dst_r, SDL_Color c) { Uint32 color = screen_surface->MapRGB(c.r, c.g, c.b); SDL_Rect r = *dst_r; if(VideoMustLock()) { LockVideo(); screen_surface->Fill(&r, color); UnlockVideo(); } else { screen_surface->Fill(&r, color); } // if (!screen_surface->IsDoubleBuffered()) UpdateRect(&r); } void GUI_Screen::Erase(const SDL_Rect *area) { if (background) TileImage(background, area, 0, 0); else { SDL_Rect r; SDL_Rect *rp; if (area) { r = *area; rp = &r; } else rp = NULL; if(VideoMustLock()) { LockVideo(); screen_surface->Fill(rp, background_color); UnlockVideo(); } else { screen_surface->Fill(rp, background_color); } } // if (!screen_surface->IsDoubleBuffered()) UpdateRect(area); } void GUI_Screen::Update(int force) { if (force) Erase(&area); if (contents) contents->DoUpdate(force); FlushUpdates(); } void GUI_Screen::find_widget_rec(GUI_Container *p) { if(!p) return; int count = p->GetWidgetCount(); int i, type; int j, ex; GUI_Widget *w; for(i = 0; i < count; i++) { w = p->GetWidget(i); if(p->IsVisibleWidget(w) && !(w->GetFlags() & WIDGET_DISABLED)) { type = ((GUI_Drawable*)w)->GetWType(); switch(type) { case WIDGET_TYPE_CONTAINER: find_widget_rec((GUI_Container *)w); case WIDGET_TYPE_CARDSTACK: w = ((GUI_CardStack*)w)->GetWidget( ((GUI_CardStack*)w)->GetIndex() ); find_widget_rec((GUI_Container *)w); break; case WIDGET_TYPE_BUTTON: case WIDGET_TYPE_SCROLLBAR: case WIDGET_TYPE_TEXTENTRY: if(joysel_size < 64) { ex = 0; for(j = 0; j < joysel_size; j++) { if(joysel[j] == w) { ex = 1; break; } } if(!ex) joysel[joysel_size++] = w; } default: break; } } } } void GUI_Screen::calc_parent_offset(GUI_Widget *widget, Uint16 *x, Uint16 *y) { GUI_Drawable *w = NULL; SDL_Rect warea; int type = 0, p = 0; warea = widget->GetArea(); type = ((GUI_Drawable *)widget)->GetWType(); if(type == WIDGET_TYPE_SCROLLBAR) { if(warea.w > warea.h) { p = ((GUI_ScrollBar*)widget)->GetHorizontalPosition(); *x = warea.x + p + 10; } else { *x = warea.x + (warea.w / 2); } if(warea.h > warea.w) { p = ((GUI_ScrollBar*)widget)->GetVerticalPosition(); *y = warea.y + p + 10; } else { *y = warea.y + (warea.h / 2); } } else { *x = warea.x + (warea.w / 2); *y = warea.y + (warea.h / 2); } w = widget->GetParent(); while(w) { warea = w->GetArea(); type = w->GetWType(); if(type == WIDGET_TYPE_CONTAINER) { *x += warea.x - ((GUI_Container*)w)->GetXOffset(); *y += warea.y - ((GUI_Container*)w)->GetYOffset(); } else { *x += warea.x; *y += warea.y; } w = w->GetParent(); } } void GUI_Screen::SetJoySelectState(int value) { joysel_enabled = value; } int GUI_Screen::Event(const SDL_Event *event, int xoffset, int yoffset) { /* if (event->type == SDL_QUIT) { GUI_SetRunning(0); return 1; } if (event->type == SDL_KEYDOWN) { if (event->key.keysym.sym == SDLK_ESCAPE) { GUI_SetRunning(0); return 1; } }*/ if(joysel_enabled) { SDL_Event evt; switch(event->type) { case SDL_JOYHATMOTION: { if (contents) { switch(event->jhat.value) { case 0x0E: //UP case 0x0B: //DOWN int i; for(i = 0; i < joysel_size; i++) { joysel[i] = NULL; } joysel_size = 0; find_widget_rec((GUI_Container *)contents); if(joysel_size) { if(event->jhat.value == 0x0E) { if(joysel_cur <= 0) joysel_cur = joysel_size - 1; else joysel_cur--; } else { if(joysel_cur >= joysel_size-1) joysel_cur = 0; else joysel_cur++; } if(joysel[joysel_cur]) { evt.type = SDL_MOUSEMOTION; calc_parent_offset(joysel[joysel_cur], &evt.motion.x, &evt.motion.y); evt.motion.x -= xoffset; evt.motion.y -= yoffset; SDL_PushEvent(&evt); SDL_WarpMouse(evt.motion.x, evt.motion.y); } } break; case 0x07: //LEFT case 0x0D: //RIGHT for(i = 0; i < joysel_size; i++) { joysel[i] = NULL; } joysel_size = 0; find_widget_rec((GUI_Container *)contents); joysel_cur = event->jhat.value == 0x07 ? 0 : joysel_size - 1; if(joysel_size && joysel[joysel_cur]) { evt.type = SDL_MOUSEMOTION; calc_parent_offset(joysel[joysel_cur], &evt.motion.x, &evt.motion.y); evt.motion.x -= xoffset; evt.motion.y -= yoffset; SDL_PushEvent(&evt); SDL_WarpMouse(evt.motion.x, evt.motion.y); } break; } } break; } } } if (contents) if (contents->Event(event, xoffset, yoffset)) return 1; return GUI_Drawable::Event(event, xoffset, yoffset); } void GUI_Screen::RemoveWidget(GUI_Widget *widget) { if (widget == contents) Keep(&contents, NULL); } void GUI_Screen::SetContents(GUI_Widget *widget) { Keep(&contents, widget); joysel_size = 0; joysel_cur = -1; int i; for(i = 0; i < joysel_size; i++) { joysel[i] = NULL; } MarkChanged(); } void GUI_Screen::SetBackground(GUI_Surface *image) { if (GUI_ObjectKeep((GUI_Object **) &background, image)) MarkChanged(); } void GUI_Screen::SetBackgroundColor(SDL_Color c) { Uint32 color; color = screen_surface->MapRGB(c.r, c.g, c.b); if (color != background_color) { background_color = color; MarkChanged(); } } void GUI_Screen::SetFocusWidget(GUI_Widget *widget) { //assert(widget != NULL); if (widget != NULL && focus_widget != widget) { ClearFocusWidget(); widget->SetFlags(WIDGET_HAS_FOCUS); widget->IncRef(); focus_widget = widget; } } void GUI_Screen::ClearFocusWidget() { if (focus_widget) { focus_widget->ClearFlags(WIDGET_HAS_FOCUS); focus_widget->DecRef(); focus_widget = 0; } } GUI_Widget *GUI_Screen::GetFocusWidget() { return focus_widget; } /* void GUI_Screen::SetMouse(GUI_Mouse *m) { GUI_ObjectKeep((GUI_Object **) &mouse, m); } void GUI_Screen::DrawMouse(void) { if (mouse) { int x,y; SDL_GetMouseState(&x, &y); mouse->Draw(this,x,y); } }*/ extern "C" { GUI_Screen *GUI_ScreenCreate(int w, int h, int d, int f) { return new GUI_RealScreen("screen", GetScreen()); } void GUI_ScreenSetContents(GUI_Screen *screen, GUI_Widget *widget) { screen->SetContents(widget); } void GUI_ScreenSetBackground(GUI_Screen *screen, GUI_Surface *image) { screen->SetBackground(image); } void GUI_ScreenSetFocusWidget(GUI_Screen *screen, GUI_Widget *widget) { screen->SetFocusWidget(widget); } void GUI_ScreenClearFocusWidget(GUI_Screen *screen) { screen->ClearFocusWidget(); } void GUI_ScreenSetBackgroundColor(GUI_Screen *screen, SDL_Color c) { screen->SetBackgroundColor(c); } GUI_Widget *GUI_ScreenGetFocusWidget(GUI_Screen *screen) { return screen->GetFocusWidget(); } /* void GUI_ScreenDrawMouse(GUI_Screen *screen) { screen->DrawMouse(); } */ void GUI_ScreenEvent(GUI_Screen *screen, const SDL_Event *event, int xoffset, int yoffset) { screen->Event(event, xoffset, yoffset); } void GUI_ScreenUpdate(GUI_Screen *screen, int force) { //screen->Update(force); } void GUI_ScreenDoUpdate(GUI_Screen *screen, int force) { if(screen) screen->DoUpdate(force); } void GUI_ScreenDraw(GUI_Screen *screen, GUI_Surface *image, const SDL_Rect *src_r, const SDL_Rect *dst_r) { if(screen) screen->Draw(image, src_r, dst_r); } void GUI_ScreenFill(GUI_Screen *screen, const SDL_Rect *dst_r, SDL_Color c) { if(screen) screen->Fill(dst_r, c); } void GUI_ScreenErase(GUI_Screen *screen, const SDL_Rect *area) { if(screen) screen->Erase(area); } /* void GUI_ScreenSetMouse(GUI_Screen *screen, GUI_Mouse *m) { if(screen) screen->SetMouse(m); }*/ void GUI_ScreenSetJoySelectState(GUI_Screen *screen, int value) { screen->SetJoySelectState(value); } GUI_Surface *GUI_ScreenGetSurface(GUI_Screen *screen) { if(screen) return screen->GetSurface(); return NULL; } } <file_sep>/modules/ffmpeg/mpglib.c /* * @author bero <<EMAIL>> */ #include "libavcodec/avcodec.h" #include "libavformat/avformat.h" #define NOANALYSIS 1 #include "mpglib/mpg123.h" #include "mpglib/mpglib.h" typedef struct MPADecodeContext { struct mpstr_tag mp; int header_parsed; } MPADecodeContext; static int decode_init(AVCodecContext * avctx) { MPADecodeContext *s = avctx->priv_data; InitMP3(&s->mp); return 0; } static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPacket *avpkt) { MPADecodeContext *s = avctx->priv_data; int ret; int outsize; char *outp = data; *data_size = 0; ret = decodeMP3(&s->mp, avpkt->data, avpkt->size, outp, 65536, &outsize); while(ret == MP3_OK) { if (!s->header_parsed) { struct frame *fr = &s->mp.fr; extern int tabsel_123[2][3][16]; extern long freqs[9]; s->header_parsed = 1; avctx->channels = fr->stereo; avctx->sample_rate = freqs[fr->sampling_frequency]; avctx->bit_rate = tabsel_123[fr->lsf][fr->lay-1][fr->bitrate_index]*1000; //printf("channels=%d,rate=%d\n", avctx->channels, avctx->sample_rate); } // printf("%d \n",outsize); outp += outsize; *data_size += outsize; ret = decodeMP3(&s->mp, NULL, 0, outp, 65536, &outsize); } //printf("datasize:%d \n",*data_size); return avpkt->size; } static int decode_close(AVCodecContext *avctx) { MPADecodeContext *s = avctx->priv_data; ExitMP3(&s->mp); return 0; } /* AVCodec mpglib_mp2_decoder = { "mp2", CODEC_TYPE_AUDIO, CODEC_ID_MP2, sizeof(MPADecodeContext), decode_init, NULL, decode_close, decode_frame, }; AVCodec mpglib_mp3_decoder = { "mp3", CODEC_TYPE_AUDIO, CODEC_ID_MP3, sizeof(MPADecodeContext), decode_init, NULL, decode_close, decode_frame, };*/ AVCodec mp1_decoder = { "mp1", AVMEDIA_TYPE_AUDIO, CODEC_ID_MP1, sizeof(MPADecodeContext), decode_init, NULL, decode_close, decode_frame, CODEC_CAP_PARSE_ONLY, .flush= NULL,//flush, .long_name= "MP1 (MPEG audio layer 1)", }; AVCodec mp2_decoder = { "mp2", AVMEDIA_TYPE_AUDIO, CODEC_ID_MP2, sizeof(MPADecodeContext), decode_init, NULL, decode_close, decode_frame, CODEC_CAP_PARSE_ONLY, .flush= NULL,//flush, .long_name= "MP2 (MPEG audio layer 2)", }; AVCodec mp3_decoder = { "mp3", AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3, sizeof(MPADecodeContext), decode_init, NULL, decode_close, decode_frame, CODEC_CAP_PARSE_ONLY, .flush= NULL,//flush, .long_name= "MP3 (MPEG audio layer 3)", }; <file_sep>/firmware/isoldr/loader/include/ubc.h /** * DreamShell ISO Loader * SH4 UBC * (c)2013-2020 SWAT <http://www.dc-swat.ru> * Based on Netplay VOOT code by <NAME> <<EMAIL>> */ #include <arch/types.h> /* UBC register bitmasks */ #define UBC_BAMR_NOASID (1<<2) #define UBC_BAMR_MASK_10 (1) #define UBC_BAMR_MASK_12 (1<<1) #define UBC_BAMR_MASK_16 (1<<3) #define UBC_BAMR_MASK_20 (UBC_BAMR_MASK_16 | UBC_BAMR_MASK_10) #define UBC_BAMR_MASK_ALL (UBC_BAMR_MASK_10 | UBC_BAMR_MASK_12) #define UBC_BBR_OPERAND (1<<5) #define UBC_BBR_INSTRUCT (1<<4) #define UBC_BBR_WRITE (1<<3) #define UBC_BBR_READ (1<<2) #define UBC_BBR_UNI (UBC_BBR_OPERAND | UBC_BBR_INSTRUCT) #define UBC_BBR_RW (UBC_BBR_WRITE | UBC_BBR_READ) #define UBC_BRCR_CMFA (1<<15) #define UBC_BRCR_CMFB (1<<14) #define UBC_BRCR_PCBA (1<<10) #define UBC_BRCR_PCBB (1<<6) #define UBC_BRCR_UBDE (1) /* UBC channel A registers */ #define UBC_R_BARA *(volatile uint32 *)0xff200000 #define UBC_R_BAMRA *(volatile uint8 *)0xff200004 #define UBC_R_BBRA *(volatile uint16 *)0xff200008 #define UBC_R_BASRA *(volatile uint8 *)0xff000014 /* UBC channel B registers */ #define UBC_R_BARB *(volatile uint32 *)0xff20000c #define UBC_R_BAMRB *(volatile uint8 *)0xff200010 #define UBC_R_BBRB *(volatile uint16 *)0xff200014 #define UBC_R_BASRB *(volatile uint8 *)0xff000018 /* UBC global registers */ #define UBC_R_BDRB *(volatile uint32 *)0xff200018 #define UBC_R_BDRMB *(volatile uint32 *)0xff20001c #define UBC_R_BRCR *(volatile uint16 *)0xff200020 typedef enum { UBC_CHANNEL_A, UBC_CHANNEL_B } ubc_channel; /* Initializing the UBC */ void ubc_init(void); /* Configure the appropriate channel with the specified breakpoint. */ int ubc_configure_channel (ubc_channel channel, uint32 breakpoint, uint16 options); /* Clear the appropriate channel's options. */ void ubc_clear_channel (ubc_channel channel); /* Clear the appropriate channel's break bit. */ void ubc_clear_break (ubc_channel channel); int ubc_is_channel_break (ubc_channel channel); <file_sep>/src/drivers/g2_ide.c /* KallistiOS ##version## ide.c (c)1997,2002 <NAME> */ #include <assert.h> #include <stdio.h> #include <dc/g2bus.h> #include "ds.h" #include "drivers/g2_ide.h" /* A *very* simple port-level ATA-IDE device driver. This was ported up from the _original_ KallistiOS =) (PC based) */ static uint16 dd[256]; /* hard disk parameters, read from controller */ static uint32 hd_cyls, hd_heads, hd_sects; /* hard disk geometry */ static void ide_outp(int port, uint16 value, int size) { uint32 addr = 0;//, val2; switch (port & 0xff0) { case 0x1f0: addr = 0xb4002000 + ((port & 7) << 2); break; case 0x3f0: addr = 0xb4001000 + ((port & 7) << 2); break; default: assert(0); } //printf("ide_outp %02x -> %04x(%08x)\n", value, port, addr); g2_write_16(addr, value); } uint16 ide_inp(int port, int size) { uint32 addr = 0; uint16 value; switch (port & 0xff0) { case 0x1f0: addr = 0xb4002000 + ((port & 7) << 2); break; case 0x3f0: addr = 0xb4001000 + ((port & 7) << 2); break; default: assert(0); } value = g2_read_16(addr); if (!size) value &= 0xff; return value; } #define outp(x, y) ide_outp(x, y, 0) #define outpw(x, y) ide_outp(x, y, 1) #define inp(x) ide_inp(x, 0) #define inpw(x) ide_inp(x, 1) /* These are to synchronize us with the controller so we don't do something it's not ready for */ static int wait_controller() { int timeout = 100; while ((inp(0x1f7) & 0x80) && timeout) { thd_sleep(10); timeout--; } if (!timeout) { ds_printf("DS_ERROR: IDE controller timed out waiting for ready.. status = %x/%x\n", inp(0x1f7), inp(0x1f1)); return -1; } return 0; } static int wait_data() { int timeout = 100; while (!(inp(0x1f7) & 0x08) && timeout) { thd_sleep(10); timeout--; } if (!timeout) { ds_printf("DS_ERROR: IDE controller timed out waiting for data.. status = %x/%x\n", inp(0x1f7), inp(0x1f1)); return -1; } return 0; } /* Reads a chunk of ascii out of the hd parms table */ static char *get_ascii(uint16 *in_data, uint32 off_start, uint32 off_end) { static char ret_val [255]; int loop, loop1; /* First, construct a string from the controller-retrieved data */ for (loop = off_start, loop1 = 0; loop <= off_end; loop++) { ret_val [loop1++] = (char) (in_data [loop] / 256); /* Get High byte */ ret_val [loop1++] = (char) (in_data [loop] % 256); /* Get Low byte */ } // Now, go back and eliminate the blank spaces for ( ; (ret_val[loop1]<'A' || ret_val[loop1]>'z') && loop1>=0 ; loop1--) ret_val[loop1]='\0'; return ret_val; } /* Read n sectors from the hard disk using PIO mode */ static int ide_read_chs(uint32 cyl,uint32 head,uint32 sector,uint32 numsects, uint8 *bufptr) { int o; uint16 *bufptr16 = (uint16*)bufptr; //printf("reading C/H/S/Cnt %d/%d/%d/%d\n", // cyl, head, sector, numsects); wait_controller(); /* wait for controller to be not busy */ outp(0x1f2,numsects & 0xff); /* number of sectors to read */ outp(0x1f3,sector & 0xff); /* sector number to read */ outp(0x1f4,cyl & 0xff); /* cylinder (low part) */ outp(0x1f5,cyl >> 8); /* cylinder (high part) */ outp(0x1f6,0xa0 | (head&0xf)); /* select device 0 and head */ outp(0x1f7,0x20); /* command == read sector(s) w/retry */ wait_data(); /* wait for data to be read */ for (o=0; o<256; o++) { /*if (inp(0x1f7) & 1) { printf("as of %d, error code is %x/%x\n", o, inp(0x1f7), inp(0x1f1)); return -1; } */ bufptr16[o] = inpw(0x1f0); } /* if (inp(0x1f7) & 1) { printf("after read, status is %x/%x\n", inp(0x1f7), inp(0x1f1)); } */ return 0; } /* Write n sectors to the hard disk using PIO mode */ static int ide_write_chs(uint32 cyl,uint32 head,uint32 sector,uint32 numsects, uint8 *bufptr) { int o; uint16 *bufptr16 = (uint16*)bufptr; //printf("writing C/H/S/Cnt %d/%d/%d/%d\n", // cyl, head, sector, numsects); wait_controller(); /* wait for controller to be not busy */ outp(0x1f2,numsects & 0xff); /* number of sectors to write */ outp(0x1f3,sector & 0xff); /* sector number to write */ outp(0x1f4,cyl & 0xff); /* cylinder (low part) */ outp(0x1f5,cyl >> 8); /* cylinder (high part) */ outp(0x1f6,0xa0 | (head&0xf)); /* select device 0 and head */ outp(0x1f7,0x30); /* command == write sector(s) w/retry */ wait_data(); /* wait for data to be ready */ for (o=0; o<256; o++) { /* if (inp(0x1f7) & 1) { printf("as of %d, error code is %x/%x\n", o, inp(0x1f7), inp(0x1f1)); return -1; } */ outpw(0x1f0, bufptr16[o]); } /* if (inp(0x1f7) & 1) { printf("after write, status is %x/%x\n", inp(0x1f7), inp(0x1f1)); } */ return 0; } /* Translate a linear sector address relative to the first of the partition to a CHS address suitable for feeding to the hard disk */ static void linear_to_chs(uint32 linear, uint32 * cyl, uint32 * head, uint32 * sector) { *sector = linear % hd_sects + 1; *head = (linear / hd_sects) % hd_heads; *cyl = linear / (hd_sects * hd_heads); } /* Read n sectors from the hard disk using PIO mode */ int ide_read(uint32 linear, uint32 numsects, void * bufptr) { int i; uint32 cyl,head,sector; if (numsects > 1) { for (i=0; i<numsects; i++) { if (ide_read(linear+i, 1, ((uint8 *)bufptr)+i*512) < 0) return -1; } } else { linear_to_chs(linear, &cyl, &head, &sector); if (ide_read_chs(cyl, head, sector, numsects, (uint8*)bufptr) < 0) return -1; } return 0; } /* Write n sectors to the hard disk using PIO mode */ int ide_write(uint32 linear, uint32 numsects, void *bufptr) { int i; uint32 cyl,head,sector; if (numsects > 1) { for (i=0; i<numsects; i++) { if (ide_write(linear+i, 1, ((uint8 *)bufptr)+i*512) < 0) return -1; } } else { linear_to_chs(linear, &cyl, &head, &sector); ide_write_chs(cyl, head, sector, numsects, (uint8*)bufptr); } return 0; } /* Get the available space */ uint32 ide_num_sectors() { return hd_cyls * hd_heads * hd_sects; } /* Initialize the device */ int ide_init() { int dd_off; //dbglog(DBG_INFO, "ide_init: initializing\n"); /* Reset */ outp(0x3f6, 0x0e); thd_sleep(10); outp(0x3f6, 0x0a); thd_sleep(10); if(wait_controller() < 0) { return -1; } outp(0x1f6,0xa0); /* get info on first drive. 0xb0 == 2nd */ outp(0x1f7,0xec); /* get drive info data */ if(wait_data() < 0) { return -1; } for (dd_off=0; dd_off<256; dd_off++) { dd[dd_off] = inpw(0x1f0); } hd_cyls = dd[1]; hd_heads = dd[3]; hd_sects = dd[6]; ds_printf("DS_IDE: Detected %s, %dMB, CHS (%d/%d/%d)\n", get_ascii(dd, 27, 46), (hd_cyls * hd_heads * hd_sects * 512L) / (1024L*1024L), hd_cyls, hd_heads, hd_sects); return 0; } void ide_shutdown() { } <file_sep>/modules/s3m/libs3mplay/Makefile #LibS3MPlay (C) PH3NOM #Based on work of <NAME> TARGET = libs3mplay.a OBJS = libs3mplay.o include $(KOS_BASE)/addons/Makefile.prefab <file_sep>/modules/opkg/libopk.c #include <errno.h> #include <ini.h> #include <stdlib.h> #include <stdio.h> #include <string.h> // Public interface. #pragma GCC visibility push(default) #include "opk.h" #pragma GCC visibility pop // Internal interfaces. #include "unsqfs.h" #include "exceptions.h" #define HEADER "Desktop Entry" struct OPK { struct PkgData *pdata; void *buf; struct INI *ini; }; struct OPK *opk_open(const char *opk_filename) { struct OPK *opk = (struct OPK *)malloc(sizeof(*opk)); if (!opk/* || opk == 0xffffffff*/) return NULL; EXPT_GUARD_ASSIGN(opk->pdata, opk_sqfs_open(opk_filename), free(opk); EXPT_GUARD_RETURN NULL); if (!opk->pdata) { free(opk); return NULL; } opk->buf = NULL; return opk; } int opk_read_pair(struct OPK *opk, const char **key_chars, size_t *key_size, const char **val_chars, size_t *val_size) { return ini_read_pair(opk->ini, key_chars, key_size, val_chars, val_size); } int opk_open_metadata(struct OPK *opk, const char **filename) { /* Free previous meta-data information */ if (opk->buf) { ini_close(opk->ini); free(opk->buf); } opk->buf = NULL; /* Get the name of the next .desktop */ const char *name; int err = opk_sqfs_get_metadata(opk->pdata, &name); if (err <= 0) return err; /* Extract the meta-data from the OD package */ void *buf; size_t buf_size; err = opk_sqfs_extract_file(opk->pdata, name, &buf, &buf_size); if (err) return err; struct INI *ini = ini_open_mem(buf, buf_size); if (!ini) { err = -ENOMEM; goto err_free_buf; } const char *section; size_t section_len; int has_section = ini_next_section(ini, &section, &section_len); if (has_section < 0) { err = has_section; goto error_ini_close; } /* The [Desktop Entry] section must be the first section of the * .desktop file. */ if (!has_section || strncmp(HEADER, section, section_len)) { printf("%s: not a proper desktop entry file\n", name); err = -EIO; goto error_ini_close; } opk->buf = buf; opk->ini = ini; if (filename) *filename = name; return 1; error_ini_close: ini_close(ini); err_free_buf: free(buf); return err; } void opk_close(struct OPK *opk) { opk_sqfs_close(opk->pdata); if (opk->buf) { ini_close(opk->ini); free(opk->buf); } free(opk); } int opk_extract_file(struct OPK *opk, const char *name, void **data, size_t *size) { return opk_sqfs_extract_file(opk->pdata, name, data, size); } <file_sep>/commands/untgz/untgz.c /* * untgz.c -- Display contents and extract files from a gzip'd TAR file * * written by "<NAME>" <<EMAIL>> * adaptation to Unix by <NAME> <<EMAIL>> * various fixes by <NAME> <<EMAIL>> */ #include "ds.h" #include <time.h> #include <errno.h> #include <utime.h> #include <zlib/zlib.h> #include "console.h" /* values used in typeflag field */ #define REGTYPE '0' /* regular file */ #define AREGTYPE '\0' /* regular file */ #define LNKTYPE '1' /* link */ #define SYMTYPE '2' /* reserved */ #define CHRTYPE '3' /* character special */ #define BLKTYPE '4' /* block special */ #define DIRTYPE '5' /* directory */ #define FIFOTYPE '6' /* FIFO special */ #define CONTTYPE '7' /* reserved */ #define BLOCKSIZE 512 struct tar_header { /* byte offset */ char name[100]; /* 0 */ char mode[8]; /* 100 */ char uid[8]; /* 108 */ char gid[8]; /* 116 */ char size[12]; /* 124 */ char mtime[12]; /* 136 */ char chksum[8]; /* 148 */ char typeflag; /* 156 */ char linkname[100]; /* 157 */ char magic[6]; /* 257 */ char version[2]; /* 263 */ char uname[32]; /* 265 */ char gname[32]; /* 297 */ char devmajor[8]; /* 329 */ char devminor[8]; /* 337 */ char prefix[155]; /* 345 */ /* 500 */ }; union tar_buffer { char buffer[BLOCKSIZE]; struct tar_header header; }; enum { TGZ_EXTRACT, TGZ_LIST, TGZ_INVALID }; static char *TGZfname OF((const char *)); static void TGZnotfound OF((const char *)); static int getoct OF((char *, int)); static char *strtime OF((time_t *)); static int setfiletime OF((char *, time_t)); static int ExprMatch OF((char *, char *)); static int makedir OF((char *)); static int matchname OF((int, int, char **, char *)); static void error OF((const char *)); static int tar OF((gzFile, int, int, int, char **)); static void help OF((int)); //int main OF((int, char **)); char *prog; const char *TGZsuffix[] = { "\0", ".tar", ".tar.gz", ".taz", ".tgz", NULL }; /* return the file name of the TGZ archive */ /* or NULL if it does not exist */ static char *TGZfname (const char *arcname) { static char buffer[1024]; int origlen,i; strcpy(buffer,arcname); origlen = strlen(buffer); for (i=0; TGZsuffix[i]; i++) { strcpy(buffer+origlen,TGZsuffix[i]); if (strcmp(buffer,F_OK) == 0) return buffer; } return NULL; } /* error message for the filename */ static void TGZnotfound (const char *arcname) { int i; ds_printf("DS_ERROR: Couldn't find \n"); for (i=0;TGZsuffix[i];i++) ds_printf((TGZsuffix[i+1]) ? "%s%s, " : "or %s%s\n", arcname, TGZsuffix[i]); //exit(1); } /* convert octal digits to int */ /* on error return -1 */ static int getoct (char *p,int width) { int result = 0; char c; while (width--) { c = *p++; if (c == 0) break; if (c == ' ') continue; if (c < '0' || c > '7') return -1; result = result * 8 + (c - '0'); } return result; } /* convert time_t to string */ /* use the "YYYY/MM/DD hh:mm:ss" format */ static char *strtime (time_t *t) { struct tm *local; static char result[32]; local = localtime(t); sprintf(result, "%4d/%02d/%02d %02d:%02d:%02d", local->tm_year+1900, local->tm_mon+1, local->tm_mday, local->tm_hour, local->tm_min, local->tm_sec); return result; } /* set file time */ static int setfiletime (char *fname,time_t ftime) { //struct utimbuf settime; //settime.actime = settime.modtime = ftime; //return utime(fname,&settime); return 0; } /* regular expression matching */ #define ISSPECIAL(c) (((c) == '*') || ((c) == '/')) static int ExprMatch (char *string,char *expr) { while (1) { if (ISSPECIAL(*expr)) { if (*expr == '/') { if (*string != '\\' && *string != '/') return 0; string ++; expr++; } else if (*expr == '*') { if (*expr ++ == 0) return 1; while (*++string != *expr) if (*string == 0) return 0; } } else { if (*string != *expr) return 0; if (*expr++ == 0) return 1; string++; } } } /* recursive mkdir */ /* abort on ENOENT; ignore other errors like "directory already exists" */ /* return 1 if OK */ /* 0 on error */ static int makedir (char *newdir) { char *buffer = strdup(newdir); char *p; int len = strlen(buffer); if (len <= 0) { free(buffer); return 0; } if (buffer[len-1] == '/') { buffer[len-1] = '\0'; } #ifdef DS_ARCH_DC if (fs_mkdir(buffer) == -1) { free(buffer); return 1; } #elif DS_ARCH_PSP if (mkdir(buffer, 0777) == -1) { free(buffer); return 1; } #else if (mkdir(buffer) == -1) { free(buffer); return 1; } #endif p = buffer+1; while (1) { char hold; while(*p && *p != '\\' && *p != '/') p++; hold = *p; *p = 0; #ifdef DS_ARCH_DC if ((fs_mkdir(buffer) != 0) && (errno == ENOENT)) #elif DS_ARCH_PSP if ((mkdir(buffer, 0777) != 0) && (errno == ENOENT)) #else if ((mkdir(buffer) != 0) && (errno == ENOENT)) #endif { ds_printf("DS_ERROR: Couldn't create directory %s\n", buffer); free(buffer); return 0; } if (hold == 0) break; *p++ = hold; } free(buffer); return 1; } static int matchname (int arg,int argc,char **argv,char *fname) { if (arg == argc) /* no arguments given (untgz tgzarchive) */ return 1; while (arg < argc) if (ExprMatch(fname,argv[arg++])) return 1; return 0; /* ignore this for the moment being */ } /* tar file list or extract */ static int tar (gzFile in,int action,int arg,int argc,char **argv) { union tar_buffer buffer; int len; int err; int getheader = 1; int remaining = 0; FILE *outfile = NULL; char fname[BLOCKSIZE]; int tarmode; time_t tartime; if (action == TGZ_LIST) ds_printf(" date time size file\n" " ---------- -------- --------- -----------------------------\n"); while (1) { len = gzread(in, &buffer, BLOCKSIZE); if (len < 0) error(gzerror(in, &err)); /* * Always expect complete blocks to process * the tar information. */ if (len != BLOCKSIZE) { action = TGZ_INVALID; /* force error exit */ remaining = 0; /* force I/O cleanup */ } /* * If we have to get a tar header */ if (getheader == 1) { /* * if we met the end of the tar * or the end-of-tar block, * we are done */ if ((len == 0) || (buffer.header.name[0] == 0)) break; tarmode = getoct(buffer.header.mode,8); tartime = (time_t)getoct(buffer.header.mtime,12); if (tarmode == -1 || tartime == (time_t)-1) { buffer.header.name[0] = 0; action = TGZ_INVALID; } strcpy(fname,buffer.header.name); switch (buffer.header.typeflag) { case DIRTYPE: if (action == TGZ_LIST) ds_printf("DS_INF: %s <dir> %s\n",strtime(&tartime),fname); if (action == TGZ_EXTRACT) { makedir(fname); setfiletime(fname,tartime); } break; case REGTYPE: case AREGTYPE: remaining = getoct(buffer.header.size,12); if (remaining == -1) { action = TGZ_INVALID; break; } if (action == TGZ_LIST) ds_printf("DS_INF: %s %9d %s\n",strtime(&tartime),remaining,fname); else if (action == TGZ_EXTRACT) { if (matchname(arg,argc,argv,fname)) { outfile = fopen(fname,"wb"); if (outfile == NULL) { /* try creating directory */ char *p = strrchr(fname, '/'); if (p != NULL) { *p = '\0'; makedir(fname); *p = '/'; outfile = fopen(fname,"wb"); } } if (outfile != NULL) ds_printf("DS_PROCESS: Extracting %s\n",fname); else ds_printf("DS_ERROR: Couldn't create %s\n",fname); } else outfile = NULL; } getheader = 0; break; default: if (action == TGZ_LIST) ds_printf("DS_INF: %s <---> %s\n",strtime(&tartime),fname); break; } } else { unsigned int bytes = (remaining > BLOCKSIZE) ? BLOCKSIZE : remaining; if (outfile != NULL) { if (fwrite(&buffer,sizeof(char),bytes,outfile) != bytes) { ds_printf("DS_ERROR: Error writing %s -- skipping\n",fname); fclose(outfile); outfile = NULL; remove(fname); } } remaining -= bytes; } if (remaining == 0) { getheader = 1; if (outfile != NULL) { fclose(outfile); outfile = NULL; if (action != TGZ_INVALID) setfiletime(fname,tartime); } } /* * Abandon if errors are found */ if (action == TGZ_INVALID) { ds_printf("DS_ERROR: Broken archive\n"); break; } } if (gzclose(in) != Z_OK) ds_printf("DS_ERROR: failed gzclose\n"); return 0; } /* ============================================================ */ static void help(int exitval) { ds_printf("Usage: untgz file.tgz extract all files\n" " untgz file.tgz fname ... extract selected files\n" " untgz -l file.tgz list archive contents\n"); //" untgz -h display this help\n"); //exit(exitval); } static void error(const char *msg) { ds_printf("DS_ERROR: %s\n", msg); //exit(1); } /* ============================================================ */ int main(int argc, char *argv[]) { int action = TGZ_EXTRACT; int arg = 1; char *TGZfile; gzFile *f; prog = strrchr(argv[0],'\\'); if (prog == NULL) { prog = strrchr(argv[0],'/'); if (prog == NULL) { prog = strrchr(argv[0],':'); if (prog == NULL) prog = argv[0]; else prog++; } else prog++; } else prog++; if (argc == 1) help(0); if (strcmp(argv[arg],"-l") == 0) { action = TGZ_LIST; if (argc == ++arg) help(0); } else if (strcmp(argv[arg],"-h") == 0) { help(0); } if ((TGZfile = TGZfname(argv[arg])) == NULL) TGZnotfound(argv[arg]); ++arg; if ((action == TGZ_LIST) && (arg != argc)) help(1); /* * Process the TGZ file */ switch(action) { case TGZ_LIST: case TGZ_EXTRACT: f = gzopen(TGZfile,"rb"); if (f == NULL) { ds_printf("DS_ERROR: Couldn't gzopen %s\n",TGZfile); return CMD_ERROR; } tar(f, action, arg, argc, argv); break; default: ds_printf("DS_ERROR: Unknown option\n"); return CMD_ERROR; } return CMD_OK; } <file_sep>/applications/speedtest/Makefile # # Speedtest App for DreamShell # Copyright (C) 2014 megavolt85 # SUBDIRS = modules include ../../sdk/Makefile.cfg APP_NAME = speedtest APP_DIR = $(DS_BUILD)/apps/$(APP_NAME) DEPS = modules/app_$(APP_NAME).klf all: install $(DEPS): modules/module.c cd modules && make clean: cd modules && make clean && cd ../ install: app.xml $(DEPS) -mkdir -p $(APP_DIR) -mkdir -p $(APP_DIR)/modules cp modules/app_$(APP_NAME).klf $(APP_DIR)/modules/app_$(APP_NAME).klf cp app.xml $(APP_DIR)/app.xml cp -R images $(APP_DIR) cp -R fonts $(APP_DIR) <file_sep>/src/drivers/spi.c /** * Copyright (c) 2011-2015 by SWAT <<EMAIL>> * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Dreamcast SCIF <=> SPI interface * * SCIF SD Card * ----------------------- * RTS (SPI CS) --> /CS * CTS (SPI CLK) --> CLK * TX (SPI DOUT) --> DIN * RX (SPI DIN) <-- DOUT */ #include <kos.h> #include <dc/fs_dcload.h> #include "drivers/spi.h" #include "drivers/sh7750_regs.h" #define _NO_VIDEO_H #include "console.h" #ifdef DEBUG #define SPI_DEBUG //#define SPI_DEBUG_RW #endif #define MSB 0x80 static uint16 pwork = 0; static mutex_t spi_mutex = MUTEX_INITIALIZER; static int spi_inited = 0; static int spi_delay = SPI_DEFAULT_DELAY; static void spi_custom_delay(void); //static void spi_max_speed_delay(void); #define spi_max_speed_delay() /*__asm__("nop\n\tnop\n\tnop\n\tnop\n\tnop")*/ #define RX_BIT() (reg_read_16(SCSPTR2) & SCSPTR2_SPB2DT) #define TX_BIT() \ _pwork = b & MSB ? (_pwork | SCSPTR2_SPB2DT) : (_pwork & ~SCSPTR2_SPB2DT); \ reg_write_16(SCSPTR2, _pwork) #define CTS_ON() \ reg_write_16(SCSPTR2, _pwork | SCSPTR2_CTSDT); \ if(spi_delay == SPI_DEFAULT_DELAY) spi_max_speed_delay(); \ else spi_custom_delay() #define CTS_ON_FAST() reg_write_16(SCSPTR2, _pwork | SCSPTR2_CTSDT); spi_max_speed_delay() #define CTS_OFF() reg_write_16(SCSPTR2, _pwork & ~SCSPTR2_CTSDT) #ifdef SPI_DEBUG static void dump_regs() { uint32 gpio; char gpios[512]; char gr[32]; int i = 0; pwork = reg_read_16(SCSPTR2); gpio = reg_read_32(PCTRA); dbglog(DBG_DEBUG, "SCIF registers: \n" " SCSCR2: %04x\n" " SCSMR2: %04x\n" " SCFCR2: %04x\n" " SCSSR2: %04x\n" " SCLSR2: %04x\n" " SCSPTR2: %04x\n" " TX: %d\n" " RX: %02x\n" " CLK: %d\n" " CS: %d\n\n", reg_read_16(SCSCR2), reg_read_16(SCSMR2), reg_read_16(SCFCR2), reg_read_16(SCSSR2), reg_read_16(SCLSR2), pwork, (int)(pwork & SCSPTR2_SPB2DT), (uint8)(pwork & 0x0001), (int)(pwork & SCSPTR2_CTSDT), (int)(pwork & SCSPTR2_RTSDT)); dbglog(DBG_DEBUG, "GPIO registers: \n" " GPIOIC: %08lx\n" " PDTRA: %08lx\n" " PCTRA: %08lx\n\n", reg_read_32(GPIOIC), reg_read_16(PDTRA), gpio); for(i = 0; i < 10; i++) { sprintf(gr, " GPIO_%d: %d\n", i, (int)(gpio & (1 << i))); if(!i) { strcpy(gpios, gr); } else { strcat(gpios, gr); } } dbglog(DBG_DEBUG, "%s\n", gpios); } #endif /** * Initializes the SPI interface. * */ int spi_init(int use_gpio) { if(spi_inited) { return 0; } if(*DCLOADMAGICADDR == DCLOADMAGICVALUE && dcload_type == DCLOAD_TYPE_SER) { dbglog(DBG_KDEBUG, "scif_spi_init: no spi device -- using " "dcload-serial\n"); return -1; } scif_shutdown(); #ifdef SPI_DEBUG dump_regs(); #endif int cable = CT_NONE; uint32 reg; // TX:1 CTS:0 RTS:1 (spiout:1 spiclk:0 spics:1) pwork = SCSPTR2_SPB2IO | SCSPTR2_CTSIO | SCSPTR2_RTSIO | SCSPTR2_SPB2DT | SCSPTR2_RTSDT; reg_write_16(SCSCR2, 0); reg_write_16(SCSMR2, 0); reg_write_16(SCFCR2, 0); reg_write_16(SCSPTR2, pwork); reg_write_16(SCSSR2, 0); reg_write_16(SCLSR2, 0); reg_write_16(SCSCR2, 0); spi_cs_off(SPI_CS_SCIF_RTS); if(use_gpio) { cable = vid_check_cable(); if(cable != CT_VGA && cable != CT_RGB) { reg_write_16(PDTRA, 0); reg_write_32(PCTRA, 0); reg_write_16(PDTRA, PDTRA_BIT(SPI_CS_GPIO_VGA) | PDTRA_BIT(SPI_CS_GPIO_RGB)); /* disable */ reg = reg_read_32(PCTRA); reg &= ~PCTRA_PBNPUP(SPI_CS_GPIO_VGA); reg |= PCTRA_PBOUT(SPI_CS_GPIO_VGA); reg &= ~PCTRA_PBNPUP(SPI_CS_GPIO_RGB); reg |= PCTRA_PBOUT(SPI_CS_GPIO_RGB); reg_write_32(PCTRA, reg); spi_cs_off(SPI_CS_GPIO_VGA); spi_cs_off(SPI_CS_GPIO_RGB); } else if(cable != CT_VGA) { reg_write_16(PDTRA, 0); reg_write_32(PCTRA, 0); reg_write_16(PDTRA, PDTRA_BIT(SPI_CS_GPIO_VGA)); /* disable */ reg = reg_read_32(PCTRA); reg &= ~PCTRA_PBNPUP(SPI_CS_GPIO_VGA); reg |= PCTRA_PBOUT(SPI_CS_GPIO_VGA); reg_write_32(PCTRA, reg); spi_cs_off(SPI_CS_GPIO_VGA); } else { ; } } #ifdef SPI_DEBUG dump_regs(); #endif spi_set_delay(SPI_DEFAULT_DELAY); spi_inited = 1; return 0; } int spi_shutdown() { if(spi_inited) { mutex_destroy(&spi_mutex); scif_init(); spi_inited = 0; return 0; } return -1; } void spi_set_delay(int delay) { spi_delay = delay; #ifdef SPI_DEBUG dbglog(DBG_DEBUG, "spi_set_delay: %d\n", spi_delay); #endif } int spi_get_delay() { return spi_delay; } // 1.5uSEC delay static void spi_low_speed_delay(void) { timer_prime(TMU1, 2000000, 0); timer_clear(TMU1); timer_start(TMU1); while(!timer_clear(TMU1)); while(!timer_clear(TMU1)); while(!timer_clear(TMU1)); timer_stop(TMU1); } static void spi_custom_delay(void) { timer_prime(TMU1, spi_delay, 0); timer_clear(TMU1); timer_start(TMU1); while(!timer_clear(TMU1)); timer_stop(TMU1); } void spi_cs_on(int cs) { // mutex_lock(&spi_mutex); uint16 reg; switch(cs) { case SPI_CS_SCIF_RTS: pwork &= ~SCSPTR2_RTSDT; reg_write_16(SCSPTR2, pwork); break; case SPI_CS_GPIO_VGA: case SPI_CS_GPIO_RGB: reg = reg_read_16(PDTRA); reg &= ~(1 << cs); reg_write_16(PDTRA, reg); break; default: break; } #ifdef SPI_DEBUG dbglog(DBG_DEBUG, "spi_cs_on: %d\n", cs); #endif } void spi_cs_off(int cs) { uint16 reg; switch(cs) { case SPI_CS_SCIF_RTS: pwork |= SCSPTR2_RTSDT; reg_write_16(SCSPTR2, pwork); break; case SPI_CS_GPIO_VGA: case SPI_CS_GPIO_RGB: reg = reg_read_16(PDTRA); reg |= (1 << cs); reg_write_16(PDTRA, reg); break; default: break; } // mutex_unlock(&spi_mutex); #ifdef SPI_DEBUG dbglog(DBG_DEBUG, "spi_cs_off: %d\n", cs); #endif } /** * Sends a byte over the SPI bus. * * \param[in] b The byte to send. */ void spi_cc_send_byte(register uint8 b) { register uint16 _pwork; _pwork = pwork; TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ #ifdef SPI_DEBUG_RW dbglog(DBG_DEBUG, "spi_send_byte: %02x\n", b); //dump_regs(); #endif } void spi_send_byte(register uint8 b) { register uint16 _pwork; _pwork = pwork; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1); CTS_OFF(); /* SPI clock OFF */ #ifdef SPI_DEBUG_RW dbglog(DBG_DEBUG, "spi_send_byte: %02x\n", b); //dump_regs(); #endif } /** * Receives a byte from the SPI bus. * * \returns The received byte. */ uint8 spi_cc_rec_byte() { register uint8 b; register uint16 _pwork; _pwork = pwork; b = 0xff; TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ #ifdef SPI_DEBUG_RW dbglog(DBG_DEBUG, "spi_rec_byte: %02x\n", b); //dump_regs(); #endif return b; } uint8 spi_rec_byte() { register uint8 b; register uint16 _pwork; _pwork = pwork; b = 0xff; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ #ifdef SPI_DEBUG_RW dbglog(DBG_DEBUG, "spi_rec_byte: %02x\n", b); //dump_regs(); #endif return b; } /** * Send and receive a byte to/from the SPI bus. * * \param[in] b The byte to send. * \returns The received byte. */ uint8 spi_cc_sr_byte(register uint8 b) { register uint16 _pwork; _pwork = pwork; #ifdef SPI_DEBUG_RW dbglog(DBG_DEBUG, "spi_sr_byte: send: %02x\n", b); //dump_regs(); #endif TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ #ifdef SPI_DEBUG_RW dbglog(DBG_DEBUG, "spi_sr_byte: receive: %02x\n", b); //dump_regs(); #endif return b; } uint8 spi_sr_byte(register uint8 b) { register uint16 _pwork; _pwork = pwork; #ifdef SPI_DEBUG_RW dbglog(DBG_DEBUG, "spi_sr_byte: send: %02x\n", b); //dump_regs(); #endif TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ #ifdef SPI_DEBUG_RW dbglog(DBG_DEBUG, "spi_sr_byte: receive: %02x\n", b); //dump_regs(); #endif return b; } /** * Slow send and receive a byte to/from the SPI bus. * * \param[in] b The byte to send. * \returns The received byte. */ uint8 spi_slow_sr_byte(register uint8 b) { register int cnt; #ifdef SPI_DEBUG_RW dbglog(DBG_DEBUG, "spi_slow_sr_byte: send: %02x\n", b); #endif for (cnt = 0; cnt < 8; cnt++) { pwork = b & MSB ? (pwork | SCSPTR2_SPB2DT) : (pwork & ~SCSPTR2_SPB2DT); reg_write_16(SCSPTR2, pwork); spi_low_speed_delay(); pwork |= SCSPTR2_CTSDT; reg_write_16(SCSPTR2, pwork); b = (b << 1) | RX_BIT(); spi_low_speed_delay(); pwork &= ~SCSPTR2_CTSDT; reg_write_16(SCSPTR2, pwork); } #ifdef SPI_DEBUG_RW dbglog(DBG_DEBUG, "spi_slow_sr_byte: receive: %02x\n", b); //dump_regs(); #endif return b; } /** * Sends data contained in a buffer over the SPI bus. * * \param[in] data A pointer to the buffer which contains the data to send. * \param[in] len The number of bytes to send. */ void spi_cc_send_data(const uint8* data, uint16 len) { do { /* Used send/receive byte because only receive works unstable */ spi_cc_sr_byte(*data++); } while(--len); } void spi_send_data(const uint8* data, uint16 len) { register uint8 b; register uint16 _pwork; _pwork = pwork; /* Used send/receive byte because only receive works unstable */ while(len) { b = data[0]; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ b = data[1]; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ b = data[2]; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ b = data[3]; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ data += 4; len -= 4; } } /** * Receives multiple bytes from the SPI bus and writes them to a buffer. * * \param[out] buffer A pointer to the buffer into which the data gets written. * \param[in] len The number of bytes to read. */ void spi_cc_rec_data(uint8* buffer, uint16 len) { do { *buffer++ = spi_rec_byte(); } while(--len); } void spi_rec_data(uint8* buffer, uint16 len) { register uint8 b; register uint16 _pwork; // register uint32 tmp __asm__("r1"); _pwork = pwork; while(len) { // tmp = 0; b = 0xff; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ buffer[0] = b; // tmp |= b; b = 0xff; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ buffer[1] = b; // tmp |= b << 8; b = 0xff; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ buffer[2] = b; // tmp |= b << 16; b = 0xff; TX_BIT(); CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ CTS_ON_FAST(); /* SPI clock ON */ b = (b << 1) | RX_BIT(); /* SPI data input */ CTS_OFF(); /* SPI clock OFF */ buffer[3] = b; // tmp |= b << 24; // __asm__ __volatile__("mov r1, r0\nmovca.l r0, @%0\n" : : "r" ((uint32)buffer)); // *(uint32*)buffer = tmp; buffer += 4; len -= 4; } } <file_sep>/modules/aicaos/Makefile # # aicaos module for DreamShell # Copyright (C) 2013-2014 SWAT # http://www.dc-swat.ru # TARGET_NAME = aicaos TARGET_SPU = $(TARGET_NAME).drv OBJS = module.o sh4/main.o sh4/aica_sh4.o aica_common_sh4.o sh4/aica_syscalls.o DBG_LIBS = -lds EXPORTS_FILE = exports.txt OPKG_DATA = default.desktop install.lua $(TARGET_NAME).klf $(TARGET_SPU) VER_MAJOR = 1 VER_MINOR = 0 VER_MICRO = 1 KOS_CFLAGS += -I../../include/aicaos all: rm-elf $(TARGET_SPU) include ../../sdk/Makefile.loadable aica_common_sh4.o: aica_common.c $(KOS_CC) $(KOS_CFLAGS) -c $< -o $@ $(TARGET_SPU): make -C arm SPUTARGET=$(TARGET_SPU) make -C arm SPUTARGET=$(TARGET_SPU) install clean: arm-clean arm-clean: make -C arm clean SPUTARGET=$(TARGET_SPU) rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_SPU) install: $(TARGET) $(TARGET_SPU) $(TARGET_LIB) #opkg -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_BUILD)/firmware/aica/$(TARGET_SPU) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_SPU) $(DS_BUILD)/firmware/aica/$(TARGET_SPU) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/modules/luaGUI/module.c /* DreamShell ##version## module.c - luaGUI module Copyright (C)2007-2013 SWAT */ #include <kos.h> #include <kos/exports.h> #include "ds.h" #include "lua/tolua.h" DEFAULT_MODULE_HEADER(luaGUI); int tolua_GUI_open(lua_State* tolua_S); typedef struct lua_callback_data { lua_State *state; const char *script; } lua_callback_data_t; static void luaCallbackf(void *data) { lua_callback_data_t *d = (lua_callback_data_t *) data; //ds_printf("Callback: %s %p\n", d->script, d->state); LuaDo(LUA_DO_STRING, d->script, (lua_State *) d->state); //ds_printf("Callback called\n"); } static void free_lua_callack(void *data) { if(data == NULL) { return; } lua_callback_data_t *d = (lua_callback_data_t*) data; free((void*)d->script); free(data); } GUI_Callback *GUI_LuaCallbackCreate(int appId, const char *luastring) { App_t *app = GetAppById(appId); if(app == NULL) { ds_printf("DS_ERROR: Can't find app: %d\n", appId); return NULL; } lua_callback_data_t *d = (lua_callback_data_t*) malloc(sizeof(lua_callback_data_t)); d->script = strdup(luastring); d->state = app->lua; //ds_printf("Created callback: str=%s state=%p app=%s lua=%p\n", d->script, d->state, app->name, app->lua); return GUI_CallbackCreate((GUI_CallbackFunction *) luaCallbackf, (GUI_CallbackFunction *) free_lua_callack, (void *) d); } int lib_open(klibrary_t * lib) { lua_State *L = GetLuaState(); if(L != NULL) { tolua_GUI_open(GetLuaState()); } RegisterLuaLib(lib_get_name(), (LuaRegLibOpen *)tolua_GUI_open); return nmmgr_handler_add(&ds_luaGUI_hnd.nmmgr); } int lib_close(klibrary_t * lib) { UnregisterLuaLib(lib_get_name()); return nmmgr_handler_remove(&ds_luaGUI_hnd.nmmgr); } <file_sep>/src/app/app.c /***************************** * DreamShell ##version## * * app.c * * DreamShell App * * Created by SWAT * * http://www.dc-swat.ru * ****************************/ #include "ds.h" #include "vmu.h" #include <stdlib.h> static Item_list_t *apps; static int curOpenedApp; static int first_open = 1; static int prev_width = 0; static int prev_height = 0; static void FreeApp(void *app) { if(app == NULL) return; free(app); app = NULL; } int InitApps() { curOpenedApp = 0; if((apps = listMake()) == NULL) { return -1; } return 0; } void ShutdownApps() { listDestroy(apps, (listFreeItemFunc *) FreeApp); curOpenedApp = 0; } Item_list_t *GetAppList() { return apps; } App_t *GetAppById(int id) { Item_t *i = listGetItemById(apps, id); if(i != NULL) return (App_t *) i->data; else return NULL; } App_t *GetAppByFileName(const char *fn) { App_t *a; Item_t *i; SLIST_FOREACH(i, apps, list) { a = (App_t *) i->data; if (!strncmp(fn, a->fn, NAME_MAX)) return a; } return NULL; } App_t *GetAppByName(const char *name) { Item_t *i = listGetItemByName(apps, name); if(i != NULL) return (App_t *) i->data; else return NULL; } App_t *GetAppByExtension(const char *ext) { App_t *a; Item_t *i; SLIST_FOREACH(i, apps, list) { a = (App_t *) i->data; if (strcasestr(a->ext, ext) != NULL) return a; } return NULL; } App_t *GetAppsByExtension(const char *ext, App_t **app_list, size_t count) { App_t *a; Item_t *i; size_t cnt = 0; SLIST_FOREACH(i, apps, list) { a = (App_t *) i->data; if (strcasestr(a->ext, ext) != NULL && app_list != NULL) { app_list[cnt++] = a; } if(cnt >= count) { goto result; } } goto result; result: return cnt ? app_list[cnt - 1] : NULL; } App_t *GetCurApp() { return GetAppById(curOpenedApp); } int IsFileSupportedByApp(App_t *app, const char *filename) { char *ext = strrchr(filename, '.'); if(!ext) return 0; if (strcasestr(app->ext, ext) != NULL) { return 1; } return 0; } void UnLoadOldApps() { App_t *a; Item_t *i; SLIST_FOREACH(i, apps, list) { a = (App_t *) i->data; if(a && a->state & APP_STATE_WAIT_UNLOAD) { UnLoadApp(a); //if(a->lua != NULL && curOpenedApp == 0) { //ResetLua(); //} } } } App_t *AddApp(const char *fn) { App_t *a, *at; Item_t *i; file_t fd = FILEHND_INVALID; mxml_node_t *tree = NULL, *node = NULL; char *name = NULL, *icon = NULL; char file[NAME_MAX]; a = (App_t *) calloc(1, sizeof(App_t)); if(a == NULL) { ds_printf("DS_ERROR: Memory allocation error\n"); return NULL; } realpath(fn, file); fd = fs_open(file, O_RDONLY); if(fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open file %s\n", file); goto error; } if((tree = mxmlLoadFd(NULL, fd, NULL)) == NULL) { ds_printf("DS_ERROR: XML file %s parsing error\n", file); goto error; } fs_close(fd); fd = FILEHND_INVALID; if((node = mxmlFindElement(tree, tree, "app", NULL, NULL, MXML_DESCEND)) == NULL) { ds_printf("DS_ERROR: XML file %s is not app\n", file); goto error; } name = FindXmlAttr("name", node, NULL); if(name == NULL) { ds_printf("DS_ERROR: App without name\n"); goto error; } if((at = GetAppByName(name)) != NULL) { mxmlDelete(tree); FreeApp(a); ds_printf("DS: App '%s' already exists\n", name); return at; } strncpy((char*)a->fn, file, sizeof(a->fn)); strncpy((char*)a->name, name, sizeof(a->name)); strncpy((char*)a->ver, FindXmlAttr("version", node, "1.0.0"), sizeof(a->ver)); strncpy((char*)a->ext, FindXmlAttr("extensions", node, ""), sizeof(a->ext)); icon = FindXmlAttr("icon", node, NULL); if(icon == NULL) { sprintf((char*)a->icon, "%s/gui/icons/normal/default_app.png", getenv("PATH")); } else { memset_sh4(file, 0, NAME_MAX); relativeFilePath_wb(file, a->fn, icon); // file[strlen(file)] = '\0'; strncpy((char*)a->icon, file, sizeof(a->icon)); } a->args = NULL; a->thd = NULL; a->lua = NULL; a->body = NULL; a->xml = NULL; a->resources = NULL; a->elements = NULL; if(tree) mxmlDelete(tree); //ds_printf("App: %s %s %s %s", a->fn, a->name, a->ver, a->icon); if((i = listAddItem(apps, LIST_ITEM_APP, a->name, a, sizeof(App_t))) == NULL) { goto error; } a->id = i->id; return a; error: if(tree) mxmlDelete(tree); if(a) FreeApp(a); if(fd != FILEHND_INVALID) fs_close(fd); return NULL; } int RemoveApp(App_t *app) { WaitApp(app); if(app->state & APP_STATE_OPENED) CloseApp(app, 1); if(app->state & APP_STATE_LOADED) UnLoadApp(app); //mxmlDelete(app->xml); listRemoveItem(apps, listGetItemById(apps, app->id), (listFreeItemFunc *) FreeApp); return 1; } int OpenApp(App_t *app, const char *args) { ds_printf("DS_PROCESS: Opening app %s\n", app->name); int onopen_called = 0; if(app == NULL) { ds_printf("DS_ERROR: %s: Bad app pointer - %p\n", __func__, app); return 0; } // ds_printf("State: %d %d %d %d", // app->state & APP_STATE_OPENED, // app->state & APP_STATE_LOADED, // app->state & APP_STATE_READY, // app->state & APP_STATE_SLEEP); if(app->state & APP_STATE_OPENED) { ds_printf("DS_WARNING: App %s already opened\n", app->name); return 1; } if(GetScreenOpacity() >= 1.0f && !ConsoleIsVisible() && !first_open) { vmu_draw_string("Loading..."); ScreenFadeOut(); thd_sleep(500); } if(args != NULL) { app->args = args; } //ds_printf("DS_DEBUG: Cur opened app: %d\n", curOpenedApp); if(curOpenedApp) { App_t *cur = GetCurApp(); if(cur != NULL && cur->state & APP_STATE_OPENED) { CloseApp(cur, (cur->state & APP_STATE_LOADED)); } curOpenedApp = 0; } if(app->state & APP_STATE_LOADED && app->state & APP_STATE_READY) { CallAppBodyEvent(app, "onopen"); onopen_called = 1; } if(!(app->state & APP_STATE_LOADED)) { LockVideo(); if(!LoadApp(app, 1)) { UnlockVideo(); goto error; } UnlockVideo(); } if(first_open && !ConsoleIsVisible()) { ScreenFadeOut(); } if((app->state & APP_STATE_LOADED) && !(app->state & APP_STATE_READY)) { if(!BuildAppBody(app)) { goto error; } } if(app->state & APP_STATE_READY) { if(app->state & APP_STATE_SLEEP) { SetAppSleep(app, 0); } if(app->body != NULL) { SDL_Rect rect = GUI_WidgetGetArea(app->body); if(first_open && !ConsoleIsVisible()) { first_open = 0; while(GetScreenOpacity() > 0.0f) thd_sleep(100); } if(rect.w != GetScreenWidth() || rect.h != GetScreenHeight()) { prev_width = GetScreenWidth(); prev_height = GetScreenHeight(); SetScreenMode(rect.w, rect.h, 0.0f, 0.0f, 1.0f); } //LockVideo(); GUI_ScreenSetContents(GUI_GetScreen(), app->body); //GUI_ScreenDoUpdate(GUI_GetScreen(), 1); UpdateActiveMouseCursor(); //DrawActiveMouseCursor(); //UnlockVideo(); } vmu_draw_string(app->name); app->state |= APP_STATE_OPENED; curOpenedApp = app->id; if(!onopen_called) { CallAppBodyEvent(app, "onopen"); } thd_sleep(100); } else { ShowConsole(); } if(args != NULL) { app->args = NULL; } ds_printf("DS_OK: App %s opened\n", app->name); if(GetScreenOpacity() < 1.0f) { // ScreenWaitUpdate(); ScreenFadeIn(); } return 1; error: if(args != NULL) app->args = NULL; if(GetScreenOpacity() < 1.0f) { ScreenFadeIn(); } vmu_draw_string("Error"); ShowConsole(); return 0; } int CloseApp(App_t *app, int unload) { if(app == NULL) { ds_printf("DS_ERROR: CloseApp: Bad app pointer - %p\n", app); return 0; } //ds_printf("DS_PROCESS: Closing app %s", app->name); if(!(app->state & APP_STATE_OPENED)) return 1; //if(GetScreenOpacity() >= 0.9f && !ConsoleIsVisible()) //ScreenFadeOut(); app->state &= ~APP_STATE_OPENED; WaitApp(app); //LockVideo(); //GUI_ScreenSetContents(GUI_GetScreen(), NULL); //UnLockVideo(); if(prev_width && (prev_width != GetScreenWidth() || prev_height != GetScreenHeight())) { SetScreenMode(prev_width, prev_height, 0.0f, 0.0f, 1.0f); } if(unload && (app->state & APP_STATE_LOADED)) { /* if(!UnLoadApp(app)) { ds_printf("DS_ERROR: CloseApp: App unloading error (id=%d)\n", app->id); //ShowConsole(); return 0; }*/ app->state |= APP_STATE_WAIT_UNLOAD; } if(!unload && (app->state & APP_STATE_LOADED)) { CallAppBodyEvent(app, "onclose"); SetAppSleep(app, 1); } if(app->id == curOpenedApp) { curOpenedApp = 0; } app->state &= ~APP_STATE_OPENED; // UnLoadApp(app); ds_printf("DS_OK: App %s closed%s\n", app->name, (unload ? " and unloaded." : ".")); return 1; } int SetAppSleep(App_t *app, int sleep) { if(app == NULL) { ds_printf("DS_ERROR: %s: Bad app pointer - %p\n", __func__, app); return 0; } if(sleep && (app->state & APP_STATE_SLEEP) == 0) { app->state |= APP_STATE_SLEEP; //CallAppBodyEvent(app, "onsleep"); } else if(!sleep && (app->state & APP_STATE_SLEEP)) { app->state &= ~APP_STATE_SLEEP; //CallAppBodyEvent(app, "onwakeup"); } else { return 0; } return 1; } int AddToAppBody(App_t *app, GUI_Widget *widget) { if(app == NULL) { ds_printf("DS_ERROR: %s: Bad app pointer - %p\n", __func__, app); return 0; } if(app->body && widget) GUI_ContainerAdd(app->body, widget); //GUI_ObjectDecRef((GUI_Object *) widget); return 1; } int RemoveFromAppBody(App_t *app, GUI_Widget *widget) { if(app == NULL) { ds_printf("DS_ERROR: %s: Bad app pointer - %p\n", __func__, app); return 0; } if(app->body && widget) GUI_ContainerRemove(app->body, widget); return 1; } int CallAppBodyEvent(App_t *app, char *event) { mxml_node_t *node; if(app->xml && (node = mxmlFindElement(app->xml, app->xml, "body", NULL, NULL, MXML_DESCEND)) != NULL) { const char *e = FindXmlAttr(event, node, NULL); if(e != NULL) { if(!strncmp(e, "export:", 7)) { return CallAppExportFunc(app, e); } else if(!strncmp(e, "console:", 8)) { if(dsystem_buff(e+8) == CMD_OK) return 1; } else { if(LuaDo(LUA_DO_STRING, e, app->lua) < 1) return 1; } } } return 0; } void WaitApp(App_t *app) { if(app->state & APP_STATE_PROCESS) { while(app->state & APP_STATE_PROCESS) thd_sleep(50); } } <file_sep>/modules/bflash/module.c /* DreamShell ##version## module.c - bflash module Copyright (C)2009-2014 SWAT */ #include "ds.h" #include "drivers/bflash.h" DEFAULT_MODULE_EXPORTS_CMD(bflash, "BootROM flasher"); int builtin_bflash_cmd(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s options args\n" "Options: \n" " -r, --read -Read flash sector(s) and write to file\n" " -w, --write -Write flash sector(s) from file (can be used with -a)\n" " -e, --erase -Erase flash sector(s)\n" " -a, --eraseall -Erase the whole flash chip\n" " -l, --list -Print list of supported devices\n" " -t, --sectors -Print list of device sectors\n" " -c, --check -Attempt to detect the flash chip\n\n", argv[0]); ds_printf("Arguments: \n" " -m, --manufacturer -Manufacturer id\n" " -d, --device -Device id\n" " -f, --file -Binary file (input or output)\n" " -b, --sector -Start sector\n" " -s, --size -Size to read\n\n" "Example: %s -w -f /cd/firmware.bios\n\n", argv[0]); return CMD_NO_ARG; } int bbflash_write = 0, bbflash_read = 0, bbflash_erase = 0, bbflash_eraseall = 0, bbflash_printlist = 0, bbflash_printsectors = 0, bbflash_check = 0; char *file = NULL; uint size = 0; uint32 sector = 0x0, mfr_id = 0x0, dev_id = 0x0; bflash_dev_t *dev = NULL; struct cfg_option options[] = { {"write", 'w', NULL, CFG_BOOL, (void *) &bbflash_write, 0}, {"read", 'r', NULL, CFG_BOOL, (void *) &bbflash_read, 0}, {"erase", 'e', NULL, CFG_BOOL, (void *) &bbflash_erase, 0}, {"eraseall", 'a', NULL, CFG_BOOL, (void *) &bbflash_eraseall, 0}, {"list", 'l', NULL, CFG_BOOL, (void *) &bbflash_printlist, 0}, {"sectors", 't', NULL, CFG_BOOL, (void *) &bbflash_printsectors, 0}, {"check", 'c', NULL, CFG_BOOL, (void *) &bbflash_check, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, {"sector", 'b', NULL, CFG_ULONG,(void *) &sector, 0}, {"size", 's', NULL, CFG_INT, (void *) &size, 0}, {"device", 'd', NULL, CFG_ULONG,(void *) &dev_id, 0}, {"manufacturer", 'm', NULL, CFG_ULONG,(void *) &mfr_id, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(bbflash_printlist) { size = 0, sector = 0; while (bflash_manufacturers[size].id != 0) { ds_printf(" %s [0x%04x]\n", bflash_manufacturers[size].name, bflash_manufacturers[size].id); while (bflash_devs[sector].id != 0) { if((bflash_manufacturers[size].id & 0xff) == (bflash_devs[sector].id >> 8 & 0xff)) { ds_printf(" %s [0x%04x] %d KB %s\n", bflash_devs[sector].name, bflash_devs[sector].id, bflash_devs[sector].size, (bflash_devs[sector].flags & F_FLASH_LOGIC_5V) ? ((bflash_devs[sector].flags & F_FLASH_LOGIC_3V) ? "3V,5V" : "5V") : "3V"); } sector++; } sector = 0; size++; } return CMD_OK; } if(bbflash_printsectors) { char ac[512], secb[32]; dev = bflash_find_dev(dev_id); if(dev == NULL) { ds_printf("DS_ERROR: Device 0x%04x not found\n", (uint16)dev_id); return CMD_ERROR; } for(sector = 0; sector < dev->sec_count; sector++) { memset(secb, 0, sizeof(secb)); sprintf(secb, "0x%06lx%s", dev->sectors[sector], (sector == dev->sec_count - 1) ? "" : ", "); if(sector % 4) { strcat(ac, secb); } else { if(sector) ds_printf("%s\n", ac); memset(ac, 0, sizeof(ac)); strcpy(ac, secb); } } if(sector) ds_printf("%s\n", ac); return CMD_OK; } if(bbflash_check) { if(bflash_detect(NULL, NULL) < 0) { return CMD_ERROR; } return CMD_OK; } if(bbflash_write && file != NULL) { if(bflash_auto_reflash(file, sector, bbflash_eraseall ? F_FLASH_ERASE_ALL : F_FLASH_ERASE_SECTOR) < 0) { return CMD_ERROR; } return CMD_OK; } if(bbflash_erase) { if(bflash_detect(NULL, &dev) < 0) { return CMD_ERROR; } ds_printf("DS_PROCESS: Erasing sector: 0x%08x\n", sector); if (bflash_erase_sector(dev, sector) < 0) { return CMD_ERROR; } ds_printf("DS_OK: Complete!\n"); return CMD_OK; } if(bbflash_eraseall) { if(bflash_detect(NULL, &dev) < 0) { return CMD_ERROR; } ds_printf("DS_PROCESS: Erasing full flash chip...\n"); if (bflash_erase_all(dev) < 0) { return CMD_ERROR; } ds_printf("DS_OK: Complete!\n"); return CMD_OK; } if(bbflash_read && file != NULL) { ds_printf("DS_PROCESS: Reading from 0x%08x size %d and writing to file %s\n", sector, size, file); file_t fw = fs_open(file, O_WRONLY | O_TRUNC | O_CREAT); if(fw < 0) { ds_printf("DS_ERROR: Can't create %s\n", file); return CMD_ERROR; } fs_write(fw, (uint8*)(BIOS_FLASH_ADDR | sector), size); fs_close(fw); ds_printf("DS_OK: Complete!\n"); return CMD_OK; } ds_printf("DS_ERROR: There is no option.\n"); return CMD_OK; } <file_sep>/lib/libparallax/Makefile # Parallax for DreamShell ##version## # # Makefile # (c)2002 <NAME> # (c)2014 SWAT TARGET = ../libparallax.a OBJS := $(patsubst %.c,%.o,$(wildcard src/*.c)) KOS_CFLAGS += -I../../include # Grab the shared Makefile pieces include ../../sdk/Makefile.library <file_sep>/lib/SDL_gui/NanoX.cc #include <kos.h> #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" #include "nano-X.h" #include "nanowm.h" extern "C" { char *GetWorkPath(); SDL_Surface *GetScreen(); void SetNanoXParams(SDL_Surface *surface, int w, int h, int bpp); void GetNanoXParams(SDL_Surface **surface, int *w, int *h, int *bpp); void SetNanoXEvent(SDL_Event *event); } GUI_NANOX::GUI_NANOX(const char *aname, int x, int y, int w, int h) : GUI_Widget(aname, x, y, w, h) { SDL_Surface *screen = GetScreen(); surface = GUI_SurfaceCreate("nanox_render", screen->flags, area.w, area.h, screen->format->BitsPerPixel, screen->format->Rmask, screen->format->Gmask, screen->format->Bmask, screen->format->Amask); SetNanoXParams(surface->GetSurface(), w, h, screen->format->BitsPerPixel); event_handler = NULL; if (GrOpen() < 0) { GUI_Exception("DS_ERROR: Cannot open graphics for NanoX\n"); } } GUI_NANOX::~GUI_NANOX() { GrClose(); SDL_Surface *screen = GetScreen(); SetNanoXParams(screen, screen->w, screen->h, screen->format->BitsPerPixel); surface->DecRef(); surface = NULL; if (event_handler) event_handler->DecRef(); event_handler = NULL; } void GUI_NANOX::DrawWidget(const SDL_Rect *clip) { if (parent == 0) return; if (surface) { SDL_Rect dr; SDL_Rect sr; sr.w = dr.w = surface->GetWidth(); sr.h = dr.h = surface->GetHeight(); sr.x = sr.y = 0; dr.x = area.x; dr.y = area.y + (area.h - dr.h) / 2; //if (GUI_ClipRect(&sr, &dr, clip)) parent->Draw(surface, &sr, &dr); } } void GUI_NANOX::SetGEventHandler(GUI_Callback *handler) { GUI_ObjectKeep((GUI_Object **) &event_handler, handler); } int GUI_NANOX::Event(const SDL_Event *event, int xoffset, int yoffset) { SetNanoXEvent((SDL_Event *)event); //GR_EVENT gevent; //GrGetNextEvent(&gevent); if(event_handler != NULL) { //printf("GUI_NANOX::Event: %d\n", event->type); event_handler->Call(this); } /* switch (gevent.type) { case GR_EVENT_TYPE_EXPOSURE: MarkChanged(); break; case GR_EVENT_TYPE_CLOSE_REQ: //GrClose(); break; }*/ return 0; } extern "C" { GUI_Widget *GUI_NANOX_Create(const char *name, int x, int y, int w, int h) { return new GUI_NANOX(name, x, y, w, h); } void GUI_NANOX_SetGEventHandler(GUI_Widget *widget, GUI_Callback *handler) { ((GUI_NANOX *) widget)->SetGEventHandler(handler); } } <file_sep>/modules/bitcoin/module.c /* DreamShell ##version## module.c - bitcoin module Copyright (C)2022 SWAT */ #include "ds.h" #include <secp256k1.h> DEFAULT_MODULE_EXPORTS_CMD(bitcoin, "Bitcoin Core"); void secp256k1_default_illegal_callback_fn(const char *message, void *data) { (void)data; ds_printf("DS_ERROR: %s\n", message); } void secp256k1_default_error_callback_fn(const char *message, void *data) { (void)data; ds_printf("DS_ERROR: %s\n", message); } static void print_hex(char *str, uint8 *buffer, size_t size) { char tmp[4]; memset(tmp, 0, sizeof(tmp)); for (size_t i = 0; i < size; ++i) { snprintf(tmp, 4, "%02x", buffer[i]); strncpy(str, tmp, 2); str += 2; } } // FIXME: More random size_t fill_random(uint8 *buffer, size_t size) { size_t i; for (i = 0; i < size; ++i) { buffer[i] = (rand() % 254) + 1; } return i; } int bitcoin_generate_keys(const char *output_filename) { /* Instead of signing the message directly, we must sign a 32-byte hash. * Here the message is "Hello, world!" and the hash function was SHA-256. * An actual implementation should just call SHA-256, but this case * hardcodes the output to avoid depending on an additional library. */ uint8 msg_hash[32] = { 0x31, 0x5F, 0x5B, 0xDB, 0x76, 0xD0, 0x78, 0xC4, 0x3B, 0x8A, 0xC0, 0x06, 0x4E, 0x4A, 0x01, 0x64, 0x61, 0x2B, 0x1F, 0xCE, 0x77, 0xC8, 0x69, 0x34, 0x5B, 0xFC, 0x94, 0xC7, 0x58, 0x94, 0xED, 0xD3 }; uint8 seckey[32]; uint8 randomize[32]; uint8 compressed_pubkey[33]; uint8 serialized_signature[64]; size_t len; int return_val; secp256k1_pubkey pubkey; secp256k1_ecdsa_signature sig; secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); ds_printf("DS_PROCESS: Generating Bitcoin keys...\n"); if (!ctx) { ds_printf("Failed to create secp256k1 context\n"); goto out; } if (!fill_random(randomize, sizeof(randomize))) { ds_printf("Failed to generate randomness\n"); goto out; } /* Randomizing the context is recommended to protect against side-channel * leakage See `secp256k1_context_randomize` in secp256k1.h for more * information about it. This should never fail. */ return_val = secp256k1_context_randomize(ctx, randomize); if (!return_val) { ds_printf("Failed to randomize context\n"); goto out; } /*** Key Generation ***/ /* If the secret key is zero or out of range (bigger than secp256k1's * order), we try to sample a new key. Note that the probability of this * happening is negligible. */ while (1) { return_val = fill_random(seckey, sizeof(seckey)); if (!return_val) { ds_printf("Failed to generate randomness\n"); goto out; } if (secp256k1_ec_seckey_verify(ctx, seckey)) { break; } } /* Public key creation using a valid context with a verified secret key should never fail */ return_val = secp256k1_ec_pubkey_create(ctx, &pubkey, seckey); if (!return_val) { ds_printf("Failed create public key\n"); goto out; } /* Serialize the pubkey in a compressed form(33 bytes). Should always return 1. */ len = sizeof(compressed_pubkey); return_val = secp256k1_ec_pubkey_serialize(ctx, compressed_pubkey, &len, &pubkey, SECP256K1_EC_COMPRESSED); if (!return_val) { ds_printf("Failed serialize the signature\n"); goto out; } /* Should be the same size as the size of the output, because we passed a 33 byte array. */ if (len != sizeof(compressed_pubkey)) { goto out; } /*** Signing ***/ /* Generate an ECDSA signature `noncefp` and `ndata` allows you to pass a * custom nonce function, passing `NULL` will use the RFC-6979 safe default. * Signing with a valid context, verified secret key * and the default nonce function should never fail. */ return_val = secp256k1_ecdsa_sign(ctx, &sig, msg_hash, seckey, NULL, NULL); if (!return_val) { ds_printf("Failed sign\n"); goto out; } /* Serialize the signature in a compact form. Should always return 1 * according to the documentation in secp256k1.h. */ return_val = secp256k1_ecdsa_signature_serialize_compact(ctx, serialized_signature, &sig); if (!return_val) { ds_printf("Failed serialize the signature\n"); goto out; } /*** Verification ***/ /* Deserialize the signature. This will return 0 if the signature can't be parsed correctly. */ return_val = secp256k1_ecdsa_signature_parse_compact(ctx, &sig, serialized_signature); if (!return_val) { ds_printf("Failed parsing the signature\n"); goto out; } /* Deserialize the public key. This will return 0 if the public key can't be parsed correctly. */ return_val = secp256k1_ec_pubkey_parse(ctx, &pubkey, compressed_pubkey, sizeof(compressed_pubkey)); if (!return_val) { ds_printf("Failed parsing the public key\n"); goto out; } /* Verify a signature. This will return 1 if it's valid and 0 if it's not. */ return_val = secp256k1_ecdsa_verify(ctx, &sig, msg_hash, &pubkey); if (!return_val) { ds_printf("DS_ERROR: Signature is invalid, please try again.\n"); goto out; } char _result_str[512]; char *result_str = _result_str; char hex_str[256]; memset(result_str, 0, sizeof(_result_str)); memset(hex_str, 0, sizeof(hex_str)); result_str = strcat(result_str, "Secret Key: 0x"); print_hex(hex_str, seckey, sizeof(seckey)); result_str = strncat(result_str, hex_str, sizeof(hex_str)); result_str = strcat(result_str, "\nPublic Key: 0x"); print_hex(hex_str, compressed_pubkey, sizeof(compressed_pubkey)); result_str = strncat(result_str, hex_str, sizeof(hex_str)); result_str = strcat(result_str, "\nSignature: 0x"); print_hex(hex_str, serialized_signature, sizeof(serialized_signature)); result_str = strncat(result_str, hex_str, sizeof(hex_str)); result_str = strcat(result_str, "\n"); if (output_filename) { file_t fd = fs_open(output_filename, O_WRONLY); if (fd < 0) { ds_printf("Can't open file: %s\n", output_filename); } else { fs_write(fd, result_str, strlen(result_str)); fs_close(fd); } } else { ds_printf(result_str); } ds_printf("DS_OK: Generated successfully.\n"); out: if (ctx) { secp256k1_context_destroy(ctx); } memset(seckey, 0, sizeof(seckey)); return (return_val ? CMD_OK : CMD_ERROR); } int builtin_bitcoin_cmd(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s options args\n" "Options: \n" " -g, --gen -Generate keys\n\n"); ds_printf("Arguments: \n" " -f, --file -Save keys to file instead of print screen\n\n" "Example: %s -g -f /ram/btc.txt\n\n", argv[0]); return CMD_NO_ARG; } int gen = 0; char *file = NULL; struct cfg_option options[] = { {"gen", 'g', NULL, CFG_BOOL, (void *) &gen, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if (gen) { return bitcoin_generate_keys(file); } return CMD_NO_ARG; } <file_sep>/modules/adx/LibADX/libadx.c /* This File is a part of Dreamcast Media Center ADXCORE (c)2012 Josh "PH3NOM" Pearson <EMAIL> decoder algorithm: adv2wav(c)2001 BERO http://www.geocities.co.jp/Playtown/2004/ <EMAIL> adx info from: http://ku-www.ss.titech.ac.jp/~yatsushi/adx.html */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <kos/thread.h> #include "libadx.h" #include "audio/snddrv.h" #define BASEVOL 0x4000 #define PCM_BUF_SIZE 1024*1024 /* A few global vars, should move this into a struct/handle */ static ADX_INFO ADX_Info; static FILE *adx_in; static int pcm_samples, loop; static unsigned char adx_buf[ADX_HDR_SIZE]; /* Local function definitions */ static int adx_parse( unsigned char *buf ); static void adx_to_pcm( short *out, unsigned char *in, PREV *prev ); static void *adx_thread(void *p); static void *pause_thd(void *p); static int read_be16(unsigned char *buf) /* ADX File Format is Big Endian */ { return (buf[0]<<8)|buf[1]; } static long read_be32(unsigned char *buf) { return (buf[0]<<24)|(buf[1]<<16)|(buf[2]<<8)|buf[3]; } /* Start Straming the ADX in a seperate thread */ int adx_dec( char * adx_file, int loop_enable ) { printf("LibADX: Checking Status\n"); if( snddrv.dec_status!=SNDDEC_STATUS_NULL ) { printf("LibADX: Already Running in another process!\n"); return 0; } adx_in = fopen(adx_file,"rb"); /* Make sure file exists */ if(adx_in==NULL) { printf("LibADX: Can't open file %s\n", adx_file); return 0; } if(adx_parse( adx_buf ) < 1) /* Make sure we are working with an ADX file */ { printf("LibADX: Invalid File Header\n"); fclose( adx_in ); return 0; } printf("LibADX: Starting\n"); loop = loop_enable; thd_create(0, adx_thread, NULL ); return 1; } /* Pause Streaming the ADX (if streaming) */ int adx_pause() { if( snddrv.dec_status != SNDDEC_STATUS_STREAMING ) return 0; printf("LibADX: Pausing\n"); snddrv.dec_status = SNDDEC_STATUS_PAUSING; while( snddrv.dec_status != SNDDEC_STATUS_PAUSED ) thd_pass(); thd_create(0, pause_thd, NULL ); return 1; } /* Resume Streaming the ADX (if paused) */ int adx_resume() { if( snddrv.dec_status != SNDDEC_STATUS_PAUSED ) return 0; printf("LibADX: Resuming\n"); snddrv.dec_status = SNDDEC_STATUS_RESUMING; while( snddrv.dec_status != SNDDEC_STATUS_STREAMING ) thd_pass(); return 1; } /* Restart Streaming the ADX */ int adx_restart() { if( snddrv.dec_status != SNDDEC_STATUS_STREAMING ) return 0; printf("LibADX: Restarting\n"); snddrv.dec_status = SNDDEC_STATUS_PAUSING; while( snddrv.dec_status != SNDDEC_STATUS_PAUSED ) thd_pass(); pcm_samples = ADX_Info.samples; fseek( adx_in, ADX_Info.sample_offset+ADX_CRI_SIZE, SEEK_SET ); snddrv.dec_status = SNDDEC_STATUS_STREAMING; return 1; } /* Stop Straming the ADX */ int adx_stop() { if( snddrv.dec_status != SNDDEC_STATUS_STREAMING ) return 0; printf("LibADX: Stopping\n"); loop=0; snddrv.dec_status = SNDDEC_STATUS_DONE; while( snddrv.dec_status != SNDDEC_STATUS_NULL ) thd_pass(); return 1; } /* Read and parse the ADX File header then seek to the begining sample offset */ static int adx_parse( unsigned char *buf ) { fseek( adx_in, 0, SEEK_SET ); /* Read the ADX Header into memory */ fread( buf, 1, ADX_HDR_SIZE, adx_in ); if(buf[0]!=ADX_HDR_SIG ) return -1; /* Check ADX File Signature */ /* Parse the ADX File header */ ADX_Info.sample_offset = read_be16(buf+ADX_ADDR_START)-2; ADX_Info.chunk_size = buf[ADX_ADDR_CHUNK]; ADX_Info.channels = buf[ADX_ADDR_CHAN]; ADX_Info.rate = read_be32(buf+ADX_ADDR_RATE); ADX_Info.samples = read_be32(buf+ADX_ADDR_SAMP); ADX_Info.loop_type = buf[ADX_ADDR_TYPE]; /* Two known variations for possible loop informations: type 3 and type 4 */ if( ADX_Info.loop_type == 3 ) ADX_Info.loop = read_be32(buf+ADX_ADDR_LOOP); else if( ADX_Info.loop_type == 4 ) ADX_Info.loop = read_be32(buf+ADX_ADDR_LOOP+0x0c); if( ADX_Info.loop > 1 || ADX_Info.loop < 0 ) /* Invalid header check */ ADX_Info.loop = 0; if( ADX_Info.loop && ADX_Info.loop_type == 3 ) { ADX_Info.loop_samp_start = read_be32(buf+ADX_ADDR_SAMP_START); ADX_Info.loop_start = read_be32(buf+ADX_ADDR_BYTE_START); ADX_Info.loop_samp_end = read_be32(buf+ADX_ADDR_SAMP_END); ADX_Info.loop_end = read_be32(buf+ADX_ADDR_BYTE_END); } else if( ADX_Info.loop && ADX_Info.loop_type == 4 ) { ADX_Info.loop_samp_start = read_be32(buf+ADX_ADDR_SAMP_START+0x0c); ADX_Info.loop_start = read_be32(buf+ADX_ADDR_BYTE_START+0x0c); ADX_Info.loop_samp_end = read_be32(buf+ADX_ADDR_SAMP_END+0x0c); ADX_Info.loop_end = read_be32(buf+ADX_ADDR_BYTE_END+0x0c); } if( ADX_Info.loop ) ADX_Info.loop_samples = ADX_Info.loop_samp_end-ADX_Info.loop_samp_start; fseek( adx_in, ADX_Info.sample_offset, SEEK_SET ); /* CRI File Signature */ fread( buf, 1, 6, adx_in ); if ( memcmp(buf,"(c)CRI",6) ) { printf("Invalid ADX header!\n"); return -1; } return 1; } /* Convert ADX samples to PCM samples */ static void adx_to_pcm(short *out,unsigned char *in,PREV *prev) { int scale = ((in[0]<<8)|(in[1])); int i; int s0,s1,s2,d; in+=2; s1 = prev->s1; s2 = prev->s2; for(i=0;i<16;i++) { d = in[i]>>4; if (d&8) d-=16; s0 = (BASEVOL*d*scale + 0x7298*s1 - 0x3350*s2)>>14; if (s0>32767) s0=32767; else if (s0<-32768) s0=-32768; *out++=s0; s2 = s1; s1 = s0; d = in[i]&15; if (d&8) d-=16; s0 = (BASEVOL*d*scale + 0x7298*s1 - 0x3350*s2)>>14; if (s0>32767) s0=32767; else if (s0<-32768) s0=-32768; *out++=s0; s2 = s1; s1 = s0; } prev->s1 = s1; prev->s2 = s2; } /* Decode the ADX in a seperate thread */ static void *adx_thread(void *p) { //FILE *adx_in; //unsigned char buf[ADX_HDR_SIZE]; unsigned char *pcm_buf=NULL; short outbuf[32*2]; PREV prev[2]; //ADX_INFO ADX_Info; int pcm_size=0,wsize; printf("LibADX: %ikHz, %i channel\n", ADX_Info.rate, ADX_Info.channels); if( ADX_Info.loop && loop ) printf("LibADX: Loop Enabled\n"); pcm_buf = malloc(PCM_BUF_SIZE); /* allocate PCM buffer */ if( pcm_buf == NULL ) goto exit; snddrv_start( ADX_Info.rate, ADX_Info.channels );/*Start AICA audio driver*/ snddrv.dec_status = SNDDEC_STATUS_STREAMING; prev[0].s1 = 0; prev[0].s2 = 0; prev[1].s1 = 0; prev[1].s2 = 0; adx_dec: pcm_samples = ADX_Info.samples; if (ADX_Info.channels==1) /* MONO Decode Routine */ while(pcm_samples && snddrv.dec_status != SNDDEC_STATUS_DONE) { /* Check for request to pause stream */ if( snddrv.dec_status == SNDDEC_STATUS_PAUSING ) { snddrv.dec_status = SNDDEC_STATUS_PAUSED; while( snddrv.dec_status != SNDDEC_STATUS_STREAMING ) thd_pass(); } /* If looping is enabled, check for loop point */ if( loop && ADX_Info.loop ) if( ftell( adx_in ) >= ADX_Info.loop_end ) goto dec_finished; /* If there is room in PCM buffer, decode next chunk of ADX samples */ if( pcm_size < PCM_BUF_SIZE-16384 ) { /* Read the current chunk */ fread(adx_buf,1,ADX_Info.chunk_size,adx_in); /* Convert ADX chunk to PCM */ adx_to_pcm(outbuf,adx_buf,prev); if (pcm_samples>32) wsize=32; else wsize = pcm_samples; pcm_samples-=wsize; /* Copy the deocded samples to sample buffer */ memcpy(pcm_buf+pcm_size, outbuf, wsize*2*2); pcm_size+=wsize*2; } /* wait for AICA Driver to request some samples */ while( snddrv.buf_status != SNDDRV_STATUS_NEEDBUF ) thd_pass(); /* Send requested samples to the AICA driver */ if ( snddrv.buf_status == SNDDRV_STATUS_NEEDBUF && pcm_size > snddrv.pcm_needed ) { /* Copy the Requested PCM Samples to the AICA Driver */ memcpy( snddrv.pcm_buffer, pcm_buf, snddrv.pcm_needed ); pcm_size -= snddrv.pcm_needed; /* Shift the Remaining PCM Samples Back */ memmove(pcm_buf, pcm_buf+snddrv.pcm_needed, pcm_size); /* Let the AICA Driver know the PCM samples are ready */ snddrv.buf_status = SNDDRV_STATUS_HAVEBUF; } } else if (ADX_Info.channels==2) /* STEREO Decode Routine */ while(pcm_samples && snddrv.dec_status != SNDDEC_STATUS_DONE) { /* Check for request to pause stream */ if( snddrv.dec_status == SNDDEC_STATUS_PAUSING ) { snddrv.dec_status = SNDDEC_STATUS_PAUSED; while( snddrv.dec_status != SNDDEC_STATUS_STREAMING ) thd_pass(); } /* If looping is enabled, check for loop point */ if( loop && ADX_Info.loop ) if( ftell( adx_in ) >= ADX_Info.loop_end ) goto dec_finished; /* If there is room in the PCM buffer, decode some ADX samples */ if( pcm_size < PCM_BUF_SIZE - 16384*2 ) { short tmpbuf[32*2]; int i; fread(adx_buf,1,ADX_Info.chunk_size*2,adx_in); adx_to_pcm(tmpbuf,adx_buf,prev); adx_to_pcm(tmpbuf+32,adx_buf+ADX_Info.chunk_size,prev+1); for(i=0;i<32;i++) { outbuf[i*2] = tmpbuf[i]; outbuf[i*2+1] = tmpbuf[i+32]; } if (pcm_samples>32) wsize=32; else wsize = pcm_samples; pcm_samples-=wsize; memcpy(pcm_buf+pcm_size, outbuf, wsize*2*2); pcm_size+=wsize*2*2; } /* wait for AICA Driver to request some samples */ while( snddrv.buf_status != SNDDRV_STATUS_NEEDBUF ) thd_pass(); /* Send requested samples to the AICA driver */ if ( snddrv.buf_status == SNDDRV_STATUS_NEEDBUF && pcm_size > snddrv.pcm_needed ) { memcpy(snddrv.pcm_buffer, pcm_buf, snddrv.pcm_needed); pcm_size-=snddrv.pcm_needed; memmove(pcm_buf, pcm_buf+snddrv.pcm_needed, pcm_size); snddrv.buf_status = SNDDRV_STATUS_HAVEBUF; } } dec_finished: /* Indicated samples finished or loop point reached */ /* If loop is enabled seek to loop starting offset and continue streaming */ if( loop ) { if( ADX_Info.loop ) { fseek( adx_in, ADX_Info.loop_start, SEEK_SET ); ADX_Info.samples = ADX_Info.loop_samples; } else fseek( adx_in, ADX_Info.sample_offset+ADX_CRI_SIZE, SEEK_SET ); goto adx_dec; } /* At this point, we are finished decoding yet we still have some samples */ while( pcm_size >= 16384 ) { while( snddrv.buf_status != SNDDRV_STATUS_NEEDBUF ) thd_pass(); if ( snddrv.buf_status == SNDDRV_STATUS_NEEDBUF && pcm_size > snddrv.pcm_needed ) { memcpy(snddrv.pcm_buffer, pcm_buf, snddrv.pcm_needed); pcm_size-=snddrv.pcm_needed; memmove(pcm_buf, pcm_buf+snddrv.pcm_needed, pcm_size); snddrv.buf_status = SNDDRV_STATUS_HAVEBUF; } } printf("LibADX: decode finished\n" ); /* Finished streaming */ free( pcm_buf ); pcm_size = 0; snddrv_exit(); /* Exit the Sound Driver */ return NULL; exit: fclose(adx_in); return NULL; } /* This thread will handle the 'pausing' routine */ static void *pause_thd(void *p) { while( snddrv.dec_status != SNDDEC_STATUS_RESUMING ) { if ( snddrv.buf_status == SNDDRV_STATUS_NEEDBUF ) { memset( snddrv.pcm_buffer, 0, snddrv.pcm_needed ); snddrv.buf_status = SNDDRV_STATUS_HAVEBUF; } thd_sleep(20); } snddrv.dec_status = SNDDEC_STATUS_STREAMING; return NULL; } <file_sep>/firmware/isoldr/loader/fs/net/include/commands.h /* slinkie/commands.h Copyright (C)2004 <NAME> */ #ifndef __SLINKIE_COMMANDS_H #define __SLINKIE_COMMANDS_H #include <sys/cdefs.h> __BEGIN_DECLS #include <net/net.h> // Command packet types #define CMD_EXEC "EXEC" #define CMD_LBIN "LBIN" #define CMD_PBIN "PBIN" #define CMD_DBIN "DBIN" #define CMD_SBIN "SBIN" #define CMD_SREG "SREG" #define CMD_VERS "VERS" #define CMD_RETV "RETV" #define CMD_RBOT "RBOT" #define CMD_PAUS "PAUS" #define CMD_RSUM "RSUM" #define CMD_TERM "TERM" #define CMD_CDTO "CDTO" // Command handlers typedef void (*cmd_handler_t)(ip_hdr_t * ip, udp_pkt_t * udp); #define CMD_HANDLER(TYPE) \ void cmd_##TYPE(ip_hdr_t * ip, udp_pkt_t * udp) #define CMD_HANDLER_NAME(TYPE) cmd_##TYPE CMD_HANDLER(EXEC); CMD_HANDLER(LBIN); CMD_HANDLER(PBIN); CMD_HANDLER(DBIN); CMD_HANDLER(SBIN); CMD_HANDLER(SREG); CMD_HANDLER(VERS); CMD_HANDLER(RETV); CMD_HANDLER(RBOT); CMD_HANDLER(PAUS); CMD_HANDLER(RSUM); CMD_HANDLER(TERM); CMD_HANDLER(CDTO); __END_DECLS #endif /* __SLINKIE_COMMANDS_H */ <file_sep>/modules/tolua/Makefile # # tolua module for DreamShell # Copyright (C) 2009-2022 SWAT # http://www.dc-swat.ru # TARGET_NAME = tolua TOLUA_LIB = ./tolua/src/lib OBJS = module.o \ $(TOLUA_LIB)/tolua_event.o \ $(TOLUA_LIB)/tolua_is.o \ $(TOLUA_LIB)/tolua_map.o \ $(TOLUA_LIB)/tolua_push.o \ $(TOLUA_LIB)/tolua_to.o DBG_LIBS = -lds EXPORTS_FILE = exports.txt VER_MAJOR = 5 VER_MINOR = 1 VER_MICRO = 4 VER_BUILD = 0 all: rm-elf install include ../../sdk/Makefile.loadable KOS_CFLAGS += -I./tolua/include -I$(DS_SDK)/include/lua rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/firmware/aica/codec/serial.c /******************************************************************************/ /* */ /* SERIAL.C: Low Level Serial Routines */ /* */ /******************************************************************************/ /* 10/2005 by <NAME> <<EMAIL>> based on an example-code from Keil GmbH - modified for the WinARM example - changed interface to avoid potential conflicts with "stdio.h" */ // included in board.h: #include <AT91SAM7S64.H> /* AT91SAMT7S64 definitions */ #include "Board.h" #define BR 115200 /* Baud Rate */ #define BRD (MCK/16/BR) /* Baud Rate Divisor */ AT91S_USART * pUSART = AT91C_BASE_US0; /* Global Pointer to USART0 */ void uart0_init (void) { /* Initialize Serial Interface */ /* mt: n.b: uart0 clock must be enabled to use it */ *AT91C_PIOA_PDR = AT91C_PA5_RXD0 | /* Enable RxD0 Pin */ AT91C_PA6_TXD0; /* Enalbe TxD0 Pin */ pUSART->US_CR = AT91C_US_RSTRX | /* Reset Receiver */ AT91C_US_RSTTX | /* Reset Transmitter */ AT91C_US_RXDIS | /* Receiver Disable */ AT91C_US_TXDIS; /* Transmitter Disable */ pUSART->US_MR = AT91C_US_USMODE_NORMAL | /* Normal Mode */ AT91C_US_CLKS_CLOCK | /* Clock = MCK */ AT91C_US_CHRL_8_BITS | /* 8-bit Data */ AT91C_US_PAR_NONE | /* No Parity */ AT91C_US_NBSTOP_1_BIT; /* 1 Stop Bit */ pUSART->US_BRGR = BRD; /* Baud Rate Divisor */ pUSART->US_CR = AT91C_US_RXEN | /* Receiver Enable */ AT91C_US_TXEN; /* Transmitter Enable */ } int uart0_putc(int ch) { while (!(pUSART->US_CSR & AT91C_US_TXRDY)); /* Wait for Empty Tx Buffer */ return (pUSART->US_THR = ch); /* Transmit Character */ } int uart0_putchar (int ch) { /* Write Character to Serial Port */ if (ch == '\n') { /* Check for LF */ uart0_putc( '\r' ); /* Output CR */ } return uart0_putc( ch ); /* Transmit Character */ } int uart0_puts ( char* s ) { int i = 0; while ( *s ) { uart0_putc( *s++ ); i++; } return i; } int uart0_prints ( char* s ) { int i = 0; while ( *s ) { uart0_putchar( *s++ ); i++; } return i; } int uart0_kbhit( void ) /* returns true if character in receive buffer */ { if ( pUSART->US_CSR & AT91C_US_RXRDY) { return 1; } else { return 0; } } int uart0_getc ( void ) /* Read Character from Serial Port */ { while (!(pUSART->US_CSR & AT91C_US_RXRDY)); /* Wait for Full Rx Buffer */ return (pUSART->US_RHR); /* Read Character */ } <file_sep>/lib/SDL_Console/include/SDL_console.h /* SDL_console: An easy to use drop-down console based on the SDL library Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WHITOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library Generla Public License along with this library; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA <NAME> <EMAIL> */ #ifndef _CONSOLE_H_ #define _CONSOLE_H_ #include "SDL_events.h" #include "SDL_video.h" #include "begin_code.h" /*! Number of visible characters in a line. Lines in the history, the commandline, or CON_Out strings cannot be longer than this. Remark that this number does NOT include the '/0' character at the end of a string. So if we create a string we do this char* mystring[CON_CHARS_PER_LINE + 1]; */ #define CON_CHARS_PER_LINE 127 /*! Cursor blink frequency in ms */ #define CON_BLINK_RATE 500 /*! Border in pixels from the left margin to the first letter */ #define CON_CHAR_BORDER 4 /*! Default prompt used at the commandline */ #define CON_DEFAULT_PROMPT "]" /*! Scroll this many lines at a time (when pressing PGUP or PGDOWN) */ #define CON_LINE_SCROLL 2 /*! Indicator showing that you scrolled up the history */ #define CON_SCROLL_INDICATOR "^" /*! Cursor shown if we are in insert mode */ #define CON_INS_CURSOR "_" /*! Cursor shown if we are in overwrite mode */ #define CON_OVR_CURSOR "|" /*! Defines the default hide key (that Hide()'s the console if pressed) */ #define CON_DEFAULT_HIDEKEY SDLK_ESCAPE /*! Defines the opening/closing speed when the console switches from CON_CLOSED to CON_OPEN */ #define CON_OPENCLOSE_SPEED 25 /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif enum { CON_CLOSED, /*! The console is closed (and not shown) */ CON_CLOSING, /*! The console is still open and visible but closing. After it has completely disappeared it changes to CON_CLOSED */ CON_OPENING, /*! The console is visible and opening but not yet fully open. Changes to CON_OPEN when done */ CON_OPEN /*! The console is open and visible */ }; /*! This is a struct for each consoles data */ typedef struct console_information_td { int Visible; /*! enum that tells which visible state we are in CON_CLOSED, CON_OPEN, CON_CLOSING, CON_OPENING */ int WasUnicode; /*! stores the UNICODE value before the console was shown. On Hide() the UNICODE value is restored. */ int RaiseOffset; /*! Offset used in show/hide animation */ int HideKey; /*! the key that can hide the console */ char **ConsoleLines; /*! List of all the past lines */ char **CommandLines; /*! List of all the past commands */ int TotalConsoleLines; /*! Total number of lines in the console */ int ConsoleScrollBack; /*! How much the user scrolled back in the console */ int TotalCommands; /*! Number of commands that were typed in before (which are now in the CommandLines array) */ int FontNumber; /*! This is the number of the font for the console (DT_* specific; will hopefully disappear in future releases) */ int LineBuffer; /*! The number of visible lines in the console (autocalculated on CON_UpdateConsole()) */ int VChars; /*! The number of visible characters in one console line (autocalculated on CON_Init() and recalc. on CON_Resize()) */ int BackX, BackY; /*! Background image x and y coords */ char* Prompt; /*! Prompt displayed in command line */ char Command[CON_CHARS_PER_LINE+1]; /*! current command in command line = lcommand + rcommand (Get's updated in AssembleCommand())*/ char RCommand[CON_CHARS_PER_LINE+1]; /*! left hand side of cursor */ char LCommand[CON_CHARS_PER_LINE+1]; /*! right hand side of cursor */ char VCommand[CON_CHARS_PER_LINE+1]; /*! current visible command line */ int CursorPos; /*! Current cursor position relative to the currently typed in command */ int Offset; /*! First visible character relative to the currently typed in command (used if command is too long to fit into console) */ int InsMode; /*! Boolean that tells us whether we are in Insert- or Overwrite-Mode */ SDL_Surface *ConsoleSurface; /*! THE Surface of the console */ SDL_Surface *OutputScreen; /*! This is the screen to draw the console to (normally you VideoSurface)*/ SDL_Surface *BackgroundImage; /*! Background image for the console */ SDL_Surface *InputBackground; /*! Dirty rectangle that holds the part of the background image that is behind the commandline */ int DispX, DispY; /*! The top left x and y coords of the console on the display screen */ unsigned char ConsoleAlpha; /*! The consoles alpha level */ int CommandScrollBack; /*! How much the users scrolled back in the command lines */ void(*CmdFunction)(struct console_information_td *console, char* command); /*! The Function that is executed if you press 'Return' in the console */ char*(*TabFunction)(char* command); /*! The Function that is executed if you press 'Tab' in the console */ int FontHeight; /*! The height of the font used in the console */ int FontWidth; /*! The width of the font used in the console (Remark that the console needs FIXED width fonts!!) */ } ConsoleInformation; /*! Takes keys from the keyboard and inputs them to the console if the console isVisible(). If the event was not handled (i.e. WM events or unknown ctrl- or alt-sequences) the function returns the event for further processing. ***The prototype of this function will change in the next major release to int CON_Events(ConsoleInformation* console, SDL_Event *event) ***/ extern DECLSPEC SDL_Event* SDLCALL CON_Events(SDL_Event *event); /*! Makes the console visible */ extern DECLSPEC void SDLCALL CON_Show(ConsoleInformation *console); /*! Hides the console */ extern DECLSPEC void SDLCALL CON_Hide(ConsoleInformation *console); /*! Returns 1 if the console is opening or open, 0 else */ extern DECLSPEC int SDLCALL CON_isVisible(ConsoleInformation *console); /*! Internal: Updates visible state. This function is responsible for the opening/closing animation. Only used in CON_DrawConsole() */ extern DECLSPEC void SDLCALL CON_UpdateOffset(ConsoleInformation* console); /*! Draws the console to the screen if it is visible (NOT if it isVisible()). It get's drawn if it is REALLY visible ;-) */ extern DECLSPEC void SDLCALL CON_DrawConsole(ConsoleInformation *console); /*! Initializes a new console. @param FontName A filename of an image containing the font. Look at the example code for the image contents @param DisplayScreen The VideoSurface we are blitting to. ***This was not a very intelligent move. I will change this in the next major release. CON_DrawConsole will then no more blit the console to this surface but give you a pointer to ConsoleSurface when all updates are done*** @param lines The total number of lines in the history @param rect Position and size of the new console */ extern DECLSPEC ConsoleInformation* SDLCALL CON_Init(const char *FontName, SDL_Surface *DisplayScreen, int lines, SDL_Rect rect); /*! Frees DT_DrawText and calls CON_Free */ extern DECLSPEC void SDLCALL CON_Destroy(ConsoleInformation *console); /*! Frees all the memory loaded by the console */ extern DECLSPEC void SDLCALL CON_Free(ConsoleInformation *console); /*! Function to send text to the console. Works exactly like printf and supports the same format */ extern DECLSPEC void SDLCALL CON_Out(ConsoleInformation *console, const char *str, ...); /*! Sets the alpha level of the console to the specified value (0 - transparent, 255 - opaque). Use this function also for OpenGL. */ extern DECLSPEC void SDLCALL CON_Alpha(ConsoleInformation *console, unsigned char alpha); /*! Internal: Sets the alpha channel of an SDL_Surface to the specified value. Preconditions: the surface in question is RGBA. 0 <= a <= 255, where 0 is transparent and 255 opaque */ extern DECLSPEC void SDLCALL CON_AlphaGL(SDL_Surface *s, int alpha); /*! Sets a background image for the console */ extern DECLSPEC int SDLCALL CON_Background(ConsoleInformation *console, const char *image, int x, int y); /*! Changes current position of the console to the new given coordinates */ extern DECLSPEC void SDLCALL CON_Position(ConsoleInformation *console, int x, int y); /*! Changes the size of the console */ extern DECLSPEC int SDLCALL CON_Resize(ConsoleInformation *console, SDL_Rect rect); /*! Beams a console to another screen surface. Needed if you want to make a Video restart in your program. This function first changes the OutputScreen Pointer then calls CON_Resize to adjust the new size. ***Will disappear in the next major release. Instead i will introduce a new function called CON_ReInit or something that adjusts the internal parameters etc *** */ extern DECLSPEC int SDLCALL CON_Transfer(ConsoleInformation* console, SDL_Surface* new_outputscreen, SDL_Rect rect); /*! Give focus to a console. Make it the "topmost" console. This console will receive events sent with CON_Events() ***Will disappear in the next major release. There is no need for such a focus model *** */ extern DECLSPEC void SDLCALL CON_Topmost(ConsoleInformation *console); /*! Modify the prompt of the console. If you want a backslash you will have to escape it. */ extern DECLSPEC void SDLCALL CON_SetPrompt(ConsoleInformation *console, char* newprompt); /*! Set the key, that invokes a CON_Hide() after press. default is ESCAPE and you can always hide using ESCAPE and the HideKey (2 keys for hiding). compared against event->key.keysym.sym !! */ extern DECLSPEC void SDLCALL CON_SetHideKey(ConsoleInformation *console, int key); /*! Internal: executes the command typed in at the console (called if you press 'Return')*/ extern DECLSPEC void SDLCALL CON_Execute(ConsoleInformation *console, char* command); /*! Sets the callback function that is called if a command was typed in. The function you would like to use as the callback will have to look like this: <br> <b> void my_command_handler(ConsoleInformation* console, char* command)</b> <br><br> You will then call the function like this:<br><b> CON_SetExecuteFunction(console, my_command_handler)</b><br><br> If this is not clear look at the example program */ extern DECLSPEC void SDLCALL CON_SetExecuteFunction(ConsoleInformation *console, void(*CmdFunction)(ConsoleInformation *console2, char* command)); /*! Sets the callback function that is called if you press the 'Tab' key. The function has to look like this:<br><b> char* my_tabcompletion(char* command)</b><br><br> The commandline on the left side of the cursor gets passed over to your function. You will then have to make your own tab-complete and return the completed string as return value. If you have nothing to complete you can return NULL or the string you got. ***Will change in the next major release to char* mytabfunction(ConsoleInformation* console, char* command) *** */ extern DECLSPEC void SDLCALL CON_SetTabCompletion(ConsoleInformation *console, char*(*TabFunction)(char* command)); /*! Internal: Gets called when TAB was pressed and executes the function you have earlier registered with CON_SetTabCompletion() */ extern DECLSPEC void SDLCALL CON_TabCompletion(ConsoleInformation *console); /*! Internal: makes a newline (same as printf("\n") or CON_Out(console, "\n") ) */ extern DECLSPEC void SDLCALL CON_NewLineConsole(ConsoleInformation *console); /*! Internal: shift command history (the one you can switch with the up/down keys) */ extern DECLSPEC void SDLCALL CON_NewLineCommand(ConsoleInformation *console); /*! Internal: updates console after resize, background image change, CON_Out() etc. This function draws the upper part of the console (that holds the history) */ extern DECLSPEC void SDLCALL CON_UpdateConsole(ConsoleInformation *console); /*! Internal: Default Execute callback */ extern DECLSPEC void SDLCALL Default_CmdFunction(ConsoleInformation *console, char* command); /*! Internal: Default TabCompletion callback */ extern DECLSPEC char* SDLCALL Default_TabFunction(char* command); /*! Internal: draws the commandline the user is typing in to the screen. Called from within CON_DrawConsole() *** Will change in the next major release to void DrawCommandLine(ConsoleInformation* console) *** */ extern DECLSPEC void SDLCALL DrawCommandLine(); /*! Internal: Gets called if you press the LEFT key (move cursor left) */ extern DECLSPEC void SDLCALL Cursor_Left(ConsoleInformation *console); /*! Internal: Gets called if you press the RIGHT key (move cursor right) */ extern DECLSPEC void SDLCALL Cursor_Right(ConsoleInformation *console); /*! Internal: Gets called if you press the HOME key (move cursor to the beginning of the line */ extern DECLSPEC void SDLCALL Cursor_Home(ConsoleInformation *console); /*! Internal: Gets called if you press the END key (move cursor to the end of the line*/ extern DECLSPEC void SDLCALL Cursor_End(ConsoleInformation *console); /*! Internal: Called if you press DELETE (deletes character under the cursor) */ extern DECLSPEC void SDLCALL Cursor_Del(ConsoleInformation *console); /*! Internal: Called if you press BACKSPACE (deletes character left of cursor) */ extern DECLSPEC void SDLCALL Cursor_BSpace(ConsoleInformation *console); /*! Internal: Called if you type in a character (add the char to the command) */ extern DECLSPEC void SDLCALL Cursor_Add(ConsoleInformation *console, SDL_Event *event); /*! Internal: Called if you press Ctrl-C (deletes the commandline) */ extern DECLSPEC void SDLCALL Clear_Command(ConsoleInformation *console); /*! Internal: Called if the command line has changed (assemles console->Command from LCommand and RCommand */ extern DECLSPEC void SDLCALL Assemble_Command(ConsoleInformation *console); /*! Internal: Called if you press Ctrl-L (deletes the History) */ extern DECLSPEC void SDLCALL Clear_History(ConsoleInformation *console); /*! Internal: Called if you press UP key (switches through recent typed in commands */ extern DECLSPEC void SDLCALL Command_Up(ConsoleInformation *console); /*! Internal: Called if you press DOWN key (switches through recent typed in commands */ extern DECLSPEC void SDLCALL Command_Down(ConsoleInformation *console); /* Ends C function definitions when using C++ */ #ifdef __cplusplus }; #endif #include "close_code.h" #endif /* _CONSOLE_H_ */ /* end of SDL_console.h ... */ <file_sep>/firmware/isoldr/loader/kos/src/vmu.c /* This file is part of the libdream Dreamcast function library. Please see libdream.c for further details. vmu.c (C)2000 <NAME> */ #include <string.h> #include <dc/maple.h> #include <dc/vmu.h> /* This module deals with the VMU. It provides functionality for memorycard access, and for access to the lcd screen. Thanks to <NAME> for VMU/Maple information. Ported from KallistiOS (Dreamcast OS) for libdream by <NAME> */ /* draw a 1-bit bitmap on the LCD screen (48x32). return a -1 if an error occurs */ int vmu_draw_lcd(uint8 addr, void *bitmap) { uint32 param[2 + 48]; maple_frame_t frame; param[0] = MAPLE_FUNC_LCD; /* this is (block << 24) | (phase << 8) | (partition (0 for all vmu)) */ param[1] = 0; memcpy(&param[2], bitmap, 48 * 4); do { if (maple_docmd_block(MAPLE_COMMAND_BWRITE, addr, 2 + 48, param, &frame) == -1) return -1; } while (frame.cmd == MAPLE_RESPONSE_AGAIN); if (frame.cmd != MAPLE_RESPONSE_OK) return -1; return 0; } /* read the data in block blocknum into buffer, return a -1 if an error occurs, for now we ignore MAPLE_RESPONSE_FILEERR, which will be changed shortly */ int vmu_block_read(uint8 addr, uint16 blocknum, uint8 *buffer) { uint32 param[2]; maple_frame_t frame; param[0] = MAPLE_FUNC_MEMCARD; /* this is (block << 24) | (phase << 8) | (partition (0 for all vmu)) */ param[1] = ((blocknum & 0xff) << 24) | ((blocknum >> 8) << 16); do { if (maple_docmd_block(MAPLE_COMMAND_BREAD, addr, 2, param, &frame) == -1) return -1; } while (frame.cmd == MAPLE_RESPONSE_AGAIN); if (frame.cmd == MAPLE_RESPONSE_DATATRF && *((uint32 *) frame.data) == MAPLE_FUNC_MEMCARD && *(((uint32 *) frame.data) + 1) == param[1]) { memcpy(buffer, ((uint32 *) frame.data) + 2, (frame.datalen-2) * 4); } else { printf("vmu_block_read failed: %d/%d\r\n", frame.cmd, *((uint32 *)frame.data)); return -1; } return 0; } /* writes buffer into block blocknum. ret a -1 on error. We don't do anything about the maple bus returning file errors, etc, right now, but that will change soon. */ int vmu_block_write(uint8 addr, uint16 blocknum, uint8 *buffer) { uint32 param[2 + (128 / 4)]; maple_frame_t frame; int to, phase; /* Writes have to occur in four phases per block -- this is the way of flash memory, which you must erase an entire block at once to write; the blocks in this case are 128 bytes long. */ for (phase=0; phase<4; phase++) { /* Memory card function */ param[0] = MAPLE_FUNC_MEMCARD; /* this is (block << 24) | (phase << 8) | (partition (0 for all vmu)) */ param[1] = ((blocknum & 0xff) << 24) | ((blocknum >> 8) << 16) | (phase << 8); /* data to write to the block */ memcpy(param + 2, buffer + 128*phase, 128); to = 1000; do { if (maple_docmd_block(MAPLE_COMMAND_BWRITE, addr, 2 + (128 / 4), param, &frame) == -1) return -1; to--; if (to < 0) { printf("Timed out executing BWRITE\r\n"); return -2; } } while (frame.cmd == MAPLE_RESPONSE_AGAIN); if (frame.cmd != MAPLE_RESPONSE_OK) { printf("vmu_block_write failed: %d/%d\r\n", frame.cmd, *((uint32 *)frame.data)); return -1; } /* Gotta wait a bit to let the flash catch up */ sleep(20); } return 0; } <file_sep>/applications/main/scripts/FTPd.lua ----------------------------------------- -- -- -- @name: FTP server script -- -- @author: SWAT -- -- @url: http://www.dc-swat.ru -- -- -- ----------------------------------------- -- ShowConsole(); Sleep(500); print("To get back GUI press: Start, A, Start\n"); if OpenModule(os.getenv("PATH") .. "/modules/ftpd.klf") then if os.execute("ftpd -s -p 21 -d /") == 0 then print("Network IPv4: " .. os.getenv("NET_IPV4") .. "\n"); end end <file_sep>/firmware/isoldr/loader/kos/net/arp.c /* KallistiOS ##version## net/arp.c Copyright (C)2004 <NAME> */ #include <stdio.h> #include <string.h> #include <kos/net.h> #include <net/net.h> int net_arp_input(netif_t *src, uint8 *pkt, int pktsize) { eth_hdr_t *eth; arp_pkt_t *arp; uint8 tmp[10]; uint32 ip; // Do we know our IP? if (net_ip == 0) return 0; (void)pktsize; // Get pointers eth = (eth_hdr_t*)(pkt + 0); arp = (arp_pkt_t *)(pkt + sizeof(eth_hdr_t)); // Make sure the hardware addr space = ethernet if (arp->hw_space != 0x0100) { printf("net_arp: bad hw space\n"); return 0; } // Make sure the protocol addr space = IP if (arp->proto_space != 0x0008) { printf("net_arp: bad proto space\n"); return 0; } // Is it a request? if (arp->opcode != 0x0100) { printf("net_arp: ARP not request\n"); return 0; } // Is it for our IP? ip = htonl(net_ip); if (memcmp(arp->proto_dest, &ip, 4)) { printf("net_arp: request for someone else\n"); return 0; } // Swap the MAC addresses memcpy(eth->dest, eth->src, 6); memcpy(eth->src, nif->mac_addr, 6); // ARP reply arp->opcode = 0x0200; // Swap the IP addresses memcpy(tmp, arp->hw_src, 10); memcpy(arp->hw_src, arp->hw_dest, 10); memcpy(arp->hw_dest, tmp, 10); // Put our MAC in the src address field memcpy(arp->hw_src, nif->mac_addr, 6); // Send it src->if_tx(src, net_rxbuf, sizeof(eth_hdr_t) + sizeof(arp_pkt_t)); return 0; } <file_sep>/src/utils/debug_console.c /* KallistiOS ##version## util/dsd_console.c Copyright (C) 2011-2014 SWAT */ #include "ds.h" #include <string.h> #include <errno.h> #include <kos/dbgio.h> static file_t flog = 0; static int dsd_detected() { return 1; } static int dsd_init() { return 0; } static int dsd_shutdown() { return 0; } static int dsd_sd_init() { if(flog == 0) { flog = fs_open("/sd/ds.log", O_WRONLY); } return 0; } static int dsd_sd_shutdown() { if(log > 0) { fs_close(flog); } return 0; } static int dsd_set_irq_usage(int mode) { return 0; } static int dsd_read() { errno = EAGAIN; return -1; } static int dsd_write(int c) { //ds_printf("%c", c); return 1; } static int dsd_flush() { return 0; } static int dsd_write_buffer(const uint8 *data, int len, int xlat) { ConsoleInformation *DSConsole = GetConsole(); char *ptemp, *b; if(DSConsole != NULL && DSConsole->ConsoleLines) { ptemp = (char*)data; while((b = strsep(&ptemp, "\n")) != NULL) { while(strlen(b) > DSConsole->VChars) { CON_NewLineConsole(DSConsole); strncpy(DSConsole->ConsoleLines[0], ptemp, DSConsole->VChars); DSConsole->ConsoleLines[0][DSConsole->VChars] = '\0'; b = &b[DSConsole->VChars]; } CON_NewLineConsole(DSConsole); strncpy(DSConsole->ConsoleLines[0], b, DSConsole->VChars); DSConsole->ConsoleLines[0][DSConsole->VChars] = '\0'; } CON_UpdateConsole(DSConsole); } return len; } static int dsd_sd_write_buffer(const uint8 *data, int len, int xlat) { if(flog == 0) { dsd_sd_init(); } if(flog < 0) { return dsd_write_buffer(data, len, xlat); } return fs_write(flog, data, len); } static int dsd_read_buffer(uint8 * data, int len) { errno = EAGAIN; return -1; } dbgio_handler_t dbgio_ds = { "ds", dsd_detected, dsd_init, dsd_shutdown, dsd_set_irq_usage, dsd_read, dsd_write, dsd_flush, dsd_write_buffer, dsd_read_buffer }; dbgio_handler_t dbgio_sd = { "sd", dsd_detected, dsd_sd_init, dsd_sd_shutdown, dsd_set_irq_usage, dsd_read, dsd_write, dsd_flush, dsd_sd_write_buffer, dsd_read_buffer }; void dbgio_set_dev_ds() { // Replace null device dbgio_handlers[dbgio_handler_cnt - 2] = &dbgio_ds; dbgio_dev_select("ds"); } void dbgio_set_dev_sd() { // Replace null device dbgio_handlers[dbgio_handler_cnt - 2] = &dbgio_sd; dbgio_dev_select("sd"); } void dbgio_set_dev_scif() { dbgio_dev_select("scif"); } void dbgio_set_dev_fb() { dbgio_dev_select("fb"); } <file_sep>/modules/zip/minizip/README.md Minizip zlib contribution that includes: - AES encryption - I/O buffering - PKWARE disk spanning - Visual Studio project files It also has the latest bug fixes that having been found all over the internet including the minizip forum and zlib developer's mailing list. *AES Encryption* + Requires all files in the aes folder + Requires #define HAVE_AES When using the zip library with password protection it will use AES 256-bit encryption. When using the unzip library it will automatically use AES when applicable. *I/O Buffering* ``` ourbuffer_t buffered = {0}; zlib_filefunc64_def fileFunc64 = {0}; fill_win32_filefunc64W(&buffered->filefunc64); fill_buffer_filefunc64(&fileFunc64, buffered); unzOpen2_64(wFilename, &fileFunc64) ``` *PKWARE disk spanning* To create an archive with multiple disks use zipOpen3_64 supplying a disk_size value in bytes. ``` extern zipFile ZEXPORT zipOpen3_64 OF((const void *pathname, int append, ZPOS64_T disk_size, zipcharpc* globalcomment, zlib_filefunc64_def* pzlib_filefunc_def)); ``` The central directory is the only data stored in the .zip and doesn't follow disk_size restrictions. When using the unzip library it will automatically determine when in needs to span disks.<file_sep>/sdk/bin/src/scramble/Makefile CC = gcc LD = gcc INSTALL = install DESTDIR = ../.. all : scramble ciso : scramble.o $(LD) -o scramble scramble.o ciso.o : scramble.c $(CC) -o scramble.o -c scramble.c install : scramble $(INSTALL) -m 755 scramble $(DESTDIR)/scramble clean: rm -rf *.o rm -rf scramble <file_sep>/include/status.h /** * \file status.h * \brief DreamShell status handling system * \date 2011-2014 * \author SWAT www.dc-swat.ru */ /** * @file * * @brief Header file for statuses. */ #ifndef DS_STATUS_H #define DS_STATUS_H #ifndef _DS_CONSOLE_H #include <kos/dbgio.h> int ds_printf(const char *fmt, ...); #endif /** * @defgroup DS_status Status Checks * * @{ */ /** * @brief Status codes */ typedef enum { DS_SUCCESSFUL = 0, DS_TASK_EXITTED = 1, DS_MP_NOT_CONFIGURED = 2, DS_INVALID_NAME = 3, DS_INVALID_ID = 4, DS_TOO_MANY = 5, DS_TIMEOUT = 6, DS_OBJECT_WAS_DELETED = 7, DS_INVALID_SIZE = 8, DS_INVALID_ADDRESS = 9, DS_INVALID_NUMBER = 10, DS_NOT_DEFINED = 11, DS_RESOURCE_IN_USE = 12, DS_UNSATISFIED = 13, DS_INCORRECT_STATE = 14, DS_ALREADY_SUSPENDED = 15, DS_ILLEGAL_ON_SELF = 16, DS_ILLEGAL_ON_REMOTE_OBJECT = 17, DS_CALLED_FROM_ISR = 18, DS_INVALID_PRIORITY = 19, DS_INVALID_CLOCK = 20, DS_INVALID_NODE = 21, DS_NOT_CONFIGURED = 22, DS_NOT_OWNER_OF_RESOURCE = 23, DS_NOT_IMPLEMENTED = 24, DS_INTERNAL_ERROR = 25, DS_NO_MEMORY = 26, DS_IO_ERROR = 27, DS_PROXY_BLOCKING = 28 } DStatus_t; /** * @name Print Macros * * @{ */ /** * @brief General purpose debug print macro. */ #ifdef DEBUG #ifndef DS_DEBUG_PRINT #ifdef DS_STATUS_USE_DS_PRINTF #define DS_DEBUG_PRINT( fmt, ...) \ ds_printf( "%s: " fmt, __func__, ##__VA_ARGS__) #else /* DS_STATUS_USE_DS_PRINTF */ #include <stdio.h> #define DS_DEBUG_PRINT( fmt, ...) \ dbglog(DBG_DEBUG, "%s: " fmt, __func__, ##__VA_ARGS__) #endif /* DS_STATUS_USE_DS_PRINTF */ #endif /* DS_DEBUG_PRINT */ #else /* DEBUG */ #ifdef DS_DEBUG_PRINT #warning DS_DEBUG_PRINT was defined, but DEBUG was undefined #undef DS_DEBUG_PRINT #endif /* DS_DEBUG_PRINT */ #define DS_DEBUG_PRINT( fmt, ...) #endif /* DEBUG */ /** * @brief Macro to print debug messages for successful operations. */ #define DS_DEBUG_OK( msg) \ DS_DEBUG_PRINT( "DS_OK: %s\n", msg) /** * @brief General purpose system log print macro. */ #ifndef DS_SYSLOG_PRINT #ifdef DS_STATUS_USE_DS_PRINTF #define DS_SYSLOG_PRINT( fmt, ...) \ ds_printf( fmt, ##__VA_ARGS__) #else /* DS_STATUS_USE_DS_PRINTF */ #include <stdio.h> #define DS_SYSLOG_PRINT( fmt, ...) \ dbglog(DBG_DEBUG, fmt, ##__VA_ARGS__) #endif /* DS_STATUS_USE_DS_PRINTF */ #endif /* DS_SYSLOG_PRINT */ /** * @brief General purpose system log macro. */ #define DS_SYSLOG( fmt, ...) \ DS_SYSLOG_PRINT( "%s: " fmt, __func__, ##__VA_ARGS__) /** * @brief General purpose system log macro for warnings. */ #define DS_SYSLOG_WARNING( fmt, ...) \ DS_SYSLOG( "DS_WARNING: " fmt, ##__VA_ARGS__) /** * @brief Macro to generate a system log warning message if the status code @a * sc is not equal to @ref DS_SUCCESSFUL. */ #define DS_SYSLOG_WARNING_SC( sc, msg) \ if ((DStatus_t) (sc) != DS_SUCCESSFUL) { \ DS_SYSLOG_WARNING( "SC = %i: %s\n", (int) sc, msg); \ } /** * @brief General purpose system log macro for errors. */ #define DS_SYSLOG_ERROR( fmt, ...) \ DS_SYSLOG( "DS_ERROR: " fmt, ##__VA_ARGS__) /** * @brief Macro for system log error messages with status code. */ #define DS_SYSLOG_ERROR_WITH_SC( sc, msg) \ DS_SYSLOG_ERROR( "SC = %i: %s\n", (int) sc, msg); /** * @brief Macro for system log error messages with return value. */ #define DS_SYSLOG_ERROR_WITH_RV( rv, msg) \ DS_SYSLOG_ERROR( "RV = %i: %s\n", (int) rv, msg); /** * @brief Macro to generate a system log error message if the status code @a * sc is not equal to @ref DS_SUCCESSFUL. */ #define DS_SYSLOG_ERROR_SC( sc, msg) \ if ((DStatus_t) (sc) != DS_SUCCESSFUL) { \ DS_SYSLOG_ERROR_WITH_SC( sc, msg); \ } /** * @brief Macro to generate a system log error message if the return value @a * rv is less than zero. */ #define DS_SYSLOG_ERROR_RV( rv, msg) \ if ((int) (rv) < 0) { \ DS_SYSLOG_ERROR_WITH_RV( rv, msg); \ } /** @} */ /** * @name Check Macros * * @{ */ /** * @brief Prints message @a msg and returns with status code @a sc if the status * code @a sc is not equal to @ref DS_SUCCESSFUL. */ #define DS_CHECK_SC( sc, msg) \ if ((DStatus_t) (sc) != DS_SUCCESSFUL) { \ DS_SYSLOG_ERROR_WITH_SC( sc, msg); \ return (DStatus_t) sc; \ } else { \ DS_DEBUG_OK( msg); \ } /** * @brief Prints message @a msg and returns with a return value of negative @a sc * if the status code @a sc is not equal to @ref DS_SUCCESSFUL. */ #define DS_CHECK_SC_RV( sc, msg) \ if ((DStatus_t) (sc) != DS_SUCCESSFUL) { \ DS_SYSLOG_ERROR_WITH_SC( sc, msg); \ return -((int) (sc)); \ } else { \ DS_DEBUG_OK( msg); \ } /** * @brief Prints message @a msg and returns if the status code @a sc is not equal * to @ref DS_SUCCESSFUL. */ #define DS_CHECK_SC_VOID( sc, msg) \ if ((DStatus_t) (sc) != DS_SUCCESSFUL) { \ DS_SYSLOG_ERROR_WITH_SC( sc, msg); \ return; \ } else { \ DS_DEBUG_OK( msg); \ } /** * @brief Prints message @a msg and returns with a return value @a rv if the * return value @a rv is less than zero. */ #define DS_CHECK_RV( rv, msg) \ if ((int) (rv) < 0) { \ DS_SYSLOG_ERROR_WITH_RV( rv, msg); \ return (int) rv; \ } else { \ DS_DEBUG_OK( msg); \ } /** * @brief Prints message @a msg and returns with status code @ref DS_IO_ERROR * if the return value @a rv is less than zero. */ #define DS_CHECK_RV_SC( rv, msg) \ if ((int) (rv) < 0) { \ DS_SYSLOG_ERROR_WITH_RV( rv, msg); \ return DS_IO_ERROR; \ } else { \ DS_DEBUG_OK( msg); \ } /** * @brief Prints message @a msg and returns if the return value @a rv is less * than zero. */ #define DS_CHECK_RV_VOID( rv, msg) \ if ((int) (rv) < 0) { \ DS_SYSLOG_ERROR_WITH_RV( rv, msg); \ return; \ } else { \ DS_DEBUG_OK( msg); \ } /** @} */ /** * @name Cleanup Macros * * @{ */ /** * @brief Prints message @a msg and jumps to @a label if the status code @a sc * is not equal to @ref DS_SUCCESSFUL. */ #define DS_CLEANUP_SC( sc, label, msg) \ if ((DStatus_t) (sc) != DS_SUCCESSFUL) { \ DS_SYSLOG_ERROR_WITH_SC( sc, msg); \ goto label; \ } else { \ DS_DEBUG_OK( msg); \ } /** * @brief Prints message @a msg and jumps to @a label if the status code @a sc * is not equal to @ref DS_SUCCESSFUL. The return value variable @a rv will * be set to a negative @a sc in this case. */ #define DS_CLEANUP_SC_RV( sc, rv, label, msg) \ if ((DStatus_t) (sc) != DS_SUCCESSFUL) { \ DS_SYSLOG_ERROR_WITH_SC( sc, msg); \ rv = -((int) (sc)); \ goto label; \ } else { \ DS_DEBUG_OK( msg); \ } /** * @brief Prints message @a msg and jumps to @a label if the return value @a rv * is less than zero. */ #define DS_CLEANUP_RV( rv, label, msg) \ if ((int) (rv) < 0) { \ DS_SYSLOG_ERROR_WITH_RV( rv, msg); \ goto label; \ } else { \ DS_DEBUG_OK( msg); \ } /** * @brief Prints message @a msg and jumps to @a label if the return value @a rv * is less than zero. The status code variable @a sc will be set to @ref * DS_IO_ERROR in this case. */ #define DS_CLEANUP_RV_SC( rv, sc, label, msg) \ if ((int) (rv) < 0) { \ DS_SYSLOG_ERROR_WITH_RV( rv, msg); \ sc = DS_IO_ERROR; \ goto label; \ } else { \ DS_DEBUG_OK( msg); \ } /** * @brief Prints message @a msg and jumps to @a label. */ #define DS_DO_CLEANUP( label, msg) \ do { \ DS_SYSLOG_ERROR( msg); \ goto label; \ } while (0) /** * @brief Prints message @a msg, sets the status code variable @a sc to @a val * and jumps to @a label. */ #define DS_DO_CLEANUP_SC( val, sc, label, msg) \ do { \ sc = (DStatus_t) val; \ DS_SYSLOG_ERROR_WITH_SC( sc, msg); \ goto label; \ } while (0) /** * @brief Prints message @a msg, sets the return value variable @a rv to @a val * and jumps to @a label. */ #define DS_DO_CLEANUP_RV( val, rv, label, msg) \ do { \ rv = (int) val; \ DS_SYSLOG_ERROR_WITH_RV( rv, msg); \ goto label; \ } while (0) /** @} */ /** @} */ #endif /* DS_STATUS_H */ <file_sep>/modules/opkg/libini/ini.h #ifndef __INI_H #define __INI_H #include <stdlib.h> struct INI; struct INI *ini_open(const char *file); struct INI *ini_open_mem(const char *buf, size_t len); void ini_close(struct INI *ini); /* Jump to the next section. * if 'name' is set, the pointer passed as argument * points to the name of the section. 'name_len' is set to the length * of the char array. * XXX: the pointer will be invalid as soon as ini_close() is called. * * Returns: * -EIO if an error occured while reading the file, * 0 if no more section can be found, * 1 otherwise. */ int ini_next_section(struct INI *ini, const char **name, size_t *name_len); /* Read a key/value pair. * 'key' and 'value' must be valid pointers. The pointers passed as arguments * will point to the key and value read. 'key_len' and 'value_len' are * set to the length of their respective char arrays. * XXX: the pointers will be invalid as soon as ini_close() is called. * * Returns: * -EIO if an error occured while reading the file, * 0 if no more key/value pairs can be found, * 1 otherwise. */ int ini_read_pair(struct INI *ini, const char **key, size_t *key_len, const char **value, size_t *value_len); #endif <file_sep>/src/drivers/sd.c /** * Copyright (c) 2014, 2023 by SWAT <<EMAIL>> * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <arch/types.h> #include <arch/timer.h> #include <arch/cache.h> #include <drivers/spi.h> #include <drivers/sd.h> #include <dc/sd.h> #include <errno.h> #include <stdlib.h> #include <string.h> /* For CRC16-CCITT */ #include <kos/net.h> #include <kos/blockdev.h> #include <kos/dbglog.h> //#define SD_DEBUG 1 #define MAX_RETRIES 500000 #define READ_RETRIES 50000 #define WRITE_RETRIES 150000 #define MAX_RETRY 10 /* MMC/SD command (in SPI) */ #define CMD(n) (n | 0x40) #define CMD0 (0x40+0) /* GO_IDLE_STATE */ #define CMD1 (0x40+1) /* SEND_OP_COND */ #define CMD8 (0x40+8) /* SEND_IF_COND */ #define CMD9 (0x40+9) /* SEND_CSD */ #define CMD10 (0x40+10) /* SEND_CID */ #define CMD12 (0x40+12) /* STOP_TRANSMISSION */ #define CMD16 (0x40+16) /* SET_BLOCKLEN */ #define CMD17 (0x40+17) /* READ_SINGLE_BLOCK */ #define CMD18 (0x40+18) /* READ_MULTIPLE_BLOCK */ #define CMD23 (0x40+23) /* SET_BLOCK_COUNT */ #define CMD24 (0x40+24) /* WRITE_BLOCK */ #define CMD25 (0x40+25) /* WRITE_MULTIPLE_BLOCK */ #define CMD41 (0x40+41) /* SEND_OP_COND (ACMD) */ #define CMD55 (0x40+55) /* APP_CMD */ #define CMD58 (0x40+58) /* READ_OCR */ #define CMD59 (0x40+59) /* CRC_ON_OFF */ static inline uint16_t sdc_get_uint16( const uint8_t *s) { return (uint16_t) ((s [0] << 8) | s [1]); } static inline uint32_t sdc_get_uint32( const uint8_t *s) { return ((uint32_t) s [0] << 24) | ((uint32_t) s [1] << 16) | ((uint32_t) s [2] << 8) | (uint32_t) s [3]; } /** * @name Card Identification * @{ */ #define SD_MMC_CID_SIZE 16 #define SD_MMC_CID_GET_MID( cid) ((cid) [0]) #define SD_MMC_CID_GET_OID( cid) sdc_get_uint16( cid + 1) #define SD_MMC_CID_GET_PNM( cid, i) ((char) (cid) [3 + (i)]) #define SD_MMC_CID_GET_PRV( cid) ((cid) [9]) #define SD_MMC_CID_GET_PSN( cid) sdc_get_uint32( cid + 10) #define SD_MMC_CID_GET_MDT( cid) ((cid) [14]) #define SD_MMC_CID_GET_CRC7( cid) ((cid) [15] >> 1) /** @} */ /* The type of the dev_data in the block device structure */ typedef struct sd_devdata { uint64_t block_count; uint64_t start_block; } sd_devdata_t; //static const int card_spi_delay = SPI_SDC_MMC_DELAY; //static int old_spi_delay = SPI_SDC_MMC_DELAY; static int byte_mode = 0; static int is_mmc = 0; static int initted = 0; #define SELECT() spi_cs_on(SPI_CS_SDC) #define DESELECT() spi_cs_off(SPI_CS_SDC) /* #define SELECT() do { \ spi_cs_on(SPI_CS_SDC); \ old_spi_delay = spi_get_delay(); \ if(old_spi_delay != card_spi_delay) \ spi_set_delay(card_spi_delay); \ } while(0) #define DESELECT() do { \ if(old_spi_delay != card_spi_delay) \ spi_set_delay(old_spi_delay); \ spi_cs_off(SPI_CS_SDC); \ } while(0) */ static uint8 wait_ready (void) { int i; uint8 res; (void)spi_sr_byte(0xFF); i = 0; do { res = spi_sr_byte(0xFF); i++; } while ((res != 0xFF) && i < MAX_RETRIES); return res; } static uint8 send_cmd ( uint8 cmd, /* Command byte */ uint32 arg /* Argument */ ) { uint8 n, res; uint8 cb[6]; if (wait_ready() != 0xFF) { #ifdef SD_DEBUG dbglog(DBG_DEBUG, "%s: CMD 0x%02x wait ready error\n", __func__, cmd); #endif return 0xFF; } cb[0] = cmd; cb[1] = (uint8)(arg >> 24); cb[2] = (uint8)(arg >> 16); cb[3] = (uint8)(arg >> 8); cb[4] = (uint8)arg; cb[5] = sd_crc7(cb, 5, 0); /* Send command packet */ spi_send_byte(cmd); /* Command */ spi_send_byte(cb[1]); /* Argument[31..24] */ spi_send_byte(cb[2]); /* Argument[23..16] */ spi_send_byte(cb[3]); /* Argument[15..8] */ spi_send_byte(cb[4]); /* Argument[7..0] */ spi_send_byte(cb[5]); /* CRC7 */ /* Receive command response */ if (cmd == CMD12) (void)spi_rec_byte(); /* Skip a stuff byte when stop reading */ n = 20; /* Wait for a valid response in timeout of 10 attempts */ do { res = spi_rec_byte(); } while ((res & 0x80) && --n); #ifdef SD_DEBUG dbglog(DBG_DEBUG, "%s: CMD 0x%02x response 0x%02x\n", __func__, cmd, res); #endif return res; /* Return with the response value */ } static uint8 send_slow_cmd ( uint8 cmd, /* Command byte */ uint32 arg /* Argument */ ) { uint8 n, res; uint8 cb[6]; int i; (void)spi_slow_sr_byte(0xff); i = 0; do { res = spi_slow_sr_byte(0xff); i++; } while ((res != 0xFF) && i < 100000); if (res != 0xff) { #ifdef SD_DEBUG dbglog(DBG_DEBUG, "%s: CMD 0x%02x error\n", __func__, cmd); #endif return(0xff); } cb[0] = cmd; cb[1] = (uint8)(arg >> 24); cb[2] = (uint8)(arg >> 16); cb[3] = (uint8)(arg >> 8); cb[4] = (uint8)arg; cb[5] = sd_crc7(cb, 5, 0); /* Send command packet */ spi_slow_sr_byte(cmd); /* Command */ spi_slow_sr_byte(cb[1]); /* Argument[31..24] */ spi_slow_sr_byte(cb[2]); /* Argument[23..16] */ spi_slow_sr_byte(cb[3]); /* Argument[15..8] */ spi_slow_sr_byte(cb[4]); /* Argument[7..0] */ spi_slow_sr_byte(cb[5]); // CRC7 /* Receive command response */ if (cmd == CMD12) (void)spi_slow_sr_byte(0xff);/* Skip a stuff byte when stop reading */ n = 20; /* Wait for a valid response in timeout of 10 attempts */ do { res = spi_slow_sr_byte(0xff); } while ((res & 0x80) && --n); #ifdef SD_DEBUG dbglog(DBG_DEBUG, "%s: CMD 0x%02x response 0x%02x\n", __func__, cmd, res); #endif return res; /* Return with the response value */ } int sdc_init(void) { int i; uint8 n, ty = 0, ocr[4]; if(initted) { return 0; } if(spi_init(0)) { return -1; } timer_spin_sleep(20); SELECT(); /* 80 dummy clocks */ for (n = 10; n; n--) (void)spi_slow_sr_byte(0xff); if (send_slow_cmd(CMD0, 0) == 1) { /* Enter Idle state */ #ifdef SD_DEBUG dbglog(DBG_DEBUG, "%s: Enter Idle state\n", __func__); #endif timer_spin_sleep(20); i = 0; if (send_slow_cmd(CMD8, 0x1AA) == 1) { /* SDC Ver2+ */ for (n = 0; n < 4; n++) ocr[n] = spi_slow_sr_byte(0xff); if (ocr[2] == 0x01 && ocr[3] == 0xAA) { /* The card can work at vdd range of 2.7-3.6V */ do { /* ACMD41 with HCS bit */ if (send_slow_cmd(CMD55, 0) <= 1 && send_slow_cmd(CMD41, 1UL << 30) == 0) break; ++i; } while (i < 300000); if (i < 300000 && send_slow_cmd(CMD58, 0) == 0) { /* Check CCS bit */ for (n = 0; n < 4; n++) ocr[n] = spi_slow_sr_byte(0xff); ty = (ocr[0] & 0x40) ? 6 : 2; } } } else { /* SDC Ver1 or MMC */ ty = (send_slow_cmd(CMD55, 0) <= 1 && send_slow_cmd(CMD41, 0) <= 1) ? 2 : 1; /* SDC : MMC */ do { if (ty == 2) { if (send_slow_cmd(CMD55, 0) <= 1 && send_slow_cmd(CMD41, 0) == 0) /* ACMD41 */ break; } else { if (send_slow_cmd(CMD1, 0) == 0) { /* CMD1 */ is_mmc = 1; break; } } ++i; } while (i < 300000); if (!(i < 300000) || send_slow_cmd(CMD16, 512) != 0) /* Select R/W block length */ ty = 0; } } send_slow_cmd(CMD59, 1); // crc check #ifdef SD_DEBUG dbglog(DBG_DEBUG, "%s: card type = 0x%02x\n", __func__, ty & 0xff); #endif if(!(ty & 4)) { byte_mode = 1; } DESELECT(); (void)spi_slow_sr_byte(0xff); /* Idle (Release DO) */ if (ty) { /* Initialization succeded */ initted = 1; return 0; } /* Initialization failed */ sdc_shutdown(); return -1; } int sdc_shutdown(void) { if(!initted) return -1; SELECT(); wait_ready(); DESELECT(); (void)spi_rec_byte(); spi_shutdown(); initted = 0; return 0; } static int read_data ( uint8 *buff, /* Data buffer to store received data */ size_t len /* Byte count (must be even number) */ ) { uint8 token; int i; uint16 crc, crc2; i = 0; do { /* Wait for data packet in timeout of 100ms */ token = spi_rec_byte(); ++i; } while ((token == 0xFF) && i < READ_RETRIES); if(token != 0xFE) { #ifdef SD_DEBUG dbglog(DBG_DEBUG, "%s: not valid data token: %02x\n", __func__, token); #endif return -1; /* If not valid data token, return with error */ } spi_rec_data(buff, len); crc = (uint16)spi_rec_byte() << 8; crc |= (uint16)spi_rec_byte(); crc2 = net_crc16ccitt(buff, len, 0); if(crc != crc2) { errno = EIO; return -1; } return 0; /* Return with success */ } int sdc_read_blocks(uint32 block, size_t count, uint8 *buf) { if(!initted) { errno = ENXIO; return -1; } #ifdef SD_DEBUG dbglog(DBG_DEBUG, "%s: block=%ld count=%d\n", __func__, block, count); #endif uint8 *p; int retry, cnt; if (byte_mode) block <<= 9; /* Convert to byte address if needed */ for (retry = 0; retry < MAX_RETRY; retry++) { p = buf; cnt = count; SELECT(); if (cnt == 1) { /* Single block read */ if ((send_cmd(CMD17, block) == 0) && !read_data(p, 512)) { cnt = 0; } } else { /* Multiple block read */ if (send_cmd(CMD18, block) == 0) { do { if (read_data(p, 512)) break; p += 512; } while (--cnt); send_cmd(CMD12, 0); /* STOP_TRANSMISSION */ } } DESELECT(); (void)spi_rec_byte(); /* Idle (Release DO) */ if (cnt == 0) break; } if((retry >= MAX_RETRY || cnt > 0)) { errno = EIO; return -1; } return 0; } static int write_data ( uint8 *buff, /* 512 byte data block to be transmitted */ uint8 token /* Data/Stop token */ ) { uint8 resp; uint16 crc; if (wait_ready() != 0xFF) return -1; spi_send_byte(token); /* Xmit data token */ if (token != 0xFD) { /* Is data token */ dcache_pref_range((uint32)buff, 512); crc = net_crc16ccitt(buff, 512, 0); spi_send_data(buff, 512); spi_send_byte((uint8)(crc >> 8)); spi_send_byte((uint8)crc); resp = spi_rec_byte(); /* Reсeive data response */ if ((resp & 0x1F) != 0x05) { /* If not accepted, return with error */ #ifdef SD_DEBUG dbglog(DBG_DEBUG, "%s: not accepted: %02x\n", __func__, resp); #endif errno = EIO; return -1; } } return 0; } int sdc_write_blocks(uint32 block, size_t count, const uint8 *buf) { if(!initted) { errno = ENXIO; return -1; } #ifdef SD_DEBUG dbglog(DBG_DEBUG, "%s: block=%ld count=%d\n", __func__, block, count); #endif uint8 cnt, *p; int retry; if (byte_mode) block <<= 9; /* Convert to byte address if needed */ for (retry = 0; retry < MAX_RETRY; retry++) { p = (uint8 *)buf; cnt = count; SELECT(); /* CS = L */ if (count == 1) { /* Single block write */ if ((send_cmd(CMD24, block) == 0) && !write_data(p, 0xFE)) cnt = 0; } else { /* Multiple block write */ if (!is_mmc) { send_cmd(CMD55, 0); send_cmd(CMD23, cnt); /* ACMD23 */ } if (send_cmd(CMD25, block) == 0) { do { if (write_data(p, 0xFC)) break; p += 512; } while (--cnt); if (write_data(0, 0xFD)) /* STOP_TRAN token */ cnt = 1; } } DESELECT(); /* CS = H */ (void)spi_rec_byte(); /* Idle (Release DO) */ if (cnt == 0) break; } if((retry >= MAX_RETRY || cnt > 0)) { errno = EIO; return -1; } return 0; } uint64 sdc_get_size(void) { uint8 csd[16]; int exponent; uint64 rv = 0; if(!initted) { errno = ENXIO; return (uint64)-1; } SELECT(); if(send_cmd(CMD9, 0)) { rv = (uint64)-1; errno = EIO; goto out; } /* Read back the register */ if(read_data(csd, 16)) { rv = (uint64)-1; errno = EIO; goto out; } /* Figure out what version of the CSD register we're looking at */ switch(csd[0] >> 6) { case 0: /* CSD version 1.0 (SD) C_SIZE is bits 62-73 of the CSD, C_SIZE_MULT is bits 47-49, READ_BL_LEN is bits 80-83. Card size is calculated as follows: (C_SIZE + 1) * 2^(C_SIZE_MULT + 2) * 2^(READ_BL_LEN) */ exponent = (csd[5] & 0x0F) + ((csd[9] & 0x03) << 1) + (csd[10] >> 7) + 2; rv = ((csd[8] >> 6) | (csd[7] << 2) | ((csd[6] & 0x03) << 10)) + 1; rv <<= exponent; break; case 1: /* CSD version 2.0 (SDHC/SDXC) C_SIZE is bits 48-69 of the CSD, card size is calculated as (C_SIZE + 1) * 512KiB */ rv = ((((uint64)csd[9]) | (uint64)(csd[8] << 8) | ((uint64)(csd[7] & 0x3F) << 16)) + 1) << 19; break; default: /* Unknown version, punt. */ rv = (uint64)-1; errno = ENODEV; goto out; } out: DESELECT(); (void)spi_rec_byte(); return rv; } int sdc_print_ident(void) { uint8 cid[SD_MMC_CID_SIZE]; int rv = 0; if(!initted) { errno = ENXIO; return -1; } SELECT(); if(send_cmd(CMD10, 0)) { rv = -1; errno = EIO; goto out; } memset(cid, 0, SD_MMC_CID_SIZE); /* Read back the register */ if(read_data(cid, SD_MMC_CID_SIZE)) { rv = -1; errno = EIO; goto out; } // dbglog(DBG_DEBUG, "*** Card Identification ***\n"); dbglog(DBG_DEBUG, "Manufacturer ID : %" PRIu8 "\n", SD_MMC_CID_GET_MID(cid)); dbglog(DBG_DEBUG, "OEM/Application ID : %" PRIu16 "\n", SD_MMC_CID_GET_OID(cid)); dbglog(DBG_DEBUG, "Product name : %c%c%c%c%c%c\n", SD_MMC_CID_GET_PNM(cid, 0), SD_MMC_CID_GET_PNM(cid, 1), SD_MMC_CID_GET_PNM(cid, 2), SD_MMC_CID_GET_PNM(cid, 3), SD_MMC_CID_GET_PNM(cid, 4), SD_MMC_CID_GET_PNM(cid, 5) ); dbglog(DBG_DEBUG, "Product revision : %" PRIu8 "\n", SD_MMC_CID_GET_PRV(cid)); dbglog(DBG_DEBUG, "Product serial number : %" PRIu32 "\n", SD_MMC_CID_GET_PSN(cid)); dbglog(DBG_DEBUG, "Manufacturing date : %" PRIu8 "\n", SD_MMC_CID_GET_MDT(cid)); dbglog(DBG_DEBUG, "7-bit CRC checksum : %" PRIu8 "\n", SD_MMC_CID_GET_CRC7(cid)); out: DESELECT(); (void)spi_rec_byte(); return rv; } static int sdb_init(kos_blockdev_t *d) { (void)d; if(!initted) { errno = ENODEV; return -1; } return 0; } static int sdb_shutdown(kos_blockdev_t *d) { free(d->dev_data); return 0; } static int sdb_read_blocks(kos_blockdev_t *d, uint64_t block, size_t count, void *buf) { sd_devdata_t *data = (sd_devdata_t *)d->dev_data; return sdc_read_blocks(block + data->start_block, count, (uint8 *)buf); } static int sdb_write_blocks(kos_blockdev_t *d, uint64_t block, size_t count, const void *buf) { sd_devdata_t *data = (sd_devdata_t *)d->dev_data; return sdc_write_blocks(block + data->start_block, count, (const uint8 *)buf); } static uint64_t sdb_count_blocks(kos_blockdev_t *d) { sd_devdata_t *data = (sd_devdata_t *)d->dev_data; return data->block_count; } static int sdb_flush(kos_blockdev_t *d) { (void)d; SELECT(); wait_ready(); DESELECT(); (void)spi_rec_byte(); return 0; } static kos_blockdev_t sd_blockdev = { NULL, /* dev_data */ 9, /* l_block_size (block size of 512 bytes) */ &sdb_init, /* init */ &sdb_shutdown, /* shutdown */ &sdb_read_blocks, /* read_blocks */ &sdb_write_blocks, /* write_blocks */ &sdb_count_blocks, /* count_blocks */ &sdb_flush /* flush */ }; int sdc_blockdev_for_partition(int partition, kos_blockdev_t *rv, uint8 *partition_type) { uint8 buf[512]; int pval; sd_devdata_t *ddata; if(!initted) { errno = ENXIO; return -1; } if(!rv || !partition_type) { errno = EFAULT; return -1; } /* Make sure the partition asked for is sane */ if(partition < 0 || partition > 3) { dbglog(DBG_DEBUG, "Invalid partition number given: %d\n", partition); errno = EINVAL; return -1; } /* Read the MBR from the card */ if(sdc_read_blocks(0, 1, buf)) { return -1; } /* Make sure the SD card uses MBR partitions. TODO: Support GPT partitioning at some point. */ if(buf[0x01FE] != 0x55 || buf[0x1FF] != 0xAA) { dbglog(DBG_DEBUG, "SD card doesn't appear to have a MBR\n"); errno = ENOENT; return -1; } /* Figure out where the partition record we're concerned with is, and make sure that the partition actually exists. */ pval = 16 * partition + 0x01BE; if(buf[pval + 4] == 0) { dbglog(DBG_DEBUG, "Partition %d appears to be empty\n", partition); errno = ENOENT; return -1; } /* Allocate the device data */ if(!(ddata = (sd_devdata_t *)malloc(sizeof(sd_devdata_t)))) { errno = ENOMEM; return -1; } /* Copy in the template block device and fill it in */ memcpy(rv, &sd_blockdev, sizeof(kos_blockdev_t)); ddata->block_count = buf[pval + 0x0C] | (buf[pval + 0x0D] << 8) | (buf[pval + 0x0E] << 16) | (buf[pval + 0x0F] << 24); ddata->start_block = buf[pval + 0x08] | (buf[pval + 0x09] << 8) | (buf[pval + 0x0A] << 16) | (buf[pval + 0x0B] << 24); rv->dev_data = ddata; *partition_type = buf[pval + 4]; return 0; } int sdc_blockdev_for_device(kos_blockdev_t *rv) { sd_devdata_t *ddata; if(!initted) { errno = ENXIO; return -1; } if(!rv) { errno = EFAULT; return -1; } /* Allocate the device data */ if(!(ddata = (sd_devdata_t *)malloc(sizeof(sd_devdata_t)))) { errno = ENOMEM; return -1; } ddata->start_block = 0; ddata->block_count = (sdc_get_size() / 512); rv->dev_data = ddata; return 0; } <file_sep>/modules/mongoose/Makefile # # mongoose module for DreamShell # Copyright (C) 2013 SWAT # TARGET_NAME = mongoose OBJS = module.o mongoose.o DBG_LIBS = -lds EXPORTS_FILE = exports.txt VER_MAJOR = 3 VER_MINOR = 1 VER_MICRO = 0 KOS_CFLAGS += -DNDEBUG -DNO_CGI -DNO_SSL -DNO_POPEN all: rm-elf include ../../sdk/Makefile.loadable rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) opkg -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/modules/mp3/libmp3/xingmp3/l3init.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** tinit.c *************************************************** Layer III init tables ******************************************************************/ #include <float.h> #include <math.h> #include "L3.h" #include "mhead.h" #include "protos.h" /* get rid of precision loss warnings on conversion */ #ifdef _MSC_VER #pragma warning(disable:4244 4056) #endif static const float Ci[8] = { -0.6f, -0.535f, -0.33f, -0.185f, -0.095f, -0.041f, -0.0142f, -0.0037f}; void hwin_init(MPEG *m); /* hybrid windows -- */ void imdct_init(MPEG *m); typedef struct { float *w; float *w2; void *coef; } IMDCT_INIT_BLOCK; void msis_init(MPEG *m); void msis_init_MPEG2(MPEG *m); /*=============================================================*/ int L3table_init(MPEG *m) { int i; float *x; LS *ls; int scalefact_scale, preemp, scalefac; double tmp; PAIR *csa; /*================ quant ===============================*/ /* 8 bit plus 2 lookup x = pow(2.0, 0.25*(global_gain-210)) */ /* extra 2 for ms scaling by 1/sqrt(2) */ /* extra 4 for cvt to mono scaling by 1/2 */ x = quant_init_global_addr(m); for (i = 0; i < 256 + 2 + 4; i++) x[i] = (float) pow(2.0, 0.25 * ((i - (2 + 4)) - 210 + GLOBAL_GAIN_SCALE)); /* x = pow(2.0, -0.5*(1+scalefact_scale)*scalefac + preemp) */ ls = quant_init_scale_addr(m); for (scalefact_scale = 0; scalefact_scale < 2; scalefact_scale++) { for (preemp = 0; preemp < 4; preemp++) { for (scalefac = 0; scalefac < 32; scalefac++) { ls[scalefact_scale][preemp][scalefac] = (float) pow(2.0, -0.5 * (1 + scalefact_scale) * (scalefac + preemp)); } } } /*--- iSample**(4/3) lookup, -32<=i<=31 ---*/ x = quant_init_pow_addr(m); for (i = 0; i < 64; i++) { tmp = i - 32; x[i] = (float) (tmp * pow(fabs(tmp), (1.0 / 3.0))); } /*-- pow(2.0, -0.25*8.0*subblock_gain) 3 bits --*/ x = quant_init_subblock_addr(m); for (i = 0; i < 8; i++) { x[i] = (float) pow(2.0, 0.25 * -8.0 * i); } /*-------------------------*/ // quant_init_sf_band(sr_index); replaced by code in sup.c /*================ antialias ===============================*/ csa = alias_init_addr(m); for (i = 0; i < 8; i++) { csa[i][0] = (float) (1.0 / sqrt(1.0 + Ci[i] * Ci[i])); csa[i][1] = (float) (Ci[i] / sqrt(1.0 + Ci[i] * Ci[i])); } /*================ msis ===============================*/ msis_init(m); msis_init_MPEG2(m); /*================ imdct ===============================*/ imdct_init(m); /*--- hybrid windows ------------*/ hwin_init(m); return 0; } /*====================================================================*/ typedef float ARRAY36[36]; ARRAY36 *hwin_init_addr(); /*--------------------------------------------------------------------*/ void hwin_init(MPEG *m) { int i, j; double pi; ARRAY36 *win; win = hwin_init_addr(m); pi = 4.0 * atan(1.0); /* type 0 */ for (i = 0; i < 36; i++) win[0][i] = (float) sin(pi / 36 * (i + 0.5)); /* type 1 */ for (i = 0; i < 18; i++) win[1][i] = (float) sin(pi / 36 * (i + 0.5)); for (i = 18; i < 24; i++) win[1][i] = 1.0F; for (i = 24; i < 30; i++) win[1][i] = (float) sin(pi / 12 * (i + 0.5 - 18)); for (i = 30; i < 36; i++) win[1][i] = 0.0F; /* type 3 */ for (i = 0; i < 6; i++) win[3][i] = 0.0F; for (i = 6; i < 12; i++) win[3][i] = (float) sin(pi / 12 * (i + 0.5 - 6)); for (i = 12; i < 18; i++) win[3][i] = 1.0F; for (i = 18; i < 36; i++) win[3][i] = (float) sin(pi / 36 * (i + 0.5)); /* type 2 */ for (i = 0; i < 12; i++) win[2][i] = (float) sin(pi / 12 * (i + 0.5)); for (i = 12; i < 36; i++) win[2][i] = 0.0F; /*--- invert signs by region to match mdct 18pt --> 36pt mapping */ for (j = 0; j < 4; j++) { if (j == 2) continue; for (i = 9; i < 36; i++) win[j][i] = -win[j][i]; } /*-- invert signs for short blocks --*/ for (i = 3; i < 12; i++) win[2][i] = -win[2][i]; return; } /*=============================================================*/ typedef float ARRAY4[4]; IMDCT_INIT_BLOCK *imdct_init_addr_18(); IMDCT_INIT_BLOCK *imdct_init_addr_6(); /*-------------------------------------------------------------*/ void imdct_init(MPEG *m) { int k, p, n; double t, pi; IMDCT_INIT_BLOCK *addr; float *w, *w2; float *v, *v2, *coef87; ARRAY4 *coef; /*--- 18 point --*/ addr = imdct_init_addr_18(); w = addr->w; w2 = addr->w2; coef = addr->coef; /*----*/ n = 18; pi = 4.0 * atan(1.0); t = pi / (4 * n); for (p = 0; p < n; p++) w[p] = (float) (2.0 * cos(t * (2 * p + 1))); for (p = 0; p < 9; p++) w2[p] = (float) 2.0 *cos(2 * t * (2 * p + 1)); t = pi / (2 * n); for (k = 0; k < 9; k++) { for (p = 0; p < 4; p++) coef[k][p] = (float) cos(t * (2 * k) * (2 * p + 1)); } /*--- 6 point */ addr = imdct_init_addr_6(); v = addr->w; v2 = addr->w2; coef87 = addr->coef; /*----*/ n = 6; pi = 4.0 * atan(1.0); t = pi / (4 * n); for (p = 0; p < n; p++) v[p] = (float) 2.0 *cos(t * (2 * p + 1)); for (p = 0; p < 3; p++) v2[p] = (float) 2.0 *cos(2 * t * (2 * p + 1)); t = pi / (2 * n); k = 1; p = 0; *coef87 = (float) cos(t * (2 * k) * (2 * p + 1)); /* adjust scaling to save a few mults */ for (p = 0; p < 6; p++) v[p] = v[p] / 2.0f; *coef87 = (float) 2.0 *(*coef87); return; } /*===============================================================*/ typedef float ARRAY8_2[8][2]; ARRAY8_2 *msis_init_addr(MPEG *m); /*-------------------------------------------------------------*/ void msis_init(MPEG *m) { int i; double s, c; double pi; double t; ARRAY8_2 *lr; lr = msis_init_addr(m); pi = 4.0 * atan(1.0); t = pi / 12.0; for (i = 0; i < 7; i++) { s = sin(i * t); c = cos(i * t); /* ms_mode = 0 */ lr[0][i][0] = (float) (s / (s + c)); lr[0][i][1] = (float) (c / (s + c)); /* ms_mode = 1 */ lr[1][i][0] = (float) (sqrt(2.0) * (s / (s + c))); lr[1][i][1] = (float) (sqrt(2.0) * (c / (s + c))); } /* sf = 7 */ /* ms_mode = 0 */ lr[0][i][0] = 1.0f; lr[0][i][1] = 0.0f; /* ms_mode = 1, in is bands is routine does ms processing */ lr[1][i][0] = 1.0f; lr[1][i][1] = 1.0f; /*------- for(i=0;i<21;i++) nBand[0][i] = sfBandTable[sr_index].l[i+1] - sfBandTable[sr_index].l[i]; for(i=0;i<12;i++) nBand[1][i] = sfBandTable[sr_index].s[i+1] - sfBandTable[sr_index].s[i]; -------------*/ } /*-------------------------------------------------------------*/ /*===============================================================*/ typedef float ARRAY2_64_2[2][64][2]; ARRAY2_64_2 *msis_init_addr_MPEG2(MPEG *m); /*-------------------------------------------------------------*/ void msis_init_MPEG2(MPEG *m) { int k, n; double t; ARRAY2_64_2 *lr; int intensity_scale, ms_mode, sf, sflen; float ms_factor[2]; ms_factor[0] = 1.0; ms_factor[1] = (float) sqrt(2.0); lr = msis_init_addr_MPEG2(m); /* intensity stereo MPEG2 */ /* lr2[intensity_scale][ms_mode][sflen_offset+sf][left/right] */ for (intensity_scale = 0; intensity_scale < 2; intensity_scale++) { t = pow(2.0, -0.25 * (1 + intensity_scale)); for (ms_mode = 0; ms_mode < 2; ms_mode++) { n = 1; k = 0; for (sflen = 0; sflen < 6; sflen++) { for (sf = 0; sf < (n - 1); sf++, k++) { if (sf == 0) { lr[intensity_scale][ms_mode][k][0] = ms_factor[ms_mode] * 1.0f; lr[intensity_scale][ms_mode][k][1] = ms_factor[ms_mode] * 1.0f; } else if ((sf & 1)) { lr[intensity_scale][ms_mode][k][0] = (float) (ms_factor[ms_mode] * pow(t, (sf + 1) / 2)); lr[intensity_scale][ms_mode][k][1] = ms_factor[ms_mode] * 1.0f; } else { lr[intensity_scale][ms_mode][k][0] = ms_factor[ms_mode] * 1.0f; lr[intensity_scale][ms_mode][k][1] = (float) (ms_factor[ms_mode] * pow(t, sf / 2)); } } /* illegal is_pos used to do ms processing */ if (ms_mode == 0) { /* ms_mode = 0 */ lr[intensity_scale][ms_mode][k][0] = 1.0f; lr[intensity_scale][ms_mode][k][1] = 0.0f; } else { /* ms_mode = 1, in is bands is routine does ms processing */ lr[intensity_scale][ms_mode][k][0] = 1.0f; lr[intensity_scale][ms_mode][k][1] = 1.0f; } k++; n = n + n; } } } } /*-------------------------------------------------------------*/ <file_sep>/commands/mke2fs/mke2fs.c /* KallistiOS ##version## mke2fs.c Copyright (C) 2013 <NAME> This example shows how to format a SD card with a new ext2 filesystem using pretty much no functionality from libkosext2fs (other than the definitions in the headers). No functions in the library itself are called (hence the library isn't linked in). At some point I'll probably move some of this functionality into libkosext2fs so that there's less manual work to be done, but for the time being, this gets the job done. */ #include <time.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <inttypes.h> #include <unistd.h> #ifdef _arch_dreamcast #include <kos/dbgio.h> #include <kos/blockdev.h> #include <arch/arch.h> #include <dc/sd.h> #include <dc/maple.h> #include <dc/maple/controller.h> #endif #include "ds.h" #include "ext2fs.h" #include "block.h" #include "inode.h" #include "superblock.h" #include "utils.h" #define KiB 1024LLU #define MiB (KiB * 1024LLU) #define GiB (MiB * 1024LLU) /* We don't make any blocks more than 4KiB in size, so this works as a full-size block buffer quite nicely. */ static uint8_t block[4096] __attribute__((aligned(4))); static ext2_bg_desc_t *bg_descs; static int bg_count; static uint32_t *rsvd_inodes, *rsvd_blocks; /* <= 128MiB -> 1024 byte blocks <= 4GiB -> 2048 byte blocks > 4GiB -> 4096 byte blocks While libkosext2fs should handle larger block sizes than 4096 bytes, Linux on most platforms will not, so we don't go above it. Note that these ranges are somewhat arbitrary, but work out nicely. */ static inline uint32_t pick_ext2_bs(uint64_t total_size) { if(total_size > 4 * GiB) return 4096; else if(total_size > 128 * MiB) return 2048; else return 1024; } static inline int sb_tst(int group, int root) { for(;;) { if(group == 1) return 1; if(group % root) return 0; group /= root; } } static inline int has_superblock(int group) { if(group == 0 || sb_tst(group, 3) || sb_tst(group, 5) || sb_tst(group, 7)) return 1; return 0; } /* static void __attribute__((__noreturn__)) exit_with_error(const char *err) { #ifdef _arch_dreamcast maple_device_t *dev; cont_state_t *state; ds_printf("%s\n\nPress any button to exit.\n", err); for(;;) { dev = maple_enum_type(0, MAPLE_FUNC_CONTROLLER); if(dev) { state = (cont_state_t *)maple_dev_status(dev); if(state) { if(state->buttons) arch_exit(); } } } #else ds_printf("%s\n", err); exit(EXIT_FAILURE); #endif } */ static int exit_with_error(const char *err) { ds_printf(err); return CMD_ERROR; } static int write_fs_block(ext2_superblock_t *sb, kos_blockdev_t *bd, uint32_t block_num, const uint8_t *buf) { int fs_per_block = 10 + sb->s_log_block_size - bd->l_block_size; if(fs_per_block < 0) /* This should never happen, as the ext2 block size must be at least as large as the sector size of the block device itself. */ return -EINVAL; if(sb->s_blocks_count <= block_num) return -EINVAL; if(bd->write_blocks(bd, block_num << fs_per_block, 1 << fs_per_block, buf)) return -EIO; return 0; } static int read_fs_block(ext2_superblock_t *sb, kos_blockdev_t *bd, uint32_t block_num, uint8_t *buf) { int fs_per_block = 10 + sb->s_log_block_size - bd->l_block_size; if(fs_per_block < 0) /* This should never happen, as the ext2 block size must be at least as large as the sector size of the block device itself. */ return -EINVAL; if(sb->s_blocks_count <= block_num) return -EINVAL; if(bd->read_blocks(bd, block_num << fs_per_block, 1 << fs_per_block, buf)) return -EIO; return 0; } static int read_inode_block(ext2_superblock_t *sb, kos_blockdev_t *bd, uint32_t inode_num, uint8_t *buf, ext2_inode_t **rino, uint32_t *rblk) { uint32_t bg, index, blk; uint16_t ino_sz; uint32_t block_size = 1024 << sb->s_log_block_size; int rv; if(sb->s_rev_level >= EXT2_DYNAMIC_REV) ino_sz = sb->s_inode_size; else ino_sz = 128; bg = (inode_num - 1) / sb->s_inodes_per_group; index = (inode_num - 1) % sb->s_inodes_per_group; blk = index / (block_size / ino_sz); index %= (block_size / ino_sz); *rblk = blk + bg_descs[bg].bg_inode_table; if((rv = read_fs_block(sb, bd, *rblk, buf))) return rv; *rino = (ext2_inode_t *)(buf + index * ino_sz); return 0; } static int write_superblock(ext2_superblock_t *bsb, kos_blockdev_t *bd, uint32_t bg) { uint8_t *buf; ext2_superblock_t *sb; uint32_t blk, nblks; int fs_per_block = 10 + bsb->s_log_block_size - bd->l_block_size; int rv; /* Allocate enough space for one filesystem block. */ if(!(buf = (uint8_t *)malloc(1024 << bsb->s_log_block_size))) return -ENOMEM; sb = (ext2_superblock_t *)buf; memset(buf, 0, 1024 << bsb->s_log_block_size); /* If we're working with the first block group, we need to offset within the block, potentially. */ if(!bg) { if(bd->l_block_size > 10) { /* Read what's there already, in case we have a boot block or some other nonsense. */ if(bd->read_blocks(bd, 0, 1, buf)) return -EIO; /* Fix the pointer. */ sb = (ext2_superblock_t *)(buf + 1024); /* Clear out anything after the superblock */ if(bd->l_block_size > 11) memset(buf + 2048, 0, (1 << bd->l_block_size) - 2048); blk = 0; nblks = 1; } else { nblks = blk = 1024 >> bd->l_block_size; } } else { blk = (bg * bsb->s_blocks_per_group + bsb->s_first_data_block) << (fs_per_block); nblks = 1 << fs_per_block; } /* Copy in the superblock */ memcpy(sb, bsb, sizeof(ext2_superblock_t)); /* Fix things up, depending on the revision of the filesystem. */ if(bsb->s_rev_level >= EXT2_DYNAMIC_REV) /* Write the block group number. */ sb->s_block_group_nr = (uint16_t)bg; else /* Clear everything that's not in rev0 out. */ memset(&sb->s_first_ino, 0, 176); ds_printf("Writing superblock for group %" PRIu32 " @ %" PRIu32 "\n", bg, blk >> fs_per_block); /* Write the data. */ rv = bd->write_blocks(bd, blk, nblks, buf); /* Clean up, we're done. */ free(buf); return rv; } static int write_bg_descs(ext2_superblock_t *sb, kos_blockdev_t *bd, uint32_t bg) { uint32_t blk, nblks, bg_per_block, i; uint32_t block_size = (1024 << sb->s_log_block_size); uint8_t *buf; int rv = 0; /* The block group descriptors appear right after the superblock (backup) */ blk = bg * sb->s_blocks_per_group + sb->s_first_data_block + 1; /* Figure out how big each superblock (or backup thereof) is */ bg_per_block = block_size / sizeof(ext2_bg_desc_t); nblks = bg_count / bg_per_block; if(bg_count % bg_per_block) ++nblks; if(!(buf = (uint8_t *)malloc(block_size * nblks))) return -ENOMEM; memset(buf, 0, block_size * nblks); memcpy(buf, bg_descs, bg_count * sizeof(ext2_bg_desc_t)); ds_printf("Writing block group descriptors for group %" PRIu32 " @ %" PRIu32 " (%" PRIu32 " block(s))\n", bg, blk, nblks); /* Write them */ for(i = 0; i < nblks && !rv; ++i) { rv = write_fs_block(sb, bd, blk + i, buf + (block_size * i)); } free(buf); return rv; } static int write_superblocks(ext2_superblock_t *sb, kos_blockdev_t *bd) { int i; ds_printf("Writing superblocks\n"); if(sb->s_rev_level < EXT2_DYNAMIC_REV || !(sb->s_feature_ro_compat & EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)) { for(i = 0; i < bg_count; ++i) { if(write_superblock(sb, bd, i)) return exit_with_error("Error writing superblock\n"); if(write_bg_descs(sb, bd, i)) return exit_with_error("Error writing block group descriptors\n"); } } else { if(write_superblock(sb, bd, 0)) return exit_with_error("Error writing superblock\n"); if(write_bg_descs(sb, bd, 0)) return exit_with_error("Error writing block group descriptors\n"); for(i = 1; i < bg_count; ++i) { if(has_superblock(i)) { if(write_superblock(sb, bd, i)) return exit_with_error("Error writing superblock\n"); if(write_bg_descs(sb, bd, i)) return exit_with_error("Error writing block group descriptors\n"); } } } return -ENOSYS; } static int write_blank_inode_tables(ext2_superblock_t *sb, kos_blockdev_t *bd) { int i, rv; uint32_t j, blk; memset(block, 0, 1024 << sb->s_log_block_size); for(i = 0; i < bg_count; ++i) { blk = i * sb->s_blocks_per_group + rsvd_blocks[i] + sb->s_first_data_block; ds_printf("Writing inode tables for block group %d\n" "\t%" PRIu32 " blocks (%" PRIu16 " inodes), start @ block %" PRIu32 "\n", i, rsvd_inodes[i], bg_descs[i].bg_free_inodes_count, blk); bg_descs[i].bg_inode_table = blk; for(j = 0; j < rsvd_inodes[i]; ++j) { if((rv = write_fs_block(sb, bd, blk++, block))) return exit_with_error("Error writing inode tables!\n"); } } return 0; } static int create_bg_descs(ext2_superblock_t *sb) { uint32_t bc = sb->s_blocks_count - sb->s_first_data_block; int odd_count = 0, i; /* Figure out how many block groups we'll have. */ bg_count = bc / sb->s_blocks_per_group; if(bc % sb->s_blocks_per_group) { odd_count = 1; ++bg_count; } /* Allocate space for them */ if(!(bg_descs = (ext2_bg_desc_t *)malloc(sizeof(ext2_bg_desc_t) * bg_count))) return -ENOMEM; if(!(rsvd_blocks = (uint32_t *)malloc(sizeof(uint32_t) * bg_count))) { free(bg_descs); return -ENOMEM; } if(!(rsvd_inodes = (uint32_t *)malloc(sizeof(uint32_t) * bg_count))) { free(rsvd_blocks); free(bg_descs); return -ENOMEM; } memset(bg_descs, 0, sizeof(ext2_bg_desc_t) * bg_count); memset(rsvd_blocks, 0, sizeof(uint32_t) * bg_count); memset(rsvd_inodes, 0, sizeof(uint32_t) * bg_count); sb->s_inodes_per_group = ((sb->s_inodes_count / bg_count) + 7) & ~7; sb->s_inodes_count = sb->s_inodes_per_group * bg_count; sb->s_free_inodes_count = sb->s_inodes_count - 11; /* Set up what we know for sure, we'll get the rest later. */ for(i = 0; i < bg_count - odd_count; ++i) { bg_descs[i].bg_free_blocks_count = sb->s_blocks_per_group; bg_descs[i].bg_free_inodes_count = sb->s_inodes_per_group; } /* Handle the last group specially... */ if(odd_count) { bg_descs[i].bg_free_blocks_count = sb->s_blocks_count - (sb->s_blocks_per_group * (bg_count - 1)) - sb->s_first_data_block; bg_descs[i].bg_free_inodes_count = sb->s_inodes_per_group; } return 0; } static int reserve_blocks(ext2_superblock_t *sb) { int i; uint32_t bc = sb->s_blocks_count - sb->s_first_data_block; uint32_t block_size = (1024 << sb->s_log_block_size); uint32_t bg_per_block, sb_blocks, in_per_block, inode_blocks; uint32_t total_reserved = 0; /* Figure out how big each superblock (or backup thereof) is */ bg_per_block = block_size / sizeof(ext2_bg_desc_t); sb_blocks = 1 + (bg_count / bg_per_block); if(bg_count % bg_per_block) ++sb_blocks; /* Figure out how many blocks we have to reserve beyond that in each block group for inodes. */ in_per_block = block_size / sizeof(ext2_inode_t); inode_blocks = sb->s_inodes_per_group / in_per_block; if(sb->s_inodes_per_group % in_per_block) ++inode_blocks; /* Make sure we have sufficient space in the last block group and that we aren't going to have to readjust things... */ if(bc % sb->s_blocks_per_group) { /* Make sure there's actually enough blocks in the last block group to make things work properly... */ if(bg_descs[bg_count - 1].bg_free_blocks_count <= sb_blocks + inode_blocks + 32) { ds_printf("Dropping last block group due to insufficient space!\n"); ds_printf("This lowers the filesystem size by %" PRIu16 " blocks\n", bg_descs[bg_count - 1].bg_free_blocks_count); sb->s_blocks_count -= bg_descs[bg_count - 1].bg_free_blocks_count; sb->s_free_blocks_count -= bg_descs[bg_count - 1].bg_free_blocks_count; --bg_count; sb->s_inodes_per_group = ((sb->s_inodes_count / bg_count) + 7) & ~7; sb->s_inodes_count = sb->s_inodes_per_group * bg_count; sb->s_free_inodes_count = sb->s_inodes_count - 11; inode_blocks = sb->s_inodes_per_group / in_per_block; if(sb->s_inodes_per_group % in_per_block) ++inode_blocks; } } if(sb->s_rev_level < EXT2_DYNAMIC_REV || !(sb->s_feature_ro_compat & EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)) { for(i = 0; i < bg_count; ++i) { /* Each block group has a superblock backup (and its luggage), an inode table, and 2 blocks for bitmaps */ rsvd_blocks[i] = sb_blocks + 2; rsvd_inodes[i] = inode_blocks; bg_descs[i].bg_free_blocks_count -= rsvd_blocks[i] + rsvd_inodes[i]; bg_descs[i].bg_free_inodes_count = sb->s_inodes_per_group; total_reserved += rsvd_blocks[i] + rsvd_inodes[i]; } } else { rsvd_blocks[0] = sb_blocks + 2; rsvd_inodes[0] = inode_blocks; bg_descs[0].bg_free_blocks_count -= rsvd_blocks[0] + rsvd_inodes[0]; bg_descs[0].bg_free_inodes_count = sb->s_inodes_per_group; total_reserved += rsvd_blocks[0] + rsvd_inodes[0]; for(i = 1; i < bg_count; ++i) { /* Some groups have a superblock backup (and its luggage) */ if(has_superblock(i)) rsvd_blocks[i] = sb_blocks; /* All groups have an inode table and 2 blocks for bitmaps */ rsvd_blocks[i] += 2; rsvd_inodes[i] = inode_blocks; bg_descs[i].bg_free_blocks_count -= rsvd_blocks[i] + rsvd_inodes[i]; bg_descs[i].bg_free_inodes_count = sb->s_inodes_per_group; total_reserved += rsvd_blocks[i] + rsvd_inodes[i]; } } /* Print out where the backup superblocks are. */ if(bg_count > 1) { ds_printf("Superblock backups stored on blocks:\n\t"); ds_printf("%" PRIu32, sb->s_blocks_per_group + sb->s_first_data_block); if(sb->s_rev_level < EXT2_DYNAMIC_REV || !(sb->s_feature_ro_compat & EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)) { for(i = 2; i < bg_count; ++i) { ds_printf(", %" PRIu32, i * sb->s_blocks_per_group + sb->s_first_data_block); } } else { for(i = 2; i < bg_count; ++i) { if(has_superblock(i)) ds_printf(", %" PRIu32, i * sb->s_blocks_per_group + sb->s_first_data_block); } } } else { ds_printf("FS has only one block group, no superblock backups!\n"); } ds_printf("\n"); ds_printf("%" PRIu32 " total reserved blocks (superblocks, inodes, bitmaps)\n", total_reserved); sb->s_free_blocks_count -= total_reserved; ds_printf("%" PRIu32 " blocks left afterwards\n", sb->s_free_blocks_count); return 0; } static int write_root_dir(ext2_superblock_t *sb, kos_blockdev_t *bd) { ext2_dirent_t *ent = (ext2_dirent_t *)block; uint8_t ft = 0; uint32_t bs = 1024 << sb->s_log_block_size; uint32_t blk, ino_blk; int rv, i; ext2_inode_t *ino; int fs_per_block = 10 + sb->s_log_block_size - bd->l_block_size; time_t now = time(NULL); if(sb->s_rev_level >= EXT2_DYNAMIC_REV && (sb->s_feature_incompat & EXT2_FEATURE_INCOMPAT_FILETYPE)) ft = EXT2_FT_DIR; memset(block, 0, bs); /* Fill in "." */ ent->inode = EXT2_ROOT_INO; ent->rec_len = 12; ent->name_len = 1; ent->file_type = ft; ent->name[0] = '.'; ent->name[1] = ent->name[2] = ent->name[3] = '\0'; /* Fill in ".." */ ent = (ext2_dirent_t *)(block + 12); ent->inode = EXT2_ROOT_INO; ent->rec_len = 12; ent->name_len = 2; ent->file_type = ft; ent->name[0] = ent->name[1] = '.'; ent->name[2] = ent->name[3] = '\0'; /* Fill in "lost+found" */ ent = (ext2_dirent_t *)(block + 24); ent->inode = 11; ent->rec_len = bs - 24; ent->name_len = 10; ent->file_type = ft; strncpy((char *)ent->name, "lost+found", 12); /* Update the stuff in the block group descriptor. */ bg_descs[0].bg_used_dirs_count += 2; blk = rsvd_blocks[0] + rsvd_inodes[0] + sb->s_first_data_block; rsvd_blocks[0] += 3; bg_descs[0].bg_free_blocks_count -= 3; sb->s_free_blocks_count -= 3; ds_printf("Writing root directory @ %" PRIu32 "\n", blk); /* Write the directory to the fs */ if((rv = write_fs_block(sb, bd, blk, block))) return exit_with_error("Error writing root directory\n"); /* Deal with lost+found (which is always at least two blocks) */ memset(ent, 0, 20); ent = (ext2_dirent_t *)block; ent->inode = 11; ent = (ext2_dirent_t *)(block + 12); ent->rec_len = bs - 12; ent->inode = EXT2_ROOT_INO; ds_printf("Writing lost+found directory @ %" PRIu32 "\n", blk + 1); if((rv = write_fs_block(sb, bd, blk + 1, block))) return exit_with_error("Error writing lost+found\n"); memset(block, 0, bs); ent = (ext2_dirent_t *)block; ent->rec_len = bs; if((rv = write_fs_block(sb, bd, blk + 2, block))) return exit_with_error("Error writing lost+found\n"); /* Fill in the inode for the root directory */ if((rv = read_inode_block(sb, bd, EXT2_ROOT_INO, block, &ino, &ino_blk))) return exit_with_error("Cannot read root inode\n"); ino->i_mode = EXT2_S_IFDIR | EXT2_S_IRUSR | EXT2_S_IWUSR | EXT2_S_IXUSR | EXT2_S_IRGRP | EXT2_S_IXGRP | EXT2_S_IROTH | EXT2_S_IXOTH; ino->i_uid = 0; ino->i_size = bs; ino->i_atime = ino->i_ctime = ino->i_mtime = now; ino->i_dtime = 0; ino->i_gid = 0; ino->i_links_count = 3; ino->i_blocks = (1 << fs_per_block); ino->i_flags = 0; ino->i_osd1 = 0; ino->i_block[0] = blk; for(i = 1; i < 15; ++i) ino->i_block[i] = 0; ino->i_generation = 0; ino->i_file_acl = ino->i_dir_acl = 0; ino->i_faddr = 0; ino->i_osd2.l_i_frag = ino->i_osd2.l_i_fsize = 0; ino->i_osd2.reserved = 0; ino->i_osd2.l_i_uid_high = ino->i_osd2.l_i_gid_high = 0; ino->i_osd2.reserved2 = 0; if((rv = write_fs_block(sb, bd, ino_blk, block))) return exit_with_error("Cannot write root inode\n"); /* Fill in the inode for lost+found */ if((rv = read_inode_block(sb, bd, 11, block, &ino, &ino_blk))) return exit_with_error("Cannot read lost+found inode\n"); ino->i_mode = EXT2_S_IFDIR | EXT2_S_IRUSR | EXT2_S_IWUSR | EXT2_S_IXUSR | EXT2_S_IRGRP | EXT2_S_IXGRP | EXT2_S_IROTH | EXT2_S_IXOTH; ino->i_uid = 0; ino->i_size = bs << 1; ino->i_atime = ino->i_ctime = ino->i_mtime = now; ino->i_dtime = 0; ino->i_gid = 0; ino->i_links_count = 2; ino->i_blocks = (2 << fs_per_block); ino->i_flags = 0; ino->i_osd1 = 0; ino->i_block[0] = blk + 1; ino->i_block[1] = blk + 2; for(i = 2; i < 15; ++i) ino->i_block[i] = 0; ino->i_generation = 0; ino->i_file_acl = ino->i_dir_acl = 0; ino->i_faddr = 0; ino->i_osd2.l_i_frag = ino->i_osd2.l_i_fsize = 0; ino->i_osd2.reserved = 0; ino->i_osd2.l_i_uid_high = ino->i_osd2.l_i_gid_high = 0; ino->i_osd2.reserved2 = 0; if((rv = write_fs_block(sb, bd, ino_blk, block))) return exit_with_error("Cannot write lost+found inode\n"); return 0; } static inline void ext2_bit_set(uint32_t *btbl, uint32_t bit_num) { int byte = (bit_num >> 5); int bit = (bit_num & 0x1F); btbl[byte] |= (1 << bit); } static int write_bitmaps(ext2_superblock_t *sb, kos_blockdev_t *bd) { int i; uint32_t block_size = 1024 << sb->s_log_block_size; uint32_t bg_per_block, sb_blocks, j, blk, first_inode = 11; uint32_t last_grp_blks; /* Figure out how big each superblock (or backup thereof) is */ bg_per_block = block_size / sizeof(ext2_bg_desc_t); sb_blocks = 1 + (bg_count / bg_per_block); if(bg_count % bg_per_block) ++sb_blocks; /* Go through each block group and write the block bitmap. */ for(i = 0; i < bg_count - 1; ++i) { memset(block, 0, block_size); /* Set the bits for all used blocks */ for(j = 0; j < rsvd_blocks[i] + rsvd_inodes[i]; ++j) { ext2_bit_set((uint32_t *)block, j); } blk = i * sb->s_blocks_per_group + sb->s_first_data_block; if(sb->s_rev_level < EXT2_DYNAMIC_REV || !(sb->s_feature_ro_compat & EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER) || has_superblock(i)) blk += sb_blocks; bg_descs[i].bg_block_bitmap = blk; ds_printf("Writing block bitmap for group %d @ %" PRIu32 "\n", i, blk); if(write_fs_block(sb, bd, blk, block)) return exit_with_error("Error writing bitmap\n"); } /* We might have padding bits in the last bitmap... */ memset(block, 0, block_size); /* Set the bits for all used blocks */ for(j = 0; j < rsvd_blocks[i] + rsvd_inodes[i]; ++j) { ext2_bit_set((uint32_t *)block, j); } /* Figure out how many padding bits we have and set them. */ last_grp_blks = (sb->s_blocks_count - sb->s_first_data_block) % sb->s_blocks_per_group; if(last_grp_blks) { for(j = sb->s_blocks_per_group - 1; j >= last_grp_blks; --j) { ext2_bit_set((uint32_t *)block, j); } } blk = i * sb->s_blocks_per_group + sb->s_first_data_block; if(sb->s_rev_level < EXT2_DYNAMIC_REV || !(sb->s_feature_ro_compat & EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER) || has_superblock(i)) blk += sb_blocks; bg_descs[i].bg_block_bitmap = blk; ds_printf("Writing block bitmap for group %d @ %" PRIu32 "\n", i, blk); if(write_fs_block(sb, bd, blk, block)) return exit_with_error("Error writing bitmap\n"); /* We should only have inodes in group 0, so we only have to write anything but 0 bits to that one. */ memset(block, 0, block_size); if(sb->s_rev_level >= EXT2_DYNAMIC_REV) first_inode = sb->s_first_ino; /* Set the reserved bits (inodes 1-11) */ for(j = 0; j < first_inode; ++j) { ext2_bit_set((uint32_t *)block, j); } blk = sb->s_first_data_block + 1 + sb_blocks; bg_descs[0].bg_inode_bitmap = blk; ds_printf("Writing inode bitmap for group 0 @ %" PRIu32 "\n", blk); if(write_fs_block(sb, bd, blk, block)) return exit_with_error("Error writing bitmap\n"); memset(block, 0, block_size); for(i = 1; i < bg_count; ++i) { blk = i * sb->s_blocks_per_group + sb->s_first_data_block + 1; if(sb->s_rev_level < EXT2_DYNAMIC_REV || !(sb->s_feature_ro_compat & EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER) || has_superblock(i)) blk += sb_blocks; bg_descs[i].bg_inode_bitmap = blk; ds_printf("Writing inode bitmap for group %d @ %" PRIu32 "\n", i, blk); if(write_fs_block(sb, bd, blk, block)) return exit_with_error("Error writing bitmap\n"); } return 0; } /* For testing outside of KOS... */ #ifndef _arch_dreamcast static int blockdev_dummy(kos_blockdev_t *d) { (void)d; return 0; } static int blockdev_shutdown(kos_blockdev_t *d) { FILE *fp = (FILE *)d->dev_data; fclose(fp); return 0; } static int blockdev_read(kos_blockdev_t *d, uint32_t block, size_t count, void *buf) { FILE *fp = (FILE *)d->dev_data; int fd = fileno(fp); ssize_t rv; rv = pread(fd, buf, count << d->l_block_size, block << d->l_block_size); return (rv > 0) ? 0 : -1; } static int blockdev_write(kos_blockdev_t *d, uint32_t block, size_t count, const void *buf) { FILE *fp = (FILE *)d->dev_data; int fd = fileno(fp); ssize_t rv; rv = pwrite(fd, buf, count << d->l_block_size, block << d->l_block_size); return (rv > 0) ? 0 : -1; } static uint32_t blockdev_count(kos_blockdev_t *d) { FILE *fp = (FILE *)d->dev_data; off_t len; fseeko(fp, 0, SEEK_END); len = ftello(fp); fseeko(fp, 0, SEEK_SET); return (uint32_t)(len >> d->l_block_size); } static kos_blockdev_t the_bd = { NULL, 9, &blockdev_dummy, &blockdev_shutdown, &blockdev_read, &blockdev_write, &blockdev_count }; static int sd_init(void) { return 0; } static void sd_shutdown(void) { } #endif int main(int argc, char *argv[]) { kos_blockdev_t sd_dev; uint8_t partition_type; uint32_t block_count, inode_count; uint64_t partition_size; uint32_t fs_blocksz; ext2_superblock_t sb; time_t now = time(NULL); int i; int part = 0; if(argc < 3) { ds_printf("Usage: %s device(ide,sd) partition(0-3)\n", argv[0]); return CMD_NO_ARG; } part = atoi(argv[2]); if(part < 0 || part > 3) { ds_printf("DS_ERROR: partition number can be only 0-3\n"); return CMD_ERROR; } srand(now); if(sd_init()) { return exit_with_error("Could not initialize the SD card.\n" "Please make sure that you have an SD card\n" "adapter plugged in and an SD card inserted."); } #ifdef _arch_dreamcast (void)argc; (void)argv; /* Grab the block device for the first partition on the SD card. Note that you must have the SD card formatted with an MBR partitioning scheme. */ if(sd_blockdev_for_partition(0, &sd_dev, &partition_type)) { //sd_shutdown(); return exit_with_error("Could not find the first partition on the SD card!\n"); } /* Read the MBR so we can change the partition type if needed. */ if(sd_read_blocks(0, 1, block)) { //sd_shutdown(); return exit_with_error("Cannot read the MBR from the SD card!\n"); } /* If it isn't already set to 0x83 (Linux), set it to 0x83. */ if(block[0x01BE + 4] != 0x83) { ds_printf("Partition type 0x%02x will be replaced by 0x83\n", block[0x01BE + 4]); block[0x01BE + 4] = 0x83; if(sd_write_blocks(0, 1, block)) { //sd_shutdown(); return exit_with_error("Cannot write MBR back to the SD card!\n"); } } #else (void)partition_type; if(argc != 2) return exit_with_error("Must supply an image filename!\n"); /* Whee... random scopes for fun and profit! */ { FILE *fp = fopen(argv[1], "r+b"); if(!fp) { return exit_with_error("Cannot open filesystem image file\n"); } the_bd.dev_data = fp; sd_dev = the_bd; } #endif /* Initialize the block device. */ if(sd_dev.init(&sd_dev)) { //sd_shutdown(); return exit_with_error("Could not initialize the SD block device!\n"); } /* Figure out how large the partition is, so we know how big to make our filesystem blocks. */ block_count = sd_dev.count_blocks(&sd_dev); partition_size = (uint64_t)(1 << sd_dev.l_block_size) * block_count; ds_printf("%" PRIu32 " raw blocks in partition (%d bytes each)\n", block_count, 1 << sd_dev.l_block_size); ds_printf("Detected partition size of %" PRIu64 " bytes\n", partition_size); fs_blocksz = pick_ext2_bs(partition_size); if(fs_blocksz < (uint32_t)(1 << sd_dev.l_block_size)) { fs_blocksz = 1 << sd_dev.l_block_size; if(fs_blocksz > 4 * KiB) { sd_dev.shutdown(&sd_dev); //sd_shutdown(); return exit_with_error("Cowardly refusing to make a filesystem with a\n" "block size of > 4096 bytes."); } } if(partition_size / fs_blocksz < 64) { sd_dev.shutdown(&sd_dev); //sd_shutdown(); return exit_with_error("Cowardly refusing to make a filesystem with\n" "less than 64 blocks."); } ds_printf("Will create ext2fs with %" PRIu32 " byte blocks\n", fs_blocksz); /* Figure out how many blocks and inodes we'll make. Arbitrarily take inode count to be block_count / 4. */ block_count = partition_size / fs_blocksz; inode_count = ((block_count / 4) + 7) & ~7; ds_printf("Initial params: %" PRIu32 " FS blocks; %" PRIu32 " inodes\n", block_count, inode_count); /* Start filling in our superblock. */ memset(&sb, 0, sizeof(ext2_superblock_t)); sb.s_inodes_count = inode_count; sb.s_blocks_count = block_count; sb.s_r_blocks_count = 0; sb.s_free_blocks_count = block_count - (fs_blocksz == 1024 ? 1 : 0); sb.s_free_inodes_count = inode_count - 11; sb.s_first_data_block = (fs_blocksz == 1024 ? 1 : 0); sb.s_log_block_size = fs_blocksz >> 11; sb.s_log_frag_size = fs_blocksz >> 11; sb.s_blocks_per_group = fs_blocksz * 8; sb.s_frags_per_group = fs_blocksz * 8; sb.s_inodes_per_group = fs_blocksz * 2; sb.s_mtime = sb.s_wtime = now; sb.s_mnt_count = 0; sb.s_max_mnt_count = 64; /* Picked arbitrarily. */ sb.s_magic = 0xEF53; sb.s_state = EXT2_VALID_FS; sb.s_errors = EXT2_ERRORS_RO; sb.s_minor_rev_level = 0; sb.s_lastcheck = now; sb.s_checkinterval = 180 * 60 * 60 * 24; /* 180 days */ sb.s_creator_os = EXT2_OS_LINUX; /* Yep... We're Linux. ;-) */ sb.s_rev_level = EXT2_DYNAMIC_REV; sb.s_def_resuid = 0; sb.s_def_resgid = 0; sb.s_first_ino = 11; sb.s_inode_size = 128; sb.s_block_group_nr = 0; sb.s_feature_compat = EXT2_FEATURE_COMPAT_EXT_ATTR; sb.s_feature_incompat = EXT2_FEATURE_INCOMPAT_FILETYPE; sb.s_feature_ro_compat = EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER | EXT2_FEATURE_RO_COMPAT_LARGE_FILE; /* Make a nice v4 UUID... */ for(i = 0; i < 16; ++i) { sb.s_uuid[i] = (uint8_t)rand(); } sb.s_uuid[6] = 0x40 | (sb.s_uuid[6] & 0x0F); sb.s_uuid[8] = 0x80 | (sb.s_uuid[8] & 0x3F); strncpy((char *)sb.s_volume_name, "DreamShell", 16); /* Now that we have a superblock, start on the block group descriptors. */ ds_printf("Creating block group descriptors\n"); if(create_bg_descs(&sb)) { sd_dev.shutdown(&sd_dev); //sd_shutdown(); return exit_with_error("Cannot create block group descriptors!\n"); } ds_printf("Counted %d block groups\n", bg_count); reserve_blocks(&sb); ds_printf("Final filesystem params: %" PRIu32 " blocks, %" PRIu32 " inodes\n", sb.s_blocks_count, sb.s_inodes_count); write_blank_inode_tables(&sb, &sd_dev); write_root_dir(&sb, &sd_dev); write_bitmaps(&sb, &sd_dev); bg_descs[0].bg_free_inodes_count -= 11; write_superblocks(&sb, &sd_dev); sd_dev.shutdown(&sd_dev); //sd_shutdown(); exit_with_error("Format complete."); return CMD_OK; } <file_sep>/modules/ogg/liboggvorbis/liboggvorbisplay/main.c #include <kos.h> static kthread_t * thd = NULL; static void *sndserver_thread(void *blagh) { printf("sndserver: pid is %d\n", thd_get_current()->tid); sndoggvorbis_mainloop(); return NULL; } int sndoggvorbis_init() { if (thd) { printf("sndserver: already initialized!\n"); return -1; } if (snd_stream_init() < 0) return -1; printf("sndserver: initializing sndoggvorbis 0.7 [OggVorbis 1.0 based]\n"); thd = thd_create(0, sndserver_thread, NULL); if (thd != NULL) { /* Wait until the oggvorbis decoder thread is ready */ sndoggvorbis_wait_start(); printf("sndserver: successfully created thread\n"); return 0; } else { printf("sndserver: error creating thread\n"); return -1; } } void sndoggvorbis_thd_quit(); void sndoggvorbis_shutdown() { if (!thd) { printf("sndserver: not initialized!\n"); return; } sndoggvorbis_thd_quit(); thd_join(thd, NULL); thd = NULL; printf("sndserver: exited successfully\n"); } <file_sep>/firmware/isoldr/loader/kos/conio.h /* KallistiOS ##version## conio.h (c)2002 <NAME> Adapted from Kosh, (c)2000 <NAME>, (c)2014 SWAT */ #ifndef __CONIO_H #define __CONIO_H #include <sys/cdefs.h> __BEGIN_DECLS /* functions */ void conio_scroll(); void conio_putch(int ch); void conio_putstr(char *str); int conio_printf(const char *fmt, ...); void conio_clear(); __END_DECLS #endif /* __CONIO_H */ <file_sep>/firmware/isoldr/loader/kos/src/biosfont.c /* KallistiOS ##version## biosfont.c Copyright (C)2000-2002,2004 <NAME> */ #include <main.h> #include <dc/biosfont.h> /* This module handles interfacing to the bios font. It supports the standard European encodings via ISO8859-1. Thanks to <NAME> for the bios font information. */ /* A little assembly that grabs the font address */ //extern uint8* get_font_address(); //__asm__(" .text\n" // " .align 2\n" // "_get_font_address:\n" // " mov.l syscall_b4,r0\n" // " mov.l @r0,r0\n" // " jmp @r0\n" // " mov #0,r1\n" // "\n" // " .align 4\n" // "syscall_b4:\n" // " .long 0x8c0000b4\n" //); /* Given an ASCII character, find it in the BIOS font if possible */ uint8 *bfont_find_char(int ch) { int index = -1; uint8 *fa = (uint8*)bfont_saved_addr; //get_font_address(); /* 33-126 in ASCII are 1-94 in the font */ if (ch >= 33 && ch <= 126) index = ch - 32; /* 160-255 in ASCII are 96-161 in the font */ if (ch >= 160 && ch <= 255) index = ch - (160 - 96); /* Map anything else to a space */ if (index == -1) index = 72 << 2; return fa + index*36; } /* Draw char */ void bfont_draw(uint16 *buffer, uint16 fg, uint16 bg, int c) { uint8 *ch; uint16 word; int x, y; const int bufwidth = 640; ch = bfont_find_char(c); for (y=0; y<24; ) { /* Do the first row */ word = (((uint16)ch[0]) << 4) | ((ch[1] >> 4) & 0x0f); for (x=0; x<12; x++) { if (word & (0x0800 >> x)) { *buffer = fg; *(buffer - 1) = fg; } else { *buffer = bg; } buffer++; } buffer += bufwidth - 12; y++; /* Do the second row */ word = ( (((uint16)ch[1]) << 8) & 0xf00 ) | ch[2]; for (x=0; x<12; x++) { if (word & (0x0800 >> x)) { *buffer = fg; *(buffer - 1) = fg; } else { *buffer = bg; } buffer++; } buffer += bufwidth - 12; y++; ch += 3; } } void bfont_draw_str(uint16 *buffer, uint16 fg, uint16 bg, const char *str) { while (*str) { bfont_draw(buffer, fg, bg, *str); str++; buffer += 12; } } <file_sep>/utils/iso_make/info/readme.txt С помощью этого пакета вы можете создавать образы для модуля DreamShell - isoldr. Положите все файлы с диска или образа (включая IP.BIN) в директорию data и кликните 2 раза по файлу hack_lba.bat а затем create_iso.bat Вы можете сжать образ с помощью compress_iso.bat Вы можете оптимизировать GDI образ с помощью optimize_gdi.bat English: With this package you can create images for the module DreamShell - isoldr. Put all files (and IP.BIN) from CD/Image to the "data" directory and click 2 times on the file hack_lba.bat and then create_iso.bat And you can compress iso to cso with compress_iso.bat And you can optimize GDI tracks with optimize_gdi.bat<file_sep>/resources/lua/lib/bit/utf8.lua --[[--------------- Utf8 v0.4 ------------------- utf8 -> unicode ucs2 converter How to use: to convert: ucs2_string = utf8.utf_to_uni(utf8_string) to view a string in hex: utf8.print_hex(str) Under the MIT license. Utf8 is a part of LuaBit Project(http://luaforge.net/projects/bit/). copyright(c) 2007 hanzhao (<EMAIL>) --]]--------------- require '/cd/lua/lib/bit/bit.lua'; require '/cd/lua/lib/bit/hex.lua'; do local BYTE_1_HEAD = hex.to_dec('0x00') -- 0### #### local BYTE_2_HEAD = hex.to_dec('0xC0') -- 110# #### local BYTE_3_HEAD = hex.to_dec('0xE0') -- 1110 #### -- mask to get the head local BYTE_1_MASK = hex.to_dec('0x80') -- 1### #### local BYTE_2_MASK = hex.to_dec('0xE0') -- 111# #### local BYTE_3_MASK = hex.to_dec('0xF0') -- 1111 #### -- tail byte mask local TAIL_MASK = hex.to_dec('0x3F') -- 10## #### local mask_tbl = { BYTE_3_MASK, BYTE_2_MASK, BYTE_1_MASK, } local head_tbl = { BYTE_3_HEAD, BYTE_2_HEAD, BYTE_1_HEAD, } local len_tbl = { [BYTE_1_HEAD] = 1, [BYTE_2_HEAD] = 2, [BYTE_3_HEAD] = 3, } local function utf_read_char(utf, start) local head_byte = string.byte(utf, start) --print('head byte ' .. hex.to_hex(head_byte)) for m = 1, table.getn(mask_tbl) do local mask = mask_tbl[m] -- head match local head = bit.band(head_byte, mask) --print('head ' .. hex.to_hex(head) .. ' ' .. hex.to_hex(mask)) if(head == head_tbl[m]) then local len = len_tbl[head_tbl[m]] --print('len ' .. len) local tail_idx = start + len - 1 local char = 0 -- tail for i = tail_idx, start + 1, -1 do local tail_byte = string.byte(utf, i) local byte = bit.band(tail_byte, TAIL_MASK) --print('byte ' .. hex.to_hex(byte).. ' = ' .. hex.to_hex(tail_byte) .. '&'..hex.to_hex(TAIL_MASK)) if(tail_idx - i > 0) then local sft = bit.blshift(byte, (tail_idx - i) * 6) --print('shift ' .. hex.to_hex(sft) .. ' ' .. hex.to_hex(byte) .. ' ' .. ((tail_idx - i) * 6)) char = bit.bor(char, sft) --print('char ' .. hex.to_hex(char)) else char = byte end end -- tails -- add head local head_val = bit.band(head_byte, bit.bnot(mask)) --print('head val ' .. hex.to_hex(head_val)) head_val = bit.blshift(head_val, (len-1) * 6) --print('head val ' .. hex.to_hex(head_val)) char = bit.bor(head_val, char) --print('char ' .. hex.to_hex(char)) return char, len end -- if head match end -- for mask error('not find proper head mask') end local function print_hex(str) local cat = '' for i=1, string.len(str) do cat = cat .. ' ' .. hex.to_hex(string.byte(str, i)) end print(cat) end local HI_MASK = hex.to_dec('0xF0') local LO_MASK = hex.to_dec('0xFF') local function char_to_str(char) local hi, lo = bit.brshift(char, 8), bit.band(char, LO_MASK) -- print(hex.to_hex(char)..' '..hex.to_hex(hi)..' ' .. hex.to_hex(lo)) if(hi == 0) then return string.format('%c\0', lo) elseif(lo == 0) then return string.format('\0%c', hi) else return string.format('%c%c', lo, hi) end end local function utf_to_uni(utf) local n = string.len(utf) local i = 1 local uni = '' while(i <= n) do --print('---') char, len = utf_read_char(utf, i) i = i + len --print(string.len(char_to_str(char))) uni = uni..char_to_str(char) end --print_hex(uni) return uni end -- interface utf8 = { utf_to_uni = utf_to_uni, print_hex = print_hex, } end --[[ -- test byte_3 = string.format('%c%c%c', hex.to_dec('0xE7'), hex.to_dec('0x83'), hex.to_dec('0xad')) print(string.len(byte_3)) utf8.utf_to_uni(byte_3) --]] --[[ byte_2 = string.format('%c%c', hex.to_dec('0xC2'), hex.to_dec('0x9D')) utf8.utf_to_uni(byte_2) byte_1 = string.format('%c', hex.to_dec('0xB')) utf8.utf_to_uni(byte_1) --]] --[[ test_mul = string.format( '%c%c%c%c%c%c%c%c%c', hex.to_dec('0xE8'),hex.to_dec('0xAF'), hex.to_dec('0xBA'), hex.to_dec('0xE5'),hex.to_dec('0x9F'), hex.to_dec('0xBA'), hex.to_dec('0xE4'),hex.to_dec('0xBA'), hex.to_dec('0x9A')) utf8.print_hex(utf8.utf_to_uni(test_mul)) --]]<file_sep>/modules/gumbo/gumbo/Makefile.am # Googletest magic. Gumbo relies on Googletest for its unittests, and # Googletest (by design) does not provide a "make install" option. Instead, # we'll assume you copy (or symlink) the Googletest distribution into a 'gtest' # directory inside the main library directory, and then provide rules to build # it automatically. This approach (and these rules) are copied from the # protobuf distribution. # Build gtest before we build protobuf tests.  We don't add gtest to SUBDIRS # because then "make check" would also build and run all of gtest's own tests, # which takes a lot of time and is generally not useful to us.  Also, we don't # want "make install" to recurse into gtest since we don't want to overwrite # the installed version of gtest if there is one. check-local: @echo "Making lib/libgtest.a lib/libgtest_main.a in gtest" @cd gtest && ./configure && $(MAKE) $(AM_MAKEFLAGS) lib/libgtest.la lib/libgtest_main.la # We would like to clean gtest when "make clean" is invoked.  But we have to # be careful because clean-local is also invoked during "make distclean", but # "make distclean" already recurses into gtest because it's listed among the # DIST_SUBDIRS.  distclean will delete gtest/Makefile, so if we then try to # cd to the directory again and "make clean" it will fail.  So, check that the # Makefile exists before recursing. clean-local: @if test -e gtest/Makefile; then \ echo "Making clean in gtest"; \ cd gtest && $(MAKE) $(AM_MAKEFLAGS) clean; \ fi lib_LTLIBRARIES = libgumbo.la libgumbo_la_CFLAGS = -Wall libgumbo_la_LDFLAGS = -version-info 1:0:0 -no-undefined libgumbo_la_SOURCES = \ src/attribute.c \ src/attribute.h \ src/char_ref.c \ src/char_ref.h \ src/error.c \ src/error.h \ src/insertion_mode.h \ src/parser.c \ src/parser.h \ src/string_buffer.c \ src/string_buffer.h \ src/string_piece.c \ src/string_piece.h \ src/tag.c \ src/token_type.h \ src/tokenizer.c \ src/tokenizer.h \ src/tokenizer_states.h \ src/utf8.c \ src/utf8.h \ src/util.c \ src/util.h \ src/vector.c \ src/vector.h include_HEADERS = src/gumbo.h pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = gumbo.pc check_PROGRAMS = gumbo_test TESTS = gumbo_test gumbo_test_LDADD = libgumbo.la gtest/lib/libgtest.la gtest/lib/libgtest_main.la gumbo_test_CPPFLAGS = -I"$(srcdir)/src" -I"$(srcdir)/gtest/include" gumbo_test_SOURCES = \ tests/attribute.cc \ tests/char_ref.cc \ tests/parser.cc \ tests/string_buffer.cc \ tests/string_piece.cc \ tests/tokenizer.cc \ tests/test_utils.cc \ tests/utf8.cc \ tests/vector.cc gumbo_test_DEPENDENCIES = check-local libgumbo.la noinst_PROGRAMS = clean_text find_links get_title positions_of_class LDADD = libgumbo.la AM_CPPFLAGS = -I"$(srcdir)/src" clean_text_SOURCES = examples/clean_text.cc find_links_SOURCES = examples/find_links.cc get_title_SOURCES = examples/get_title.c positions_of_class_SOURCES = examples/positions_of_class.cc <file_sep>/modules/ffmpeg/player.c /* DreamShell ##version## player.c - ffmpeg player Copyright (C)2011-2014 SWAT */ #define USE_DIRECT_AUDIO 1 //#define USE_HW_YUV 1 #include "ds.h" #ifdef USE_DIRECT_AUDIO #include "aica.h" #include "drivers/aica_cmd_iface.h" #else #include "drivers/aica_cmd_iface.h" #endif #include "libavcodec/avcodec.h" #include "libavformat/avformat.h" #define ASIC_EVT_PVR_YUV_DONE 0x0006 #define PVR_YUV_STAT 0x0150 #define PVR_YUV_CONV 0x10800000 #define PVR_YUV_FORMAT_YUV420 0 #define PVR_YUV_FORMAT_YUV422 1 #define PVR_YUV_MODE_SINGLE 0 #define PVR_YUV_MODE_MULTI 1 typedef struct video_txr { pvr_poly_hdr_t hdr; int tw, th; int width, height; void (*render_cb)(void *); pvr_ptr_t addr; void *backbuf; } video_txr_t; #ifndef USE_HW_YUV static void yuvtex(uint16 *tbuf,int tstride,unsigned width,unsigned height,uint8 *ybuf,int ystride,uint8 *ubuf,int ustride,uint8 *vbuf,int vstride) { int h = height/2; uint8 u, v; do { uint8 *uptr,*vptr,*yptr,*yptr2; uint8 *tex,*tex2; int w = width/2; tex = (uint8*)tbuf; tbuf+=tstride; tex2 = (uint8*)tbuf; tbuf+=tstride; yptr = ybuf; ybuf +=ystride; yptr2 = ybuf; ybuf +=ystride; uptr = ubuf; ubuf +=ustride; vptr = vbuf; vbuf +=vstride; do { #if 1 //uint8 u,v; u = *uptr++; v = *vptr++; // asm("pref @%0"::"r"(yptr+4)); tex[0] = u; tex[1] = *yptr++; tex[2] = v; tex[3] = *yptr++; tex2[0] = u; tex2[1] = *yptr2++; tex2[2] = v; tex2[3] = *yptr2++; tex+=4; tex2+=4; #else //uint8 u,v; u = *uptr++; v = *vptr++; #define store(base,offset,data) __asm__("mov.b %1,@(" #offset ",%0)"::"r"(base),"z"(data)) tex[0] = u; store(tex,1,*yptr++); store(tex,2,v); store(tex,3,*yptr++); tex2[0] = u; store(tex2,1,*yptr2++); store(tex2,2,v); store(tex2,3,*yptr2++); tex+=4; tex2+=4; #endif } while(--w); } while(--h); } #else //static uint32 yuv_inited = 0; static semaphore_t yuv_done; void block8x8_copy(void *src, void *dst, uint32 stride); uint32 mblock_copy(void *lum, void *b, void *r, void *dst, int w, int h) { uint32 x, y; uint32 old_dst = (uint32)dst; for ( y = 0; y < h / 16; y++ ) { for ( x = 0; x < w / 2; x += 8 ) { block8x8_copy ( b + x, dst, w / 2 ); dst += 64; block8x8_copy ( r + x, dst, w / 2 ); dst += 64; block8x8_copy ( lum + x * 2, dst, w ); dst += 64; block8x8_copy ( lum + x * 2 + 8, dst, w ); dst += 64; block8x8_copy ( lum + x * 2 + w * 8, dst, w ); dst += 64; block8x8_copy ( lum + x * 2 + 8 + w * 8, dst, w ); dst += 64; } lum += w * 16; b += w * 4; r += w * 4; } return (uint32)dst - old_dst; } static void asic_yuv_evt_handler(uint32 code) { sem_signal(&yuv_done); thd_schedule(1, 0); } int yuv_conv_init() { asic_evt_set_handler(ASIC_EVT_PVR_YUV_DONE, asic_yuv_evt_handler); asic_evt_enable(ASIC_EVT_PVR_YUV_DONE, ASIC_IRQ_DEFAULT); sem_init(&yuv_done, 0); return 0; } void yuv_conv_shutdown() { asic_evt_disable(ASIC_EVT_PVR_YUV_DONE, ASIC_IRQ_DEFAULT); asic_evt_set_handler(ASIC_EVT_PVR_YUV_DONE, NULL); sem_destroy(&yuv_done); } void yuv_conv_setup(pvr_ptr_t addr, int mode, int format, int width, int height) { PVR_SET(PVR_YUV_CFG_1, ((((width / 16))-1) | ((height / 16)-1) << 8 | mode << 16 | format << 24)); PVR_SET(PVR_YUV_ADDR, (uint32)addr); } void yuv_conv_frame(video_txr_t *txr, AVFrame *frame, AVCodecContext *codec, int block) { uint32 size = mblock_copy(frame->data[0], frame->data[1], frame->data[2], txr->backbuf, codec->width, codec->height); dcache_flush_range((uint32)txr->backbuf, size); while (!pvr_dma_ready()); pvr_dma_transfer((void*)txr->backbuf, PVR_YUV_CONV, size, PVR_DMA_TA, 0, NULL, 0); if(block) { sem_wait(&yuv_done); // printf("PVR: YUV Macroblocks Converted: %ld\n", PVR_GET(PVR_YUV_STAT)); } } #endif static void FreeVideoTexture(video_txr_t *txr) { if (txr->addr) { pvr_mem_free(txr->addr); txr->addr = NULL; } if (txr->backbuf) { free(txr->backbuf); txr->backbuf = NULL; } } static void MakeVideoTexture(video_txr_t *txr, int width, int height, int format, int filler) { pvr_poly_cxt_t tmp; int tw,th; for(tw = 8; tw < width ; tw <<= 1); for(th = 8; th < height; th <<= 1); txr->width = width; txr->height = height; txr->tw = tw; txr->th = th; if(txr->addr || txr->backbuf) { FreeVideoTexture(txr); } txr->backbuf = memalign(32, txr->tw * txr->height * 2); txr->addr = pvr_mem_malloc(tw * th * 2); pvr_poly_cxt_txr(&tmp, PVR_LIST_OP_POLY, format, tw, th, txr->addr, filler); pvr_poly_compile(&txr->hdr, &tmp); } static void RenderVideoTexture(video_txr_t *txr, int x, int y, int w, int h, int color) { pvr_vertex_t v; pvr_prim(&txr->hdr, sizeof(txr->hdr)); float u0,v0,u1,v1; float x0,y0,x1,y1; u0 = 0; v0 = 0; u1 = (float)txr->width/txr->tw; v1 = (float)txr->height/txr->th; x0 = x; y0 = y; x1 = x + w; y1 = y + h; v.flags = PVR_CMD_VERTEX; v.argb = color; v.oargb = 0; v.z = 512; v.x = x0; v.y = y0; v.u = u0; v.v = v0; pvr_prim(&v,sizeof(v)); v.x = x1; v.y = y0; v.u = u1; v.v = v0; pvr_prim(&v,sizeof(v)); v.x = x0; v.y = y1; v.u = u0; v.v = v1; pvr_prim(&v,sizeof(v)); v.flags = PVR_CMD_VERTEX_EOL; v.x = x1; v.y = y1; v.u = u1; v.v = v1; pvr_prim(&v,sizeof(v)); } static void RenderVideo(video_txr_t *txr, AVFrame *frame, AVCodecContext *codec) { switch(codec->pix_fmt) { case PIX_FMT_YUVJ420P: case PIX_FMT_YUVJ422P: case PIX_FMT_YUV420P: #ifdef USE_HW_YUV yuv_conv_frame(txr, frame, codec, -1); #else yuvtex(txr->backbuf, txr->tw, codec->width, codec->height, frame->data[0], frame->linesize[0], frame->data[1], frame->linesize[1], frame->data[2], frame->linesize[2] ); // dcache_flush_range((unsigned)txr->backbuf, txr->tw * codec->height * 2); // while (!pvr_dma_ready()); // pvr_txr_load_dma(txr->backbuf, txr->addr, txr->tw * codec->height * 2, -1, NULL, 0); sq_cpy(txr->addr, txr->backbuf, txr->tw * codec->height * 2); #endif break; case PIX_FMT_UYVY422: // dcache_flush_range((unsigned)frame->data[0], txr->tw * codec->height * 2); // while (!pvr_dma_ready()); // pvr_txr_load_dma((uint8 *)(((uint32)frame->data[0] + 31) & (~31)), txr->addr, txr->tw * codec->height * 2, -1, NULL, 0); sq_cpy(txr->addr, frame->data[0], txr->tw * codec->height * 2); break; default: // dcache_flush_range((unsigned)frame->data[0], txr->tw * codec->height * 2); // while (!pvr_dma_ready()); // pvr_txr_load_dma((uint8 *)(((uint32)frame->data[0] + 31) & (~31)), txr->addr, txr->tw * codec->height * 2, -1, NULL, 0); sq_cpy(txr->addr, frame->data[0], txr->tw * codec->height * 2); break; } pvr_wait_ready(); pvr_scene_begin(); pvr_list_begin(PVR_LIST_OP_POLY); if (txr->addr) { int dispw = 640; int disph = 640 * txr->height/txr->width; RenderVideoTexture(txr, (640-dispw)/2, (480-disph)/2, dispw, disph, 0xFFFFFFFF); } pvr_list_finish(); if(txr->render_cb != NULL) { txr->render_cb((void *)txr); } pvr_scene_finish(); } #ifdef USE_DIRECT_AUDIO static struct { int rate; int channels; int bits; int bytes; int playing; int writepos; int sampsize; int leftbuf,rightbuf; } auds,*aud=&auds; //static int16 *sep_buffer[2] = {NULL, NULL}; /* sound */ static void audioinit(AVCodecContext *audio) { printf("bitrate=%d sample_rate=%d channels=%d framesize=%d bits=%d\n", audio->bit_rate,audio->sample_rate,audio->channels,audio->frame_size,audio->frame_bits ); aud->rate = audio->sample_rate; aud->channels = audio->channels; aud->bits = audio->frame_bits; if (aud->bits == 0) aud->bits = 16; aud->bytes = aud->bits / 8; //spu_dma_init(); /* if (!sep_buffer[0]) { sep_buffer[0] = memalign(32, (SND_STREAM_BUFFER_MAX/2)); sep_buffer[1] = memalign(32, (SND_STREAM_BUFFER_MAX/2)); }*/ } static void audio_end() { aud->playing = 0; aica_stop(0); aica_stop(1); /* Free global buffers */ /* if (sep_buffer[0]) { free(sep_buffer[0]); sep_buffer[0] = NULL; free(sep_buffer[1]); sep_buffer[1] = NULL; }*/ } #define G2_LOCK(OLD) \ do { \ if (!irq_inside_int()) \ OLD = irq_disable(); \ /* suspend any G2 DMA here... */ \ while((*(volatile unsigned int *)0xa05f688c) & 0x20) \ ; \ } while(0) #define G2_UNLOCK(OLD) \ do { \ /* resume any G2 DMA here... */ \ if (!irq_inside_int()) \ irq_restore(OLD); \ } while(0) #define SPU_RAM_BASE 0xa0800000 #if 0 /* Performs stereo seperation for the two channels; this routine has been optimized for the SH-4. */ static void sep_data(void *buffer, int len, int stereo) { #if 1 register int16 *bufsrc, *bufdst_left, *bufdst_right; register int cnt; cnt = len / 2; bufsrc = (int16*)buffer; bufdst_left = sep_buffer[0]; bufdst_right = sep_buffer[1]; while(cnt) { *bufdst_left++ = *bufsrc++; *bufdst_right++ = *bufsrc++; cnt -= 2; } #else register int16 *bufsrc, *bufdst; register int x, y, cnt; if (stereo) { bufsrc = (int16*)buffer; bufdst = sep_buffer[0]; x = 0; y = 0; cnt = len / 2; do { *bufdst = *bufsrc; bufdst++; bufsrc+=2; cnt--; } while (cnt > 0); bufsrc = (int16*)buffer; bufsrc++; bufdst = sep_buffer[1]; x = 1; y = 0; cnt = len / 2; do { *bufdst = *bufsrc; bufdst++; bufsrc+=2; cnt--; x+=2; y++; } while (cnt > 0); } else { memcpy(sep_buffer[0], buffer, len); memcpy(sep_buffer[1], buffer, len); } #endif } #endif #if 0 static int _spu_dma_transfer(void *from, uint32 dest, uint32 length, int block, g2_dma_callback_t callback, ptr_t cbdata) { /* Adjust destination to SPU RAM */ dest += 0x00800000; return g2_dma_transfer(from, (void *) dest, length, block, callback, cbdata, 0, SPU_DMA_MODE, 1, 1); } static uint32 dmadest, dmacnt; static void spu_dma_transfer2(ptr_t data) { spu_dma_transfer(sep_buffer[1], dmadest, dmacnt, -1, NULL, 0); } #endif /* static void spu_memload_stereo16(int leftpos, int rightpos, void *src0, size_t size) { register uint16 *src = (uint16 *)src0; register uint32 *left = (uint32 *)(leftpos + SPU_RAM_BASE); register uint32 *right = (uint32 *)(rightpos + SPU_RAM_BASE); // size = (size+7)/8; unsigned int old = 0; while(size) { g2_fifo_wait(); G2_LOCK(old); left[0] = src[0] | (src[2] << 16); right[0] = src[1] | (src[3] << 16); left[1] = src[4] | (src[6] << 16); right[1] = src[5] | (src[7] << 16); G2_UNLOCK(old); src += 8; left += 2; right += 2; size -= 16; } } */ static void spu_memload_stereo16(int leftpos, int rightpos, void *src0, size_t size) { register uint16 *src = src0; #if 0 sep_data(src, size, 1); dcache_flush_range((unsigned)sep_buffer, size); dmadest = rightpos; dmacnt = size / 2; spu_dma_transfer(sep_buffer[0], leftpos, size / 2, -1, spu_dma_transfer2, 0); //spu_dma_transfer(sep_buffer[1], rightpos, size / 2, -1, NULL, 0); #else register uint32 *left = (uint32*)(leftpos + SPU_RAM_BASE); register uint32 *right = (uint32*)(rightpos + SPU_RAM_BASE); size = (size+7)/8; unsigned lval, rval, old = 0; while(size--) { lval = *src++; rval = *src++; lval|= (*src++)<<16; rval|= (*src++)<<16; g2_fifo_wait(); G2_LOCK(old); *left++=lval; *right++=rval; G2_UNLOCK(old); /* g2_write_32(*left++,lval); g2_write_32(*right++,rval); g2_fifo_wait();*/ } #endif } /* static void spu_memload_mono16(int pos, void *src0, size_t size) { uint16 *src = (uint16 *)(((uint32)src0 + 31) & (~31)); dcache_flush_range((unsigned)src, size); spu_dma_transfer(src, pos, size, -1, NULL, 0); }*/ static void audio_write(AVCodecContext *audio, void *buf, size_t size) { if(!aud->channels) { return; } int nsamples = size/(aud->channels*aud->bytes); int writepos = 0; int curpos =0; if (!aud->playing) { aud->sampsize = (65535)/nsamples*nsamples; //printf("audio size=%d n=%d sampsize=%d\n",size,nsamples,aud->sampsize); aud->leftbuf = 0x11000;//AICA_RAM_START;// aud->rightbuf = 0x11000/*AICA_RAM_START*/ + aud->sampsize*aud->bytes; aud->writepos = 0; } else { //curpos = aica_get_pos(0); //if (writepos < curpos && curpos < writepos+nsamples) { //printf("audio:wait"); //} /* while(aud->writepos < curpos && curpos < aud->writepos + nsamples) { curpos = aica_get_pos(0); //timer_spin_sleep(50); //thd_sleep(50); //thd_pass(); thd_sleep(10); //timer_spin_sleep(2); } */ writepos = aud->writepos; curpos = aica_get_pos(0); do { curpos = aica_get_pos(0); } while(writepos < curpos && curpos < writepos + nsamples); //audio_end(); } writepos = aud->writepos * aud->bytes; if (aud->channels == 1) { spu_memload(aud->leftbuf + writepos, buf, size); //spu_memload_mono16(aud->leftbuf + writepos, buf, size); } else { spu_memload_stereo16(aud->leftbuf + writepos, aud->rightbuf + writepos, buf, size); } aud->writepos += nsamples; if (aud->writepos >= aud->sampsize) { aud->writepos = 0; } if (!aud->playing) { int mode; int vol = 255; aud->playing = 1; mode = (aud->bits == 16) ? SM_16BIT : SM_8BIT; if (aud->channels == 1) { aica_play(0,mode,aud->leftbuf,0,aud->sampsize,aud->rate,vol,128,1); } else { // printf("%d %d\n",aud->sampsize,aud->rate); aica_play(0,mode,aud->leftbuf ,0,aud->sampsize,aud->rate,vol, 0,1); aica_play(1,mode,aud->rightbuf,0,aud->sampsize,aud->rate,vol,255,1); } } } #else /* NOT USE_DIRECT_AUDIO*/ #define BUFFER_MAX_FILL 65536+16384 //static char tmpbuf[BUFFER_MAX_FILL]; // Temporary storage space for PCM data--65534 16-bit // samples should be plenty of room--that's about 0.5 seconds. //static char sndbuf[BUFFER_MAX_FILL]; static uint8 *tmpbuf, *sndbuf; static int sndptr; static int sbsize; static int last_read, snd_ct; static int waiting_for_data = 0; static snd_stream_hnd_t shnd; static kthread_t * loop_thread; static mutex_t * audio_mut = NULL; static int aud_set = 0; static int sample_rate; static int chans; void *aica_audio_callback(snd_stream_hnd_t hnd, int len, int * actual) { int wegots; mutex_lock(audio_mut); if (len >= sndptr) { wegots = sndptr; } else { wegots = len; } if (wegots <= 0) { snd_ct = 0; last_read = 0; *actual = chans * 2; /* This seems... wrong. But how should we handle such a case? */ waiting_for_data = 0; /* return NULL here? We will end up with a gap if we're not at the start of a video. We could say *actual = 1; or something? That might eliminate the lag at the beginning of a video? */ mutex_unlock(audio_mut); return NULL; } else { snd_ct = wegots; *actual = wegots; waiting_for_data = 0; } memcpy (sndbuf, tmpbuf, snd_ct); last_read = 1; sndptr -=snd_ct; memcpy(tmpbuf, tmpbuf+snd_ct, sndptr); last_read = 0; snd_ct = 0; mutex_unlock(audio_mut); return sndbuf; } /* This loops as long as the audio driver is open. Do we want to poll more frequently? */ static void *play_loop(void* yarr) { while (aud_set == 1) { if (sndptr >= sbsize) { while(waiting_for_data == 1) { snd_stream_poll(shnd); thd_pass(); if (aud_set == 0) { return NULL; } } waiting_for_data = 1; } else { thd_pass(); } } /* while (aud_set == 1) */ return NULL; } static void start_audio() { aud_set = 1; //snd_stream_prefill(shnd); snd_stream_start(shnd, sample_rate, chans-1); loop_thread = thd_create(0, play_loop, NULL); } static void stop_audio() { aud_set = 0; thd_join(loop_thread, NULL); snd_stream_stop(shnd); } int aica_audio_open(int freq, int channels, uint32_t size) { if (audio_mut == NULL) { audio_mut = mutex_create(); } sample_rate = freq; chans = channels; tmpbuf = (uint8*) malloc(BUFFER_MAX_FILL); sndbuf = (uint8*) malloc(BUFFER_MAX_FILL); memset (tmpbuf, 0, BUFFER_MAX_FILL); memset (sndbuf, 0, BUFFER_MAX_FILL); sbsize = size; sndptr = last_read = snd_ct = 0; waiting_for_data = 1; shnd = snd_stream_alloc(aica_audio_callback, sbsize); if(shnd < 0) { ds_printf("DS_ERROR: Can't alloc stream\n"); return -1; } snd_stream_prefill(shnd); snd_stream_start(shnd, freq, channels-1); return 0; } int aica_audio_write(char *buffer, int len) { /*If this stuff works, get rid of that bit left from the old output system. */ if (len== -1) { return 0; } retry: mutex_lock(audio_mut); if (sndptr + len > BUFFER_MAX_FILL) { mutex_unlock(audio_mut); if(!aud_set) { start_audio(); } thd_pass(); goto retry; } memcpy (tmpbuf + sndptr, buffer, len); sndptr += len; mutex_unlock(audio_mut); if(!aud_set && sndptr >= sbsize) { start_audio(); } return 0; //return len; } int aica_audio_close() { aud_set = sndptr = 0; thd_join(loop_thread, NULL); snd_stream_stop(shnd); snd_stream_destroy(shnd); if(tmpbuf) free(tmpbuf); if(sndbuf) free(sndbuf); return 0; } /* static int spu_ch[2]; static uint32 spu_ram_inbuf; static uint32 spu_ram_outbuf; static uint32 spu_ram_malloc; void snd_init_decoder(int buf_size) { spu_ram_inbuf = snd_mem_malloc(buf_size * 2); spu_ram_outbuf = snd_mem_malloc(64*1024); spu_ram_malloc = snd_mem_malloc(256*1024); // And channels spu_ch[0] = snd_sfx_chn_alloc(); spu_ch[1] = snd_sfx_chn_alloc(); AICA_CMDSTR_DECODER(tmp, cmd, dec); cmd->cmd = AICA_CMD_DECODER; cmd->timestamp = 0; cmd->size = AICA_CMDSTR_DECODER_SIZE; dec->cmd = AICA_DECODER_CMD_INIT; dec->base = spu_ram_malloc; dec->out = spu_ram_outbuf; snd_sh4_to_aica(tmp, cmd->size); } void snd_decode(uint8 *data, int size, uint32 codec) { AICA_CMDSTR_DECODER(tmp, cmd, dec); spu_dma_transfer((void *)(((uint32)data + 31) & (~31)), spu_ram_inbuf, size, -1, NULL, 0); cmd->cmd = AICA_CMD_DECODER; cmd->timestamp = 0; cmd->size = AICA_CMDSTR_DECODER_SIZE; dec->cmd = AICA_DECODER_CMD_DECODE; dec->codec = codec; dec->base = spu_ram_inbuf; dec->out = spu_ram_outbuf; dec->length = size; dec->chan[0] = spu_ch[0]; dec->chan[1] = spu_ch[1]; snd_sh4_to_aica(tmp, cmd->size); } void snd_cpu_clock(uint32 clock) { return; aica_cmd_t cmd; cmd.cmd = AICA_CMD_CPU_CLOCK; cmd.cmd_id = clock; cmd.timestamp = 0; snd_sh4_to_aica(cmd, 512); }*/ #endif static int codecs_inited = 0; extern AVCodec mp1_decoder; extern AVCodec mp2_decoder; extern AVCodec mp3_decoder; extern AVCodec vorbis_decoder; //extern AVCodec mpeg4_decoder; static AVCodecContext *findDecoder(AVFormatContext *format, int type, int *index) { AVCodec *codec = NULL; AVCodecContext *codec_ctx = NULL; int i, r; char errbuf[256]; int good_audio = -1; for(i = 0; i < format->nb_streams; i++) { if(format->streams[i]->codec->codec_type == type) { format->streams[i]->discard = AVDISCARD_ALL; codec_ctx = format->streams[i]->codec; if(type == AVMEDIA_TYPE_AUDIO && codec_ctx->codec_type == type && codec_ctx->codec_id == CODEC_ID_MP3) { good_audio = i; } } } codec_ctx = NULL; for(i = 0; i < format->nb_streams; i++) { if(format->streams[i]->codec->codec_type == type) { if(good_audio > -1 && good_audio != i) { continue; } codec_ctx = format->streams[i]->codec; // Find the decoder for the audio stream codec = avcodec_find_decoder(codec_ctx->codec_id); if(codec == NULL) { format->streams[i]->discard = AVDISCARD_ALL; codec_ctx = NULL; continue; } ds_printf("DS_FFMPEG: Codec %s\n", codec->long_name); // Open codec if((r = avcodec_open(codec_ctx, codec)) < 0) { av_strerror(r, errbuf, 256); ds_printf("DS_ERROR_FFMPEG: %s\n", errbuf); continue; } format->streams[i]->discard = AVDISCARD_DEFAULT; *index = i; return codec_ctx; } } return NULL; } int ffplay(const char *filename, const char *force_format) { char errbuf[256]; int r = 0; int frameFinished; AVPacket packet; int audio_buf_size = AVCODEC_MAX_AUDIO_FRAME_SIZE; int16_t *audio_buf = (int16_t *) malloc((AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2); if(!audio_buf) { ds_printf("DS_ERROR: No free memory\n"); return -1; } memset(audio_buf, 0, (AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2); AVFormatContext *pFormatCtx = NULL; AVFrame *pFrame = NULL; AVCodecContext *pVideoCodecCtx = NULL, *pAudioCodecCtx = NULL; AVInputFormat *file_iformat = NULL; video_txr_t movie_txr; int videoStream = -1, audioStream = -1; maple_device_t *cont = NULL; cont_state_t *state = NULL; int pause = 0, done = 0; char fn[NAME_MAX]; sprintf(fn, "ds:%s", filename); memset(&movie_txr, 0, sizeof(movie_txr)); if(!codecs_inited) { avcodec_register_all(); avcodec_register(&mp1_decoder); avcodec_register(&mp2_decoder); avcodec_register(&mp3_decoder); avcodec_register(&vorbis_decoder); //avcodec_register(&mpeg4_decoder); codecs_inited = 1; } if(force_format) file_iformat = av_find_input_format(force_format); else file_iformat = NULL; // Open video file ds_printf("DS_PROCESS_FFMPEG: Opening file: %s\n", filename); if((r = av_open_input_file((AVFormatContext**)(&pFormatCtx), fn, file_iformat, /*FFM_PACKET_SIZE*/0, NULL)) != 0) { av_strerror(r, errbuf, 256); ds_printf("DS_ERROR_FFMPEG: %s\n", errbuf); free(audio_buf); return -1; // Couldn't open file } // Retrieve stream information ds_printf("DS_PROCESS_FFMPEG: Retrieve stream information...\n"); if((r = av_find_stream_info(pFormatCtx)) < 0) { av_strerror(r, errbuf, 256); ds_printf("DS_ERROR_FFMPEG: %s\n", errbuf); av_close_input_file(pFormatCtx); free(audio_buf); return -1; // Couldn't find stream information } // Dump information about file onto standard error dump_format(pFormatCtx, 0, filename, 0); //thd_sleep(5000); pVideoCodecCtx = findDecoder(pFormatCtx, AVMEDIA_TYPE_VIDEO, &videoStream); pAudioCodecCtx = findDecoder(pFormatCtx, AVMEDIA_TYPE_AUDIO, &audioStream); if(pVideoCodecCtx) { //LockVideo(); ShutdownVideoThread(); SDL_DS_FreeScreenTexture(0); int format = 0; switch(pVideoCodecCtx->pix_fmt) { case PIX_FMT_YUV420P: case PIX_FMT_YUVJ420P: format = PVR_TXRFMT_YUV422; #ifdef USE_HW_YUV yuv_conv_init(); #endif break; case PIX_FMT_UYVY422: case PIX_FMT_YUVJ422P: format = PVR_TXRFMT_YUV422; break; default: format = PVR_TXRFMT_RGB565; break; } MakeVideoTexture(&movie_txr, pVideoCodecCtx->width, pVideoCodecCtx->height, format | PVR_TXRFMT_NONTWIDDLED, PVR_FILTER_BILINEAR); #ifdef USE_HW_YUV yuv_conv_setup(movie_txr.addr, PVR_YUV_MODE_MULTI, PVR_YUV_FORMAT_YUV420, movie_txr.width, movie_txr.height); pvr_dma_init(); #endif } else { ds_printf("DS_ERROR: Didn't find a video stream.\n"); } if(pAudioCodecCtx) { #ifdef USE_DIRECT_AUDIO audioinit(pAudioCodecCtx); #else sprintf(fn, "%s/firmware/aica/ds_stream.drv", getenv("PATH")); if(snd_init_fw(fn) < 0) { goto exit_free; } if(aica_audio_open(pAudioCodecCtx->sample_rate, pAudioCodecCtx->channels, 8192) < 0) { goto exit_free; } //snd_cpu_clock(0x19); //snd_init_decoder(8192); #endif } else { ds_printf("DS_ERROR: Didn't find a audio stream.\n"); } //ds_printf("FORMAT: %d\n", pVideoCodecCtx->pix_fmt); // Allocate video frame pFrame = avcodec_alloc_frame(); if(pFrame == NULL) { ds_printf("DS_ERROR: Can't alloc memory\n"); goto exit_free; } int pressed = 0, framecnt = 0; uint32 fa = 0; fa = GET_EXPORT_ADDR("ffplay_format_handler"); if(fa > 0 && fa != 0xffffffff) { EXPT_GUARD_BEGIN; void (*ff_format_func)(AVFormatContext *, AVCodecContext *, AVCodecContext *) = (void (*)(AVFormatContext *, AVCodecContext *, AVCodecContext *))fa; ff_format_func(pFormatCtx, pVideoCodecCtx, pAudioCodecCtx); EXPT_GUARD_CATCH; EXPT_GUARD_END; } fa = GET_EXPORT_ADDR("ffplay_frame_handler"); void (*ff_frame_func)(AVFrame *) = NULL; if(fa > 0 && fa != 0xffffffff) { EXPT_GUARD_BEGIN; ff_frame_func = (void (*)(AVFrame *))fa; // Test call ff_frame_func(NULL); EXPT_GUARD_CATCH; ff_frame_func = NULL; EXPT_GUARD_END; } fa = GET_EXPORT_ADDR("ffplay_render_handler"); if(fa > 0 && fa != 0xffffffff) { EXPT_GUARD_BEGIN; movie_txr.render_cb = (void (*)(void *))fa; // Test call movie_txr.render_cb(NULL); EXPT_GUARD_CATCH; movie_txr.render_cb = NULL; EXPT_GUARD_END; } while(av_read_frame(pFormatCtx, &packet) >= 0 && !done) { do { if(ff_frame_func) ff_frame_func(pFrame); cont = maple_enum_type(0, MAPLE_FUNC_CONTROLLER); framecnt++; if(cont) { state = (cont_state_t *)maple_dev_status(cont); if (!state) { break; } if (state->buttons & CONT_START || state->buttons & CONT_B) { av_free_packet(&packet); done = 1; } if (state->buttons & CONT_A) { if((framecnt - pressed) > 10) { pause = pause ? 0 : 1; if(pause) { #ifdef USE_DIRECT_AUDIO audio_end(); #else stop_audio(); #endif } else { #ifndef USE_DIRECT_AUDIO start_audio(); #endif } } pressed = framecnt; } if(state->buttons & CONT_DPAD_LEFT) { //av_seek_frame(pFormatCtx, -1, timestamp * ( AV_TIME_BASE / 1000 ), AVSEEK_FLAG_BACKWARD); } if(state->buttons & CONT_DPAD_RIGHT) { //av_seek_frame(pFormatCtx, -1, timestamp * ( AV_TIME_BASE / 1000 ), AVSEEK_FLAG_BACKWARD); } } if(pause) thd_sleep(100); } while(pause); //printf("Packet: size: %d data: %02x%02x%02x pst: %d\n", packet.size, packet.data[0], packet.data[1], packet.data[2], pFrame->pts); // Is this a packet from the video stream? if(packet.stream_index == videoStream) { //printf("video\n"); // Decode video frame if((r = avcodec_decode_video2(pVideoCodecCtx, pFrame, &frameFinished, &packet)) < 0) { //av_strerror(r, errbuf, 256); //printf("DS_ERROR_FFMPEG: %s\n", errbuf); } else { // Did we get a video frame? if(frameFinished && !pVideoCodecCtx->hurry_up) { RenderVideo(&movie_txr, pFrame, pVideoCodecCtx); } } } else if(packet.stream_index == audioStream) { //printf("audio\n"); //snd_decode((uint8*)audio_buf, audio_buf_size, AICA_CODEC_MP3); audio_buf_size = AVCODEC_MAX_AUDIO_FRAME_SIZE; if((r = avcodec_decode_audio3(pAudioCodecCtx, audio_buf, &audio_buf_size, &packet)) < 0) { //av_strerror(r, errbuf, 256); //printf("DS_ERROR_FFMPEG: %s\n", errbuf); //continue; } else { if(audio_buf_size > 0 && !pAudioCodecCtx->hurry_up) { #ifdef USE_DIRECT_AUDIO audio_write(pAudioCodecCtx, audio_buf, audio_buf_size); #else aica_audio_write((char*)audio_buf, audio_buf_size); #endif } } } // Free the packet that was allocated by av_read_frame av_free_packet(&packet); } goto exit_free; exit_free: if(pFrame) av_free(pFrame); if(pFormatCtx) av_close_input_file(pFormatCtx); if(audioStream > -1) { if(pAudioCodecCtx) avcodec_close(pAudioCodecCtx); #ifdef USE_DIRECT_AUDIO audio_end(); #else aica_audio_close(); sprintf(fn, "%s/firmware/aica/kos_stream.drv", getenv("PATH")); snd_init_fw(fn); #endif } if(audio_buf) { free(audio_buf); } if(videoStream > -1) { if(pVideoCodecCtx) avcodec_close(pVideoCodecCtx); FreeVideoTexture(&movie_txr); SDL_DS_AllocScreenTexture(GetScreen()); InitVideoThread(); //UnlockVideo(); } ProcessVideoEventsUpdate(NULL); return 0; } <file_sep>/sdk/bin/src/wav2adpcm/wav2adpcm.c /* aica adpcm <-> wave converter; (c) 2002 BERO <<EMAIL>> under GPL or notify me aica adpcm seems same as YMZ280B adpcm adpcm->pcm algorithm can found MAME/src/sound/ymz280b.c by <NAME> this code is for little endian machine Modified by <NAME> to read/write ADPCM WAV files, and to handle stereo (though the stereo is very likely KOS specific since we make no effort to interleave it). Please see README.GPL in the KOS docs dir for more info on the GPL license. */ #include <stdio.h> #include <stdlib.h> #include <string.h> static int diff_lookup[16] = { 1, 3, 5, 7, 9, 11, 13, 15, -1, -3, -5, -7, -9, -11, -13, -15, }; static int index_scale[16] = { 0x0e6, 0x0e6, 0x0e6, 0x0e6, 0x133, 0x199, 0x200, 0x266, 0x0e6, 0x0e6, 0x0e6, 0x0e6, 0x133, 0x199, 0x200, 0x266 //same value for speedup }; static inline int limit(int val, int min, int max) { if(val < min) return min; else if(val > max) return max; else return val; } void pcm2adpcm(unsigned char *dst, const short *src, size_t length) { int signal, step; signal = 0; step = 0x7f; // length/=4; length = (length + 3) / 4; do { int data, val, diff; /* hign nibble */ diff = *src++ - signal; diff = (diff * 8) / step; val = abs(diff) / 2; if(val > 7) val = 7; if(diff < 0) val += 8; signal += (step * diff_lookup[val]) / 8; signal = limit(signal, -32768, 32767); step = (step * index_scale[val]) >> 8; step = limit(step, 0x7f, 0x6000); data = val; /* low nibble */ diff = *src++ - signal; diff = (diff * 8) / step; val = (abs(diff)) / 2; if(val > 7) val = 7; if(diff < 0) val += 8; signal += (step * diff_lookup[val]) / 8; signal = limit(signal, -32768, 32767); step = (step * index_scale[val]) >> 8; step = limit(step, 0x7f, 0x6000); data |= val << 4; *dst++ = data; } while(--length); } void adpcm2pcm(short *dst, const unsigned char *src, size_t length) { int signal, step; signal = 0; step = 0x7f; do { int data, val; data = *src++; /* low nibble */ val = data & 15; signal += (step * diff_lookup[val]) / 8; signal = limit(signal, -32768, 32767); step = (step * index_scale[val & 7]) >> 8; step = limit(step, 0x7f, 0x6000); *dst++ = signal; /* high nibble */ val = (data >> 4) & 15; signal += (step * diff_lookup[val]) / 8; signal = limit(signal, -32768, 32767); step = (step * index_scale[val & 7]) >> 8; step = limit(step, 0x7f, 0x6000); *dst++ = signal; } while(--length); } void deinterleave(void *buffer, size_t size) { short * buf; short * buf1, * buf2; int i; buf = (short *)buffer; buf1 = malloc(size / 2); buf2 = malloc(size / 2); for(i = 0; i < size / 4; i++) { buf1[i] = buf[i * 2 + 0]; buf2[i] = buf[i * 2 + 1]; } memcpy(buf, buf1, size / 2); memcpy(buf + size / 4, buf2, size / 2); free(buf1); free(buf2); } void interleave(void *buffer, size_t size) { short * buf; short * buf1, * buf2; int i; buf = malloc(size); buf1 = (short *)buffer; buf2 = buf1 + size / 4; for(i = 0; i < size / 4; i++) { buf[i * 2 + 0] = buf1[i]; buf[i * 2 + 1] = buf2[i]; } memcpy(buffer, buf, size); free(buf); } struct wavhdr_t { char hdr1[4]; long totalsize; char hdr2[8]; long hdrsize; short format; short channels; long freq; long byte_per_sec; short blocksize; short bits; char hdr3[4]; long datasize; }; int wav2adpcm(const char *infile, const char *outfile) { struct wavhdr_t wavhdr; FILE *in, *out; size_t pcmsize, adpcmsize; short *pcmbuf; unsigned char *adpcmbuf; in = fopen(infile, "rb"); if(in == NULL) { printf("can't open %s\n", infile); return -1; } fread(&wavhdr, 1, sizeof(wavhdr), in); if(memcmp(wavhdr.hdr1, "RIFF", 4) || memcmp(wavhdr.hdr2, "WAVEfmt ", 8) || memcmp(wavhdr.hdr3, "data", 4) || wavhdr.hdrsize != 0x10 || wavhdr.format != 1 || (wavhdr.channels != 1 && wavhdr.channels != 2) || wavhdr.bits != 16) { printf("unsupport format\n"); fclose(in); return -1; } pcmsize = wavhdr.datasize; adpcmsize = pcmsize / 4; pcmbuf = malloc(pcmsize); adpcmbuf = malloc(adpcmsize); fread(pcmbuf, 1, pcmsize, in); fclose(in); if(wavhdr.channels == 1) { pcm2adpcm(adpcmbuf, pcmbuf, pcmsize); } else { /* For stereo we just deinterleave the input and store the left and right channel of the ADPCM data separately. */ deinterleave(pcmbuf, pcmsize); pcm2adpcm(adpcmbuf, pcmbuf, pcmsize / 2); pcm2adpcm(adpcmbuf + adpcmsize / 2, pcmbuf + pcmsize / 4, pcmsize / 2); } out = fopen(outfile, "wb"); wavhdr.datasize = adpcmsize; wavhdr.format = 20; /* ITU G.723 ADPCM (Yamaha) */ wavhdr.bits = 4; wavhdr.totalsize = wavhdr.datasize + sizeof(wavhdr) - 8; fwrite(&wavhdr, 1, sizeof(wavhdr), out); fwrite(adpcmbuf, 1, adpcmsize, out); fclose(out); return 0; } int adpcm2wav(const char *infile, const char *outfile) { struct wavhdr_t wavhdr; FILE *in, *out; size_t pcmsize, adpcmsize; short *pcmbuf; unsigned char *adpcmbuf; in = fopen(infile, "rb"); if(in == NULL) { printf("can't open %s\n", infile); return -1; } fread(&wavhdr, 1, sizeof(wavhdr), in); if(memcmp(wavhdr.hdr1, "RIFF", 4) || memcmp(wavhdr.hdr2, "WAVEfmt ", 8) || memcmp(wavhdr.hdr3, "data", 4) || wavhdr.hdrsize != 0x10 || wavhdr.format != 20 || (wavhdr.channels != 1 && wavhdr.channels != 2) || wavhdr.bits != 4) { printf("unsupport format\n"); fclose(in); return -1; } adpcmsize = wavhdr.datasize; pcmsize = adpcmsize * 4; adpcmbuf = malloc(adpcmsize); pcmbuf = malloc(pcmsize); fread(adpcmbuf, 1, adpcmsize, in); fclose(in); if(wavhdr.channels == 1) { adpcm2pcm(pcmbuf, adpcmbuf, adpcmsize); } else { adpcm2pcm(pcmbuf, adpcmbuf, adpcmsize / 2); adpcm2pcm(pcmbuf + pcmsize / 4, adpcmbuf + adpcmsize / 2, adpcmsize / 2); interleave(pcmbuf, pcmsize); } wavhdr.blocksize = wavhdr.channels * sizeof(short); wavhdr.byte_per_sec = wavhdr.freq * wavhdr.blocksize; wavhdr.datasize = pcmsize; wavhdr.totalsize = wavhdr.datasize + sizeof(wavhdr) - 8; wavhdr.format = 1; wavhdr.bits = 16; out = fopen(outfile, "wb"); fwrite(&wavhdr, 1, sizeof(wavhdr), out); fwrite(pcmbuf, 1, pcmsize, out); fclose(out); return 0; } void usage() { printf("wav2adpcm: 16bit mono wav to aica adpcm and vice-versa (c)2002 BERO\n" " wav2adpcm -t <infile.wav> <outfile.wav> (To adpcm)\n" " wav2adpcm -f <infile.wav> <outfile.wav> (From adpcm)\n" ); } int main(int argc, char **argv) { if(argc == 4) { if(!strcmp(argv[1], "-t")) { return wav2adpcm(argv[2], argv[3]); } else if(!strcmp(argv[1], "-f")) { return adpcm2wav(argv[2], argv[3]); } else { usage(); return -1; } } else { usage(); return -1; } } <file_sep>/modules/zip/Makefile # # zip module for DreamShell # Copyright (C) 2009-2020 SWAT # http://www.dc-swat.ru # TARGET_NAME = zip OBJS = module.o minizip.o miniunz.o \ ./minizip/zip.o ./minizip/unzip.o \ ./minizip/ioapi.o DBG_LIBS = -lds -lbzip2 EXPORTS_FILE = exports.txt VER_MAJOR = 1 VER_MINOR = 0 VER_MICRO = 30 all: rm-elf include ../../sdk/Makefile.loadable KOS_CFLAGS += -I./minizip -DHAVE_BZIP2=1 -DIOAPI_NO_64=1 rm-elf: -rm -f $(TARGET) -rm -f $(TARGET_LIB) install: $(TARGET) $(TARGET_LIB) -rm $(DS_BUILD)/modules/$(TARGET) -rm $(DS_SDK)/lib/$(TARGET_LIB) cp $(TARGET) $(DS_BUILD)/modules/$(TARGET) cp $(TARGET_LIB) $(DS_SDK)/lib/$(TARGET_LIB) <file_sep>/include/video.h /** * \file video.h * \brief DreamShell video rendering * \date 2004-2014 * \author SWAT www.dc-swat.ru */ #ifndef _DS_VIDEO_H #define _DS_VIDEO_H #include <kos.h> #include "SDL/SDL.h" #include "SDL/SDL_ttf.h" #include "SDL/SDL_image.h" #include "SDL/SDL_dreamcast.h" #include "SDL/SDL_gfxPrimitives.h" #include "SDL/SDL_gfxBlitFunc.h" #include "SDL/SDL_rotozoom.h" #include "SDL/SDL_console.h" #include "SDL/DT_drawtext.h" #include "plx/font.h" #include "plx/sprite.h" #include "plx/list.h" #include "plx/dr.h" #include "plx/context.h" #include "plx/texture.h" #include "gui.h" #include "list.h" // Pixel packing macro #define PACK_PIXEL(r, g, b) ( ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3) ) SDL_Surface *GetScreen(); void SetScreen(SDL_Surface *new_screen); int GetScreenWidth(); int GetScreenHeight(); /* Always RGB565 */ int GetVideoMode(); void SetVideoMode(int mode); void SDL_DS_SetWindow(int width, int height); void SetScreenMode(int w, int h, float x, float y, float z); void SDL_DS_AllocScreenTexture(SDL_Surface *screen); void SDL_DS_FreeScreenTexture(int reset_pvr_memory); pvr_ptr_t GetScreenTexture(); void SetScreenTexture(pvr_ptr_t *txr); void SetScreenOpacity(float opacity); float GetScreenOpacity(); void SetScreenFilter(int filter); void SetScreenVertex(float u1, float v1, float u2, float v2); void ScreenRotate(float x, float y, float z); void ScreenTranslate(float x, float y, float z); void ScreenFadeIn(); void ScreenFadeOut(); void ScreenFadeStop(); void DisableScreen(); void EnableScreen(); int ScreenIsEnabled(); void ScreenChanged(); int ScreenUpdated(); void ScreenWaitUpdate(); void LockVideo(); void UnlockVideo(); int VideoIsLocked(); int VideoMustLock(); void InitVideoHardware(); int InitVideo(int w, int h, int bpp); void ShutdownVideo(); void InitVideoThread(); void ShutdownVideoThread(); void ShowLogo(); void HideLogo(); /* Load PVR to a KOS Platform Independent Image */ int pvr_to_img(const char *filename, kos_img_t *rv); /* Load zlib compressed KMG to a KOS Platform Independent Image */ int gzip_kmg_to_img(const char * filename, kos_img_t *rv); /* Utility function to fill out the initial poly contexts */ void plx_fill_contexts(plx_texture_t * txr); static inline void plx_vert_ifpm3(int flags, float x, float y, float z, uint32 color, float u, float v) { plx_mat_tfip_3d(x, y, z); plx_vert_ifp(flags, x, y, z, color, u, v); } #endif <file_sep>/lib/SDL_Console/src/SDL_console.c /* SDL_console: An easy to use drop-down console based on the SDL library Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WHITOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library Generla Public License along with this library; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA <NAME> <EMAIL> */ /* SDL_console.c * Written By: <NAME> <<EMAIL>> * Code Cleanup and heavily extended by: Clemens Wacha <<EMAIL>> * Modified by SWAT */ #include "SDL_console.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include "DT_drawtext.h" #include "internal.h" #ifdef HAVE_SDLIMAGE #include "SDL_image.h" #endif #include "ds.h" /* This contains a pointer to the "topmost" console. The console that * is currently taking keyboard input. */ static ConsoleInformation *Topmost; /* Takes keys from the keyboard and inputs them to the console If the event was not handled (i.e. WM events or unknown ctrl-shift sequences) the function returns the event for further processing. */ SDL_Event* CON_Events(SDL_Event *event) { if(Topmost == NULL) return event; if(!CON_isVisible(Topmost)) return event; if(event->type == SDL_KEYDOWN) { if(event->key.keysym.mod & KMOD_CTRL) { /* CTRL pressed */ switch(event->key.keysym.sym) { case SDLK_a: Cursor_Home(Topmost); break; case SDLK_e: Cursor_End(Topmost); break; case SDLK_c: Clear_Command(Topmost); break; case SDLK_l: Clear_History(Topmost); CON_UpdateConsole(Topmost); break; default: return event; } } else if(event->key.keysym.mod & KMOD_ALT) { /* the console does not handle ALT combinations! */ return event; } else { /* first of all, check if the console hide key was pressed */ if(event->key.keysym.sym == Topmost->HideKey) { CON_Hide(Topmost); return NULL; } switch (event->key.keysym.sym) { case SDLK_HOME: if(event->key.keysym.mod & KMOD_SHIFT) { Topmost->ConsoleScrollBack = Topmost->LineBuffer-1; CON_UpdateConsole(Topmost); } else { Cursor_Home(Topmost); } break; case SDLK_END: if(event->key.keysym.mod & KMOD_SHIFT) { Topmost->ConsoleScrollBack = 0; CON_UpdateConsole(Topmost); } else { Cursor_End(Topmost); } break; case SDLK_PAGEUP: Topmost->ConsoleScrollBack += CON_LINE_SCROLL; if(Topmost->ConsoleScrollBack > Topmost->LineBuffer-1) Topmost->ConsoleScrollBack = Topmost->LineBuffer-1; CON_UpdateConsole(Topmost); break; case SDLK_PAGEDOWN: Topmost->ConsoleScrollBack -= CON_LINE_SCROLL; if(Topmost->ConsoleScrollBack < 0) Topmost->ConsoleScrollBack = 0; CON_UpdateConsole(Topmost); break; case SDLK_UP: Command_Up(Topmost); break; case SDLK_DOWN: Command_Down(Topmost); break; case SDLK_LEFT: Cursor_Left(Topmost); break; case SDLK_RIGHT: Cursor_Right(Topmost); break; case SDLK_BACKSPACE: Cursor_BSpace(Topmost); break; case SDLK_DELETE: Cursor_Del(Topmost); break; case SDLK_INSERT: Topmost->InsMode = 1-Topmost->InsMode; break; case SDLK_TAB: CON_TabCompletion(Topmost); break; case SDLK_RETURN: if(strlen(Topmost->Command) > 0) { CON_NewLineCommand(Topmost); /* copy the input into the past commands strings */ strcpy(Topmost->CommandLines[0], Topmost->Command); /* display the command including the prompt */ CON_Out(Topmost, "%s%s", Topmost->Prompt, Topmost->Command); CON_Execute(Topmost, Topmost->Command); /* printf("Command: %s\n", Topmost->Command); */ Clear_Command(Topmost); Topmost->CommandScrollBack = -1; } break; case SDLK_ESCAPE: /* deactivate Console */ CON_Hide(Topmost); return NULL; default: if(Topmost->InsMode) Cursor_Add(Topmost, event); else { Cursor_Add(Topmost, event); //Cursor_Del(Topmost); } } } Topmost->WasUnicode = 1; return NULL; } return event; } #if 0 /* CON_AlphaGL() -- sets the alpha channel of an SDL_Surface to the * specified value. Preconditions: the surface in question is RGBA. * 0 <= a <= 255, where 0 is transparent and 255 is opaque. */ void CON_AlphaGL(SDL_Surface *s, int alpha) { Uint8 val; int x, y, w, h; Uint32 pixel; Uint8 r, g, b, a; SDL_PixelFormat *format; //static char errorPrinted = 0; /* debugging assertions -- these slow you down, but hey, crashing sucks */ if(!s) { PRINT_ERROR("NULL Surface passed to CON_AlphaGL\n"); return; } /* clamp alpha value to 0...255 */ if(alpha < SDL_ALPHA_TRANSPARENT) val = SDL_ALPHA_TRANSPARENT; else if(alpha > SDL_ALPHA_OPAQUE) val = SDL_ALPHA_OPAQUE; else val = alpha; /* loop over alpha channels of each pixel, setting them appropriately. */ w = s->w; h = s->h; format = s->format; switch (format->BytesPerPixel) { #if 0 case 2: /* 16-bit surfaces don't seem to support alpha channels. */ if(!errorPrinted) { errorPrinted = 1; PRINT_ERROR("16-bit SDL surfaces do not support alpha-blending under OpenGL.\n"); } break; #endif case 4: { /* we can do this very quickly in 32-bit mode. 24-bit is more * difficult. And since 24-bit mode is reall the same as 32-bit, * so it usually ends up taking this route too. Win! Unroll loop * and use pointer arithmetic for extra speed. */ int numpixels = h * (w << 2); Uint8 *pix = (Uint8 *) (s->pixels); Uint8 *last = pix + numpixels; Uint8 *pixel; if((numpixels & 0x7) == 0) for(pixel = pix + 3; pixel < last; pixel += 32) *pixel = *(pixel + 4) = *(pixel + 8) = *(pixel + 12) = *(pixel + 16) = *(pixel + 20) = *(pixel + 24) = *(pixel + 28) = val; else for(pixel = pix + 3; pixel < last; pixel += 4) *pixel = val; break; } default: /* we have no choice but to do this slowly. <sigh> */ for(y = 0; y < h; ++y) for(x = 0; x < w; ++x) { // char print = 0; /* Lock the surface for direct access to the pixels */ if(SDL_MUSTLOCK(s) && SDL_LockSurface(s) < 0) { PRINT_ERROR("Can't lock surface: "); fprintf(stderr, "%s\n", SDL_GetError()); return; } pixel = DT_GetPixel(s, x, y); // if(x == 0 && y == 0) // print = 1; SDL_GetRGBA(pixel, format, &r, &g, &b, &a); pixel = SDL_MapRGBA(format, r, g, b, val); SDL_GetRGBA(pixel, format, &r, &g, &b, &a); DT_PutPixel(s, x, y, pixel); /* unlock surface again */ if(SDL_MUSTLOCK(s)) SDL_UnlockSurface(s); } break; } } #endif /* Updates the console, draws the background and the history lines. Does not draw the Commandline */ void CON_UpdateConsole(ConsoleInformation *console) { int loop; int loop2; int Screenlines; SDL_Rect DestRect; // BitFont *CurrentFont = DT_FontPointer(console->FontNumber); if(!console) return; /* Due to the Blits, the update is not very fast: So only update if it's worth it */ if(!CON_isVisible(console)) return; Screenlines = (console->ConsoleSurface->h / console->FontHeight) - 2; console->WasUnicode = 1; SDL_FillRect(console->ConsoleSurface, NULL, SDL_MapRGBA(console->ConsoleSurface->format, 0, 0, 0, console->ConsoleAlpha)); // if(console->OutputScreen->flags & SDL_OPENGLBLIT) // SDL_SetAlpha(console->ConsoleSurface, 0, SDL_ALPHA_OPAQUE); /* draw the background image if there is one */ if(console->BackgroundImage) { DestRect.x = console->BackX; DestRect.y = console->BackY; DestRect.w = console->BackgroundImage->w; DestRect.h = console->BackgroundImage->h; SDL_BlitSurface(console->BackgroundImage, NULL, console->ConsoleSurface, &DestRect); } /* Draw the text from the back buffers, calculate in the scrollback from the user * this is a normal SDL software-mode blit, so we need to temporarily set the ColorKey * for the font, and then clear it when we're done. */ // if((console->OutputScreen->flags & SDL_OPENGLBLIT) && (console->OutputScreen->format->BytesPerPixel > 2)) { // Uint32 *pix = (Uint32 *) (CurrentFont->FontSurface->pixels); // SDL_SetColorKey(CurrentFont->FontSurface, SDL_SRCCOLORKEY, *pix); // } /* now draw text from last but second line to top loop: for every line in the history loop2: draws the scroll indicators to the line above the Commandline */ for(loop = 0; loop < Screenlines-1 && loop < console->LineBuffer - console->ConsoleScrollBack; loop++) { if(console->ConsoleScrollBack != 0 && loop == 0) for(loop2 = 0; loop2 < (console->VChars / 5) + 1; loop2++) DT_DrawText(CON_SCROLL_INDICATOR, console->ConsoleSurface, console->FontNumber, CON_CHAR_BORDER + (loop2*5*console->FontWidth), (Screenlines - loop - 1) * console->FontHeight); else DT_DrawText(console->ConsoleLines[console->ConsoleScrollBack + loop], console->ConsoleSurface, console->FontNumber, CON_CHAR_BORDER, (Screenlines - loop - 1) * console->FontHeight); } // if(console->OutputScreen->flags & SDL_OPENGLBLIT) // SDL_SetColorKey(CurrentFont->FontSurface, 0, 0); } void CON_UpdateOffset(ConsoleInformation* console) { if(!console) return; switch(console->Visible) { case CON_CLOSING: console->RaiseOffset -= CON_OPENCLOSE_SPEED; console->WasUnicode = 1; if(console->RaiseOffset <= 0) { console->RaiseOffset = 0; console->Visible = CON_CLOSED; console->WasUnicode = 0; } break; case CON_OPENING: console->RaiseOffset += CON_OPENCLOSE_SPEED; console->WasUnicode = 1; if(console->RaiseOffset >= console->ConsoleSurface->h) { console->RaiseOffset = console->ConsoleSurface->h; console->Visible = CON_OPEN; } break; case CON_OPEN: case CON_CLOSED: break; } } /* Draws the console buffer to the screen if the console is "visible" */ void CON_DrawConsole(ConsoleInformation *console) { SDL_Rect DestRect; SDL_Rect SrcRect; if(!console) return; /* only draw if console is visible: here this means, that the console is not CON_CLOSED */ if(console->Visible == CON_CLOSED) return; /* Update the scrolling offset */ CON_UpdateOffset(console); if(!console->WasUnicode) return; // dbglog(DBG_INFO, "%s\n", __func__); /* Update the command line since it has a blinking cursor */ DrawCommandLine(); /* before drawing, make sure the alpha channel of the console surface is set * properly. (sigh) I wish we didn't have to do this every frame... */ // if(console->OutputScreen->flags & SDL_OPENGLBLIT) // CON_AlphaGL(console->ConsoleSurface, console->ConsoleAlpha); SrcRect.x = 0; SrcRect.y = console->ConsoleSurface->h - console->RaiseOffset; SrcRect.w = console->ConsoleSurface->w; SrcRect.h = console->RaiseOffset; /* Setup the rect the console is being blitted into based on the output screen */ DestRect.x = console->DispX; DestRect.y = console->DispY; DestRect.w = console->ConsoleSurface->w; DestRect.h = console->ConsoleSurface->h; if(console->Visible == CON_CLOSING) { SDL_FillRect(console->OutputScreen, NULL, SDL_MapRGBA(console->ConsoleSurface->format, 0, 0, 0, console->ConsoleAlpha)); } SDL_BlitSurface(console->ConsoleSurface, &SrcRect, console->OutputScreen, &DestRect); console->WasUnicode = 0; ScreenChanged(); // if(console->OutputScreen->flags & SDL_OPENGLBLIT) // SDL_UpdateRects(console->OutputScreen, 1, &DestRect); } /* Initializes the console */ ConsoleInformation *CON_Init(const char *FontName, SDL_Surface *DisplayScreen, int lines, SDL_Rect rect) { int loop; SDL_Surface *Temp; ConsoleInformation *newinfo; /* Create a new console struct and init it. */ if((newinfo = (ConsoleInformation *) malloc(sizeof(ConsoleInformation))) == NULL) { PRINT_ERROR("Could not allocate the space for a new console info struct.\n"); return NULL; } newinfo->Visible = CON_CLOSED; newinfo->WasUnicode = 0; newinfo->RaiseOffset = 0; newinfo->ConsoleLines = NULL; newinfo->CommandLines = NULL; newinfo->TotalConsoleLines = 0; newinfo->ConsoleScrollBack = 0; newinfo->TotalCommands = 0; newinfo->BackgroundImage = NULL; newinfo->ConsoleAlpha = SDL_ALPHA_OPAQUE; newinfo->Offset = 0; newinfo->InsMode = 1; newinfo->CursorPos = 0; newinfo->CommandScrollBack = 0; newinfo->OutputScreen = DisplayScreen; newinfo->Prompt = CON_DEFAULT_PROMPT; newinfo->HideKey = CON_DEFAULT_HIDEKEY; CON_SetExecuteFunction(newinfo, Default_CmdFunction); CON_SetTabCompletion(newinfo, Default_TabFunction); /* Load the consoles font */ if(-1 == (newinfo->FontNumber = DT_LoadFont(FontName, TRANS_FONT))) { ds_printf("DS_ERROR: Could not load the font \"%s\" for the console!\n", FontName); return NULL; } newinfo->FontHeight = DT_FontHeight(newinfo->FontNumber); newinfo->FontWidth = DT_FontWidth(newinfo->FontNumber); /* make sure that the size of the console is valid */ if(rect.w > newinfo->OutputScreen->w || rect.w < newinfo->FontWidth * 32) rect.w = newinfo->OutputScreen->w; if(rect.h > newinfo->OutputScreen->h || rect.h < newinfo->FontHeight) rect.h = newinfo->OutputScreen->h; if(rect.x < 0 || rect.x > newinfo->OutputScreen->w - rect.w) newinfo->DispX = 0; else newinfo->DispX = rect.x; if(rect.y < 0 || rect.y > newinfo->OutputScreen->h - rect.h) newinfo->DispY = 0; else newinfo->DispY = rect.y; /* load the console surface */ Temp = SDL_CreateRGBSurface(SDL_HWSURFACE, rect.w, rect.h, newinfo->OutputScreen->format->BitsPerPixel, 0, 0, 0, 0); if(Temp == NULL) { ds_printf("DS_ERROR: Couldn't create the ConsoleSurface\n"); return NULL; } newinfo->ConsoleSurface = SDL_DisplayFormat(Temp); SDL_FreeSurface(Temp); SDL_FillRect(newinfo->ConsoleSurface, NULL, SDL_MapRGBA(newinfo->ConsoleSurface->format, 0, 0, 0, newinfo->ConsoleAlpha)); /* Load the dirty rectangle for user input */ Temp = SDL_CreateRGBSurface(SDL_HWSURFACE, rect.w, newinfo->FontHeight, newinfo->OutputScreen->format->BitsPerPixel, 0, 0, 0, SDL_ALPHA_OPAQUE); if(Temp == NULL) { ds_printf("DS_ERROR: Can't create the InputBackground\n"); return NULL; } newinfo->InputBackground = SDL_DisplayFormat(Temp); SDL_FreeSurface(Temp); SDL_FillRect(newinfo->InputBackground, NULL, SDL_MapRGBA(newinfo->ConsoleSurface->format, 0, 0, 0, SDL_ALPHA_OPAQUE)); /* calculate the number of visible characters in the command line */ newinfo->VChars = (rect.w - CON_CHAR_BORDER) / newinfo->FontWidth; if(newinfo->VChars > CON_CHARS_PER_LINE) newinfo->VChars = CON_CHARS_PER_LINE; /* deprecated! Memory errors disabled by C.Wacha :-) We would like to have a minumum # of lines to guarentee we don't create a memory error */ /* if(rect.h / newinfo->FontHeight > lines) newinfo->LineBuffer = rect.h / newinfo->FontHeight; else newinfo->LineBuffer = lines; */ newinfo->LineBuffer = lines; newinfo->ConsoleLines = (char **)malloc(sizeof(char *) * newinfo->LineBuffer); newinfo->CommandLines = (char **)malloc(sizeof(char *) * newinfo->LineBuffer); for(loop = 0; loop <= newinfo->LineBuffer - 1; loop++) { newinfo->ConsoleLines[loop] = (char *)calloc(CON_CHARS_PER_LINE+1, sizeof(char)); newinfo->CommandLines[loop] = (char *)calloc(CON_CHARS_PER_LINE+1, sizeof(char)); } memset_sh4(newinfo->Command, 0, CON_CHARS_PER_LINE+1); memset_sh4(newinfo->LCommand, 0, CON_CHARS_PER_LINE+1); memset_sh4(newinfo->RCommand, 0, CON_CHARS_PER_LINE+1); memset_sh4(newinfo->VCommand, 0, CON_CHARS_PER_LINE+1); CON_Out(newinfo, "Console initialised."); CON_NewLineConsole(newinfo); return newinfo; } /* Makes the console visible */ void CON_Show(ConsoleInformation *console) { if(console) { console->Visible = CON_OPENING; // FIXME: Flag WasUnicode used for updating //console->WasUnicode = SDL_EnableUNICODE(-1); //SDL_EnableUNICODE(1); } } /* Hides the console (make it invisible) */ void CON_Hide(ConsoleInformation *console) { if(console) { console->Visible = CON_CLOSING; //SDL_EnableUNICODE(console->WasUnicode); } } /* tells wether the console is visible or not */ int CON_isVisible(ConsoleInformation *console) { if(!console) return CON_CLOSED; return((console->Visible == CON_OPEN) || (console->Visible == CON_OPENING) || (console->Visible == CON_CLOSING)); } /* Frees all the memory loaded by the console */ void CON_Destroy(ConsoleInformation *console) { DT_DestroyDrawText(); CON_Free(console); } /* Frees all the memory loaded by the console */ void CON_Free(ConsoleInformation *console) { int i; if(!console) return; for(i = 0; i <= console->LineBuffer - 1; i++) { free(console->ConsoleLines[i]); free(console->CommandLines[i]); } free(console->ConsoleLines); free(console->CommandLines); console->ConsoleLines = NULL; console->CommandLines = NULL; free(console); } /* Increments the console lines */ void CON_NewLineConsole(ConsoleInformation *console) { int loop; char* temp; if(!console) return; temp = console->ConsoleLines[console->LineBuffer - 1]; for(loop = console->LineBuffer - 1; loop > 0; loop--) console->ConsoleLines[loop] = console->ConsoleLines[loop - 1]; console->ConsoleLines[0] = temp; memset_sh4(console->ConsoleLines[0], 0, CON_CHARS_PER_LINE+1); if(console->TotalConsoleLines < console->LineBuffer - 1) console->TotalConsoleLines++; /* Now adjust the ConsoleScrollBack dont scroll if not at bottom */ if(console->ConsoleScrollBack != 0) console->ConsoleScrollBack++; /* boundaries */ if(console->ConsoleScrollBack > console->LineBuffer-1) console->ConsoleScrollBack = console->LineBuffer-1; } /* Increments the command lines */ void CON_NewLineCommand(ConsoleInformation *console) { int loop; char *temp; if(!console) return; temp = console->CommandLines[console->LineBuffer - 1]; for(loop = console->LineBuffer - 1; loop > 0; loop--) console->CommandLines[loop] = console->CommandLines[loop - 1]; console->CommandLines[0] = temp; memset_sh4(console->CommandLines[0], 0, CON_CHARS_PER_LINE+1); if(console->TotalCommands < console->LineBuffer - 1) console->TotalCommands++; } /* Draws the command line the user is typing in to the screen */ /* completely rewritten by C.Wacha */ void DrawCommandLine() { SDL_Rect rect; int x; int commandbuffer; // BitFont* CurrentFont; // static Uint32 NextBlinkTime = 0; /* time the consoles cursor blinks again */ // static int LastCursorPos = 0; /* Last Cursor Position */ // static int Blink = 0; /* Is the cursor currently blinking */ // static int OldBlink = 1; if(!Topmost) return; /* at last add the cursor check if the blink period is over */ // if(SDL_GetTicks() > NextBlinkTime) { // NextBlinkTime = SDL_GetTicks() + CON_BLINK_RATE; // Blink = 1 - Blink; // } // // /* check if cursor has moved - if yes display cursor anyway */ // if(Topmost->CursorPos != LastCursorPos) { // LastCursorPos = Topmost->CursorPos; // NextBlinkTime = SDL_GetTicks() + CON_BLINK_RATE; // Blink = 1; // } // // if(Blink == OldBlink) // return; // else { // OldBlink = Blink; // Topmost->WasUnicode = 1; // } commandbuffer = Topmost->VChars - strlen(Topmost->Prompt) - 1; /* -1 to make cursor visible */ // CurrentFont = DT_FontPointer(Topmost->FontNumber); /* calculate display offset from current cursor position */ if(Topmost->Offset < Topmost->CursorPos - commandbuffer) Topmost->Offset = Topmost->CursorPos - commandbuffer; if(Topmost->Offset > Topmost->CursorPos) Topmost->Offset = Topmost->CursorPos; /* first add prompt to visible part */ strcpy(Topmost->VCommand, Topmost->Prompt); /* then add the visible part of the command */ strncat(Topmost->VCommand, &Topmost->Command[Topmost->Offset], strlen(&Topmost->Command[Topmost->Offset])); /* now display the result */ /* once again we're drawing text, so in OpenGL context we need to temporarily set up software-mode transparency. */ // if(Topmost->OutputScreen->flags & SDL_OPENGLBLIT) { // Uint32 *pix = (Uint32 *) (CurrentFont->FontSurface->pixels); // SDL_SetColorKey(CurrentFont->FontSurface, SDL_SRCCOLORKEY, *pix); // } /* first of all restore InputBackground */ rect.x = 0; rect.y = Topmost->ConsoleSurface->h - (Topmost->FontHeight*2); rect.w = Topmost->InputBackground->w; rect.h = Topmost->InputBackground->h; SDL_BlitSurface(Topmost->InputBackground, NULL, Topmost->ConsoleSurface, &rect); /* now add the text */ DT_DrawText(Topmost->VCommand, Topmost->ConsoleSurface, Topmost->FontNumber, CON_CHAR_BORDER, Topmost->ConsoleSurface->h - (Topmost->FontHeight*2)); // if(Blink) { x = CON_CHAR_BORDER + Topmost->FontWidth * (Topmost->CursorPos - Topmost->Offset + strlen(Topmost->Prompt)); if(Topmost->InsMode) DT_DrawText(CON_INS_CURSOR, Topmost->ConsoleSurface, Topmost->FontNumber, x, Topmost->ConsoleSurface->h - (Topmost->FontHeight*2)); else DT_DrawText(CON_OVR_CURSOR, Topmost->ConsoleSurface, Topmost->FontNumber, x, Topmost->ConsoleSurface->h - (Topmost->FontHeight*2)); // } // if(Topmost->OutputScreen->flags & SDL_OPENGLBLIT) { // SDL_SetColorKey(CurrentFont->FontSurface, 0, 0); // } } /* Outputs text to the console (in game), up to CON_CHARS_PER_LINE chars can be entered */ void CON_Out(ConsoleInformation *console, const char *str, ...) { va_list marker; char temp[CON_CHARS_PER_LINE+1]; char* ptemp; if(!console) return; va_start(marker, str); vsnprintf(temp, CON_CHARS_PER_LINE, str, marker); va_end(marker); ptemp = temp; /* temp now contains the complete string we want to output the only problem is that temp is maybe longer than the console width so we have to cut it into several pieces */ if(console->ConsoleLines) { while(strlen(ptemp) > console->VChars) { CON_NewLineConsole(console); strncpy(console->ConsoleLines[0], ptemp, console->VChars); console->ConsoleLines[0][console->VChars] = '\0'; ptemp = &ptemp[console->VChars]; } CON_NewLineConsole(console); strncpy(console->ConsoleLines[0], ptemp, console->VChars); console->ConsoleLines[0][console->VChars] = '\0'; CON_UpdateConsole(console); } /* And print to stdout */ /* printf("%s\n", temp); */ } /* Sets the alpha level of the console, 0 turns off alpha blending */ void CON_Alpha(ConsoleInformation *console, unsigned char alpha) { if(!console) return; /* store alpha as state! */ console->ConsoleAlpha = alpha; if((console->OutputScreen->flags & SDL_OPENGLBLIT) == 0) { if(alpha == 0) SDL_SetAlpha(console->ConsoleSurface, 0, alpha); else SDL_SetAlpha(console->ConsoleSurface, SDL_SRCALPHA, alpha); } /* CON_UpdateConsole(console); */ } /* Adds background image to the console, x and y based on consoles x and y */ int CON_Background(ConsoleInformation *console, const char *image, int x, int y) { SDL_Surface *temp; SDL_Rect backgroundsrc, backgrounddest; if(!console) return 1; /* Free the background from the console */ if(image == NULL) { if(console->BackgroundImage ==NULL) SDL_FreeSurface(console->BackgroundImage); console->BackgroundImage = NULL; SDL_FillRect(console->InputBackground, NULL, SDL_MapRGBA(console->ConsoleSurface->format, 0, 0, 0, SDL_ALPHA_OPAQUE)); return 0; } /* Load a new background */ #ifdef HAVE_SDLIMAGE temp = IMG_Load(image); #else temp = SDL_LoadBMP(image); #endif if(!temp) { CON_Out(console, "Cannot load background %s.", image); return 1; } console->BackgroundImage = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); console->BackX = x; console->BackY = y; backgroundsrc.x = 0; backgroundsrc.y = console->ConsoleSurface->h - console->FontHeight - console->BackY; backgroundsrc.w = console->BackgroundImage->w; backgroundsrc.h = console->InputBackground->h; backgrounddest.x = console->BackX; backgrounddest.y = 0; backgrounddest.w = console->BackgroundImage->w; backgrounddest.h = console->FontHeight; SDL_FillRect(console->InputBackground, NULL, SDL_MapRGBA(console->ConsoleSurface->format, 0, 0, 0, SDL_ALPHA_OPAQUE)); SDL_BlitSurface(console->BackgroundImage, &backgroundsrc, console->InputBackground, &backgrounddest); CON_UpdateConsole(console); return 0; } /* takes a new x and y of the top left of the console window */ void CON_Position(ConsoleInformation *console, int x, int y) { if(!console) return; if(x < 0 || x > console->OutputScreen->w - console->ConsoleSurface->w) console->DispX = 0; else console->DispX = x; if(y < 0 || y > console->OutputScreen->h - console->ConsoleSurface->h) console->DispY = 0; else console->DispY = y; } /* resizes the console, has to reset alot of stuff * returns 1 on error */ int CON_Resize(ConsoleInformation *console, SDL_Rect rect) { SDL_Surface *Temp; SDL_Rect backgroundsrc, backgrounddest; if(!console) return 1; /* make sure that the size of the console is valid */ if(rect.w > console->OutputScreen->w || rect.w < console->FontWidth * 32) rect.w = console->OutputScreen->w; if(rect.h > console->OutputScreen->h || rect.h < console->FontHeight) rect.h = console->OutputScreen->h; if(rect.x < 0 || rect.x > console->OutputScreen->w - rect.w) console->DispX = 0; else console->DispX = rect.x; if(rect.y < 0 || rect.y > console->OutputScreen->h - rect.h) console->DispY = 0; else console->DispY = rect.y; /* load the console surface */ SDL_FreeSurface(console->ConsoleSurface); Temp = SDL_CreateRGBSurface(SDL_HWSURFACE, rect.w, rect.h, console->OutputScreen->format->BitsPerPixel, 0, 0, 0, 0); if(Temp == NULL) { PRINT_ERROR("Couldn't create the console->ConsoleSurface\n"); return 1; } console->ConsoleSurface = SDL_DisplayFormat(Temp); SDL_FreeSurface(Temp); /* Load the dirty rectangle for user input */ SDL_FreeSurface(console->InputBackground); Temp = SDL_CreateRGBSurface(SDL_HWSURFACE, rect.w, console->FontHeight, console->OutputScreen->format->BitsPerPixel, 0, 0, 0, 0); if(Temp == NULL) { PRINT_ERROR("Couldn't create the input background\n"); return 1; } console->InputBackground = SDL_DisplayFormat(Temp); SDL_FreeSurface(Temp); /* Now reset some stuff dependent on the previous size */ console->ConsoleScrollBack = 0; /* Reload the background image (for the input text area) in the console */ if(console->BackgroundImage) { backgroundsrc.x = 0; backgroundsrc.y = console->ConsoleSurface->h - console->FontHeight - console->BackY; backgroundsrc.w = console->BackgroundImage->w; backgroundsrc.h = console->InputBackground->h; backgrounddest.x = console->BackX; backgrounddest.y = 0; backgrounddest.w = console->BackgroundImage->w; backgrounddest.h = console->FontHeight; SDL_FillRect(console->InputBackground, NULL, SDL_MapRGBA(console->ConsoleSurface->format, 0, 0, 0, SDL_ALPHA_OPAQUE)); SDL_BlitSurface(console->BackgroundImage, &backgroundsrc, console->InputBackground, &backgrounddest); } /* restore the alpha level */ CON_Alpha(console, console->ConsoleAlpha); /* re-calculate the number of visible characters in the command line */ console->VChars = (rect.w - CON_CHAR_BORDER) / console->FontWidth; if(console->VChars > CON_CHARS_PER_LINE) console->VChars = CON_CHARS_PER_LINE; CON_UpdateConsole(console); return 0; } /* Transfers the console to another screen surface, and adjusts size */ int CON_Transfer(ConsoleInformation* console, SDL_Surface* new_outputscreen, SDL_Rect rect) { if(!console) return 1; console->OutputScreen = new_outputscreen; return( CON_Resize(console, rect) ); } /* Sets the topmost console for input */ void CON_Topmost(ConsoleInformation *console) { SDL_Rect rect; if(!console) return; /* Make sure the blinking cursor is gone */ if(Topmost) { rect.x = 0; rect.y = Topmost->ConsoleSurface->h - Topmost->FontHeight; rect.w = Topmost->InputBackground->w; rect.h = Topmost->InputBackground->h; SDL_BlitSurface(Topmost->InputBackground, NULL, Topmost->ConsoleSurface, &rect); DT_DrawText(Topmost->VCommand, Topmost->ConsoleSurface, Topmost->FontNumber, CON_CHAR_BORDER, Topmost->ConsoleSurface->h - Topmost->FontHeight); } Topmost = console; } /* Sets the Prompt for console */ void CON_SetPrompt(ConsoleInformation *console, char* newprompt) { if(!console) return; /* check length so we can still see at least 1 char :-) */ if(strlen(newprompt) < console->VChars) console->Prompt = strdup(newprompt); else CON_Out(console, "prompt too long. (max. %i chars)", console->VChars - 1); } /* Sets the key that deactivates (hides) the console. */ void CON_SetHideKey(ConsoleInformation *console, int key) { if(console) console->HideKey = key; } /* Executes the command entered */ void CON_Execute(ConsoleInformation *console, char* command) { if(console) console->CmdFunction(console, command); } void CON_SetExecuteFunction(ConsoleInformation *console, void(*CmdFunction)(ConsoleInformation *console2, char* command)) { if(console) console->CmdFunction = CmdFunction; } void Default_CmdFunction(ConsoleInformation *console, char* command) { CON_Out(console, " No CommandFunction registered"); CON_Out(console, " use 'CON_SetExecuteFunction' to register one"); CON_Out(console, " "); CON_Out(console, "Unknown Command \"%s\"", command); } void CON_SetTabCompletion(ConsoleInformation *console, char*(*TabFunction)(char* command)) { if(console) console->TabFunction = TabFunction; } void CON_TabCompletion(ConsoleInformation *console) { int i,j; char* command; if(!console) return; command = strdup(console->LCommand); command = console->TabFunction(command); if(!command) return; /* no tab completion took place so return silently */ /* command now contains the tabcompleted string. check for correct size since the string has to fit into the commandline it can have a maximum length of CON_CHARS_PER_LINE = commandlength + space + cursor => commandlength = CON_CHARS_PER_LINE - 2 */ j = strlen(command); if(j + 2 > CON_CHARS_PER_LINE) j = CON_CHARS_PER_LINE - 2; memset_sh4(console->LCommand, 0, CON_CHARS_PER_LINE+1); console->CursorPos = 0; for(i = 0; i < j; i++) { console->CursorPos++; console->LCommand[i] = command[i]; } /* add a trailing space */ console->CursorPos++; console->LCommand[j] = ' '; console->LCommand[j+1] = '\0'; Assemble_Command(console); } char* Default_TabFunction(char* command) { CON_Out(Topmost, " No TabFunction registered"); CON_Out(Topmost, " use 'CON_SetTabCompletion' to register one"); CON_Out(Topmost, " "); return NULL; } void Cursor_Left(ConsoleInformation *console) { char temp[CON_CHARS_PER_LINE+1]; if(Topmost->CursorPos > 0) { Topmost->CursorPos--; strcpy(temp, Topmost->RCommand); strcpy(Topmost->RCommand, &Topmost->LCommand[strlen(Topmost->LCommand)-1]); strcat(Topmost->RCommand, temp); Topmost->LCommand[strlen(Topmost->LCommand)-1] = '\0'; /* CON_Out(Topmost, "L:%s, R:%s", Topmost->LCommand, Topmost->RCommand); */ } } void Cursor_Right(ConsoleInformation *console) { char temp[CON_CHARS_PER_LINE+1]; if(Topmost->CursorPos < strlen(Topmost->Command)) { Topmost->CursorPos++; strncat(Topmost->LCommand, Topmost->RCommand, 1); strcpy(temp, Topmost->RCommand); strcpy(Topmost->RCommand, &temp[1]); /* CON_Out(Topmost, "L:%s, R:%s", Topmost->LCommand, Topmost->RCommand); */ } } void Cursor_Home(ConsoleInformation *console) { char temp[CON_CHARS_PER_LINE+1]; Topmost->CursorPos = 0; strcpy(temp, Topmost->RCommand); strcpy(Topmost->RCommand, Topmost->LCommand); strncat(Topmost->RCommand, temp, strlen(temp)); memset(Topmost->LCommand, 0, CON_CHARS_PER_LINE+1); } void Cursor_End(ConsoleInformation *console) { Topmost->CursorPos = strlen(Topmost->Command); strncat(Topmost->LCommand, Topmost->RCommand, strlen(Topmost->RCommand)); memset_sh4(Topmost->RCommand, 0, CON_CHARS_PER_LINE+1); } void Cursor_Del(ConsoleInformation *console) { char temp[CON_CHARS_PER_LINE+1]; if(strlen(Topmost->RCommand) > 0) { strcpy(temp, Topmost->RCommand); strcpy(Topmost->RCommand, &temp[1]); Assemble_Command(console); } } void Cursor_BSpace(ConsoleInformation *console) { if(Topmost->CursorPos > 0) { Topmost->CursorPos--; Topmost->Offset--; if(Topmost->Offset < 0) Topmost->Offset = 0; Topmost->LCommand[strlen(Topmost->LCommand)-1] = '\0'; Assemble_Command(console); } } void Cursor_Add(ConsoleInformation *console, SDL_Event *event) { int len = 0; //int ch = kbd_get_key(); /* Again: the commandline has to hold the command and the cursor (+1) */ if(strlen(Topmost->Command) + 1 < CON_CHARS_PER_LINE && isascii(event->key.keysym.unicode)) { Topmost->CursorPos++; len = strlen(Topmost->LCommand); Topmost->LCommand[len] = (char)event->key.keysym.unicode; //(char)ch; Topmost->LCommand[len + sizeof(char)] = '\0'; Assemble_Command(console); } } void Clear_Command(ConsoleInformation *console) { Topmost->CursorPos = 0; memset_sh4(Topmost->VCommand, 0, CON_CHARS_PER_LINE+1); memset_sh4(Topmost->Command, 0, CON_CHARS_PER_LINE+1); memset_sh4(Topmost->LCommand, 0, CON_CHARS_PER_LINE+1); memset_sh4(Topmost->RCommand, 0, CON_CHARS_PER_LINE+1); } void Assemble_Command(ConsoleInformation* console) { int len = 0; /* Concatenate the left and right side to command */ len = CON_CHARS_PER_LINE - strlen(Topmost->LCommand); strcpy(Topmost->Command, Topmost->LCommand); strncat(Topmost->Command, Topmost->RCommand, len); Topmost->Command[CON_CHARS_PER_LINE] = '\0'; } void Clear_History(ConsoleInformation *console) { int loop; for(loop = 0; loop <= console->LineBuffer - 1; loop++) memset_sh4(console->ConsoleLines[loop], 0, CON_CHARS_PER_LINE+1); } void Command_Up(ConsoleInformation *console) { if(console->CommandScrollBack < console->TotalCommands - 1) { /* move back a line in the command strings and copy the command to the current input string */ console->CommandScrollBack++; /* I want to know if my string handling REALLY works :-) */ /* memset_sh4(console->RCommand, 0, CON_CHARS_PER_LINE); memset_sh4(console->LCommand, 0, CON_CHARS_PER_LINE); */ console->RCommand[0] = '\0'; console->Offset = 0; strcpy(console->LCommand, console->CommandLines[console->CommandScrollBack]); console->CursorPos = strlen(console->CommandLines[console->CommandScrollBack]); Assemble_Command(console); } } void Command_Down(ConsoleInformation *console) { if(console->CommandScrollBack > -1) { /* move forward a line in the command strings and copy the command to the current input string */ console->CommandScrollBack--; /* I want to know if my string handling REALLY works :-) */ /* memset_sh4(console->RCommand, 0, CON_CHARS_PER_LINE); memset_sh4(console->LCommand, 0, CON_CHARS_PER_LINE); */ console->RCommand[0] = '\0'; console->Offset = 0; if(console->CommandScrollBack > -1) strcpy(console->LCommand, console->CommandLines[console->CommandScrollBack]); console->CursorPos = strlen(console->LCommand); Assemble_Command(console); } } <file_sep>/modules/dreameye/dreameye.c /* DreamShell ##version## dreameye.c - dreameye driver addons Copyright (C)2015 SWAT */ #include <ds.h> #include <assert.h> #include <kos/genwait.h> #include <drivers/dreameye.h> static int frame_pkg_size = 1004; // FIXME static dreameye_state_t *first_state = NULL; static int dreameye_send_get_video_frame(maple_device_t *dev, dreameye_state_t *state, uint8 req, uint8 cnt); void hexDump(char *desc, void *addr, int len) { int i; unsigned char buff[17]; unsigned char *pc = (unsigned char*)addr; // Output description if given. if (desc != NULL) dbglog(DBG_DEBUG, "%s:\n", desc); // Process every byte in the data. for (i = 0; i < len; i++) { // Multiple of 16 means new line (with line offset). if ((i % 16) == 0) { // Just don't print ASCII for the zeroth line. if (i != 0) dbglog(DBG_DEBUG, " %s\n", buff); // Output the offset. dbglog(DBG_DEBUG, " %04x ", i); } // Now the hex code for the specific character. dbglog(DBG_DEBUG, " %02x", pc[i]); // And store a printable ASCII character for later. if ((pc[i] < 0x20) || (pc[i] > 0x7e)) buff[i % 16] = '.'; else buff[i % 16] = pc[i]; buff[(i % 16) + 1] = '\0'; } // Pad out last line if not exactly 16 characters. while ((i % 16) != 0) { dbglog(DBG_DEBUG, " "); i++; } // And print the final ASCII bit. dbglog(DBG_DEBUG, " %s\n", buff); } static void dreameye_get_video_frame_cb(maple_frame_t *frame) { maple_device_t *dev; maple_response_t *resp; uint32 *respbuf32; uint8 *respbuf8, cur_pkg; int len = 0, bit_exp = 0, pix_exp = 0, frame_info = 0, packet_len = 0; /* Unlock the frame */ maple_frame_unlock(frame); if(frame->dev == NULL) return; dev = frame->dev; /* Make sure we got a valid response */ resp = (maple_response_t *)frame->recv_buf; respbuf32 = (uint32 *)resp->data; respbuf8 = (uint8 *)resp->data; hexDump("resp", resp->data, resp->data_len * 4); // if(resp->response == MAPLE_COMMAND_CAMCONTROL && respbuf8[4] == DREAMEYE_SUBCOMMAND_ERROR) { // dbglog(DBG_ERROR, "dreameye_get_video_frame: error 0x%02X%02X%02X\n", // respbuf8[5], respbuf8[6], respbuf8[7]); // } if(resp->response != MAPLE_RESPONSE_DATATRF) { first_state->img_transferring = -1; return; } if(respbuf32[0] != MAPLE_FUNC_CAMERA) { first_state->img_transferring = -1; dbglog(DBG_ERROR, "%s: bad func: 0x%08lx\n", __func__, respbuf32[0]); return; } len = (resp->data_len - 3) * 4; cur_pkg = respbuf8[5]; bit_exp = respbuf8[14] + (respbuf8[13] << 8); pix_exp = respbuf8[12] + ((respbuf8[11] & 0x3f) << 8); frame_info = respbuf8[11] & 0xc0; packet_len = ((bit_exp + 47) >> 4) << 1; dbglog(DBG_DEBUG, "%s: cur=%d len=%d part=%02x bit=%d pix=%d fi=%02x pkglen=%d\n", __func__, cur_pkg, len, respbuf8[4], bit_exp, pix_exp, frame_info, packet_len); /* Copy the data. */ memcpy(first_state->img_buf + first_state->img_size, respbuf8 + 16, len); first_state->img_size += len; /* Check if we're done. */ if(respbuf8[4] & 0x40) { first_state->img_transferring = 0; return; } cur_pkg += 5; if(cur_pkg < first_state->transfer_count) { dreameye_send_get_video_frame(dev, first_state, DREAMEYE_IMAGEREQ_CONTINUE, cur_pkg); } } static int dreameye_send_get_video_frame(maple_device_t *dev, dreameye_state_t *state, uint8 req, uint8 cnt) { uint32 *send_buf; /* Lock the frame */ if(maple_frame_lock(&dev->frame) < 0) return MAPLE_EAGAIN; /* Reset the frame */ maple_frame_init(&dev->frame); send_buf = (uint32 *)dev->frame.recv_buf; send_buf[0] = MAPLE_FUNC_CAMERA; send_buf[1] = DREAMEYE_SUBCOMMAND_IMAGEREQ | (state->img_number << 8) | (req << 16) | (cnt << 24); dev->frame.cmd = MAPLE_COMMAND_CAMCONTROL; dev->frame.dst_port = dev->port; dev->frame.dst_unit = dev->unit; dev->frame.length = 2; dev->frame.callback = dreameye_get_video_frame_cb; dev->frame.send_buf = send_buf; maple_queue_frame(&dev->frame); return MAPLE_EOK; } int dreameye_get_video_frame(maple_device_t *dev, uint8 image, uint8 **data, int *img_sz) { dreameye_state_t *de; maple_device_t *dev2, *dev3, *dev4, *dev5; assert(dev != NULL); assert(dev->unit == 1); dev2 = maple_enum_dev(dev->port, 2); dev3 = maple_enum_dev(dev->port, 3); dev4 = maple_enum_dev(dev->port, 4); dev5 = maple_enum_dev(dev->port, 5); de = (dreameye_state_t *)dev->status; first_state = de; de->img_transferring = 1; de->img_buf = NULL; de->img_size = 0; de->img_number = image; de->transfer_count = 32; // FIXME /* Allocate space for the largest possible image that could fit in that number of transfers. */ de->img_buf = (uint8 *)malloc(frame_pkg_size * de->transfer_count); if(!de->img_buf) goto fail; /* Send out the image requests to all sub devices. */ dreameye_send_get_video_frame(dev, de, DREAMEYE_IMAGEREQ_START, 0); dreameye_send_get_video_frame(dev2, de, DREAMEYE_IMAGEREQ_CONTINUE, 1); dreameye_send_get_video_frame(dev3, de, DREAMEYE_IMAGEREQ_CONTINUE, 2); dreameye_send_get_video_frame(dev4, de, DREAMEYE_IMAGEREQ_CONTINUE, 3); dreameye_send_get_video_frame(dev5, de, DREAMEYE_IMAGEREQ_CONTINUE, 4); while(de->img_transferring == 1) { thd_pass(); } if(de->img_transferring == 0) { *data = de->img_buf; *img_sz = de->img_size; dbglog(DBG_DEBUG, "dreameye_get_image: Image of size %d received in " "%d transfers\n", de->img_size, de->transfer_count); first_state = NULL; de->img_buf = NULL; de->img_size = 0; de->transfer_count = 0; return MAPLE_EOK; } /* If we get here, something went wrong. */ if(de->img_buf != NULL) { free(de->img_buf); } fail: first_state = NULL; de->img_transferring = 0; de->img_buf = NULL; de->img_size = 0; de->transfer_count = 0; return MAPLE_EFAIL; } static void dreameye_get_param_cb(maple_frame_t *frame) { dreameye_state_ext_t *de; maple_response_t *resp; uint32 *respbuf32; uint8 *respbuf8; /* Unlock the frame */ maple_frame_unlock(frame); /* Make sure we got a valid response */ resp = (maple_response_t *)frame->recv_buf; respbuf32 = (uint32 *)resp->data; respbuf8 = (uint8 *)resp->data; if(resp->response == MAPLE_COMMAND_CAMCONTROL && respbuf8[4] == DREAMEYE_SUBCOMMAND_ERROR) { dbglog(DBG_ERROR, "dreameye_get_param: error 0x%02X%02X%02X\n", respbuf8[5], respbuf8[6], respbuf8[7]); } if(resp->response != MAPLE_RESPONSE_DATATRF) { // dbglog(DBG_ERROR, "%s: bad response: %d\n", __func__, resp->response); return; } if(respbuf32[0] != MAPLE_FUNC_CAMERA) return; /* Update the status that was requested. */ if(frame->dev) { assert((resp->data_len) == 3); assert(respbuf8[4] == 0xD0); assert(respbuf8[5] == 0x00); // assert(respbuf8[8] == DREAMEYE_GETCOND_***); /* Update the data in the status. */ de = (dreameye_state_ext_t *)frame->dev->status; // hexDump("getparam", respbuf8, 12); de->value = respbuf8[10] | respbuf8[11] << 8; } /* Wake up! */ genwait_wake_all(frame); } int dreameye_get_param(maple_device_t *dev, uint8 param, uint8 arg, uint16 *value) { uint32 *send_buf; dreameye_state_ext_t *de; assert(dev != NULL); /* Lock the frame */ if(maple_frame_lock(&dev->frame) < 0) return MAPLE_EAGAIN; /* Reset the frame */ maple_frame_init(&dev->frame); send_buf = (uint32 *)dev->frame.recv_buf; send_buf[0] = MAPLE_FUNC_CAMERA; send_buf[1] = param | (arg << 8); dev->frame.cmd = MAPLE_COMMAND_GETCOND; dev->frame.dst_port = dev->port; dev->frame.dst_unit = dev->unit; dev->frame.length = 2; dev->frame.callback = dreameye_get_param_cb; dev->frame.send_buf = send_buf; maple_queue_frame(&dev->frame); /* Wait for the Dreameye to accept it */ if(genwait_wait(&dev->frame, "dreameye_get_param", 500, NULL) < 0) { if(dev->frame.state != MAPLE_FRAME_VACANT) { /* Something went wrong... */ dev->frame.state = MAPLE_FRAME_VACANT; dbglog(DBG_ERROR, "dreameye_get_param: timeout to unit " "%c%c\n", dev->port + 'A', dev->unit + '0'); return MAPLE_ETIMEOUT; } } if(value) { de = (dreameye_state_ext_t *)dev->status; *value = de->value; } return MAPLE_EOK; } static void dreameye_set_param_cb(maple_frame_t *frame) { // dreameye_state_ext_t *de; maple_response_t *resp; uint8 *respbuf8; /* Unlock the frame */ maple_frame_unlock(frame); /* Make sure we got a valid response */ resp = (maple_response_t *)frame->recv_buf; respbuf8 = (uint8 *)resp->data; if(resp->response == MAPLE_COMMAND_CAMCONTROL && respbuf8[4] == DREAMEYE_SUBCOMMAND_ERROR) { dbglog(DBG_ERROR, "dreameye_set_param: error 0x%02X%02X%02X\n", respbuf8[5], respbuf8[6], respbuf8[7]); return; } if(resp->response != MAPLE_RESPONSE_OK) { dbglog(DBG_ERROR, "%s: bad response: %d\n", __func__, resp->response); return; } hexDump("setparam", respbuf8, 12); /* Wake up! */ genwait_wake_all(frame); } int dreameye_set_param(maple_device_t *dev, uint8 param, uint8 arg, uint16 value) { uint32 *send_buf; // dreameye_state_ext_t *de; assert(dev != NULL); /* Lock the frame */ if(maple_frame_lock(&dev->frame) < 0) return MAPLE_EAGAIN; /* Reset the frame */ maple_frame_init(&dev->frame); send_buf = (uint32 *)dev->frame.recv_buf; send_buf[0] = MAPLE_FUNC_CAMERA; send_buf[1] = param | (arg << 8) | (value << 16); dev->frame.cmd = MAPLE_COMMAND_SETCOND; dev->frame.dst_port = dev->port; dev->frame.dst_unit = dev->unit; dev->frame.length = 2; dev->frame.callback = dreameye_set_param_cb; dev->frame.send_buf = send_buf; maple_queue_frame(&dev->frame); /* Wait for the Dreameye to accept it */ if(genwait_wait(&dev->frame, "dreameye_set_param", 500, NULL) < 0) { if(dev->frame.state != MAPLE_FRAME_VACANT) { /* Something went wrong... */ dev->frame.state = MAPLE_FRAME_VACANT; dbglog(DBG_ERROR, "dreameye_set_param: timeout to unit " "%c%c\n", dev->port + 'A', dev->unit + '0'); return MAPLE_ETIMEOUT; } } return MAPLE_EOK; } <file_sep>/firmware/isoldr/syscalls/syscallsc.c /** * This file is part of DreamShell ISO Loader * Copyright (C)2019 megavolt85 * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include "syscalls.h" void gd_release() { #ifdef LOG LOGFF(0); #endif } void gd_pause(uint32_t *params, GDS *my_gds) { #ifdef LOG LOGFF(0); #endif (void) params; my_gds->drv_stat = STAT_PAUSE; } void gd_play2() { #ifdef LOG LOGFF(0); #endif } void gd_play(uint32_t *params, GDS *my_gds) { #ifdef LOG LOGFF(0); #endif (void) params; my_gds->drv_stat = STAT_PLAY; } void gd_seek() { #ifdef LOG LOGFF(0); #endif } void gd_stop(uint32_t *params, GDS *my_gds) { #ifdef LOG LOGFF(0); #endif (void) params; my_gds->drv_stat = STAT_PAUSE; } /* int gdGdcChangeDataType(uint32_t *param) { #ifdef LOG LOGFF(0); #endif if (allocate_GD() != 0) { return 4; } GDS *my_gds = get_GDS(); switch (param[0]) { case 0: { if (param[3] == 2048) { release_GD(); return 0; } break; } case 1: { param[1] = 0x2000; param[2] = (my_gds->drv_media == 0x20) ? 0x800 : 0x400; param[3] = 0x800; release_GD(); return 0; break; } } release_GD(); return -1; } */ static int res_count = 0; void gdGdcChangeCD(int disc_num) { #ifdef LOG LOGFF("%d\n", disc_num); #endif res_count = 1; disc_id[0] = disc_num; } int gdGdcGetCmdStat(int gd_chn, int *status) { #ifdef LOG LOGFF(0); #endif GDS *my_gds; if (allocate_GD() != 0) { #if 0//def LOG LOGF("CMD_STAT_WAITING\n"); #endif return CMD_STAT_WAITING; /* CMD_STAT_WAITING */ } my_gds = get_GDS(); status[0] = 0; status[1] = 0; status[2] = 0; status[3] = 0; if (gd_chn == 0) { #if 0//def LOG LOGF("gd_chn=0\n"); #endif if (my_gds->gd_cmd_stat == CMD_STAT_NO_ACTIVE) { release_GD(); return CMD_STAT_NO_ACTIVE; /* CMD_STAT_NO_ACTIVE */ } release_GD(); return CMD_STAT_PROCESSING; /* CMD_STAT_PROCESSING */ } if (my_gds->gd_chn != gd_chn) { #if 0 //def LOG LOGF("gd_chn error\n"); #endif status[0] = CMD_STAT_ERROR; release_GD(); return CMD_STAT_FAILED; /* CMD_STAT_FAILED */ } switch (my_gds->gd_cmd_stat) { case CMD_STAT_NO_ACTIVE: #if 0 //def LOG LOGF("CMD_STAT_NO_ACTIVE\n"); #endif release_GD(); return CMD_STAT_NO_ACTIVE; /* CMD_STAT_NO_ACTIVE */ break; case CMD_STAT_PROCESSING: case CMD_STAT_COMPLETED: status[2] = my_gds->transfered; status[3] = my_gds->ata_status; release_GD(); #if 0 //def LOG LOGF("CMD_STAT_PROCESSING\n"); #endif return CMD_STAT_PROCESSING; /* CMD_STAT_PROCESSING */ break; case CMD_STAT_ABORTED: if (my_gds->gd_cmd_err != GDCMD_OK) { status[0] = my_gds->gd_cmd_err; status[1] = my_gds->gd_cmd_err2; status[2] = my_gds->transfered; status[3] = my_gds->ata_status; release_GD(); return CMD_STAT_FAILED; /* CMD_STAT_FAILED */ } #if 0 //def LOG LOGF("CMD_STAT_COMPLETED\n"); #endif status[2] = my_gds->transfered; status[3] = my_gds->ata_status; my_gds->ata_status = 0; my_gds->gd_cmd_stat = CMD_STAT_NO_ACTIVE; release_GD(); return CMD_STAT_COMPLETED; /* CMD_STAT_COMPLETED */ break; case CMD_STAT_WAITING: if (my_gds->gd_cmd_err != GDCMD_OK) { status[0] = my_gds->gd_cmd_err; status[1] = my_gds->gd_cmd_err2; status[2] = my_gds->transfered; status[3] = my_gds->ata_status; release_GD(); return CMD_STAT_FAILED; /* CMD_STAT_FAILED */ } status[2] = my_gds->transfered; status[3] = my_gds->ata_status; release_GD(); #if 0 //def LOG LOGF("CMD_STAT_ABORTED\n"); #endif return CMD_STAT_ABORTED; /* CMD_STAT_ABORTED */ break; default: break; } #if 0 //def LOG LOGF("CMD_STAT_NO_ACTIVE\n"); #endif release_GD(); return CMD_STAT_NO_ACTIVE; /* CMD_STAT_NO_ACTIVE */ } int gdGdcGetDrvStat(uint32_t *status) { GDS *my_gds = get_GDS(); #if 0 //def LOG LOGFF("%d\n", my_gds->drv_stat); #endif if (allocate_GD() != 0) { return 4; } if (res_count) { res_count++; if (res_count == 2) { my_gds->drv_media = TYPE_CDDA; my_gds->drv_stat = STAT_OPEN; } else if (res_count > 30) { my_gds->drv_media = TYPE_GDROM; my_gds->drv_stat = STAT_PAUSE; res_count = 0; release_GD(); return 2; } else { status[0] = my_gds->drv_stat; status[1] = my_gds->drv_media; release_GD(); return 1; } } status[0] = my_gds->drv_stat; status[1] = my_gds->drv_media; release_GD(); return 0; /* #ifdef LOG LOGFF(0); #endif if (allocate_GD() != 0) { return 4; } GDS *my_gds = get_GDS(); if (my_gds->dma_in_progress == 0) { if (!(IN8(G1_ATA_ALTSTATUS) & G1_ATA_SR_BSY)) { my_gds->drv_stat = STAT_PAUSE; status[0] = STAT_PAUSE; } else { release_GD(); return 1; } } else { my_gds->drv_stat = STAT_PLAY; status[0] = STAT_PLAY; } status[1] = my_gds->drv_media; release_GD(); return 0; */ } /* void gdGdcG1DmaEnd(uint32_t func, uint32_t param) { #ifdef LOG LOGFF("%08X %d\n", func, param); #endif OUT32(NORMAL_INT_STAT, 0x4000); #if 0 //def LOG scif_init(); #endif if (!func) { return; } void (*callback)() = (void (*)())(func); callback(param); } */ int gdGdcReqDmaTrans(int gd_chn, uint32_t *params) /* _8c0032a2 */ { #ifdef LOG LOGFF("%08X %d\n", params[0], params[1]); #endif GDS *my_gds; my_gds = get_GDS(); if (gd_chn != my_gds->gd_chn) { return -1; } if (my_gds->gd_cmd_stat != CMD_STAT_WAITING) { return -1; } if (params[1] > my_gds->requested) { return -1; } OUT32(G1_ATA_DMA_PRO, G1_ATA_DMA_PRO_SYSMEM); OUT32(G1_ATA_DMA_ADDRESS, params[0]); OUT32(G1_ATA_DMA_LENGTH, params[1]); OUT8(G1_ATA_DMA_DIRECTION, 1); my_gds->requested -= params[1]; OUT8(G1_ATA_DMA_ENABLE, 1); OUT8(G1_ATA_DMA_STATUS, 1); return 0; } int gdGdcCheckDmaTrans(int gd_chn, uint32_t *size) { #ifdef LOG LOGFF(0); #endif GDS *my_gds; my_gds = get_GDS(); if (gd_chn != my_gds->gd_chn) { return -1; } if (my_gds->gd_cmd_stat != CMD_STAT_WAITING) { return -1; } if(IN8(G1_ATA_DMA_STATUS)) { *size = IN32(G1_ATA_DMA_LEND); return 1; } *size = my_gds->requested; return 0; } int gdGdcReadAbort(int gd_chn) { #ifdef LOG LOGFF(0); #endif GDS *my_gds; my_gds = get_GDS(); if (gd_chn != my_gds->gd_chn) { return -1; } if (my_gds->cmd_abort) { return -1; } switch (my_gds->gd_cmd) { case 16: case 17: case 20: case 21: case 22: case 27: case 28: case 29: case 32: case 33: case 34: case 37: case 38: case 39: switch (my_gds->gd_cmd_stat) { case CMD_STAT_PROCESSING: case CMD_STAT_COMPLETED: case CMD_STAT_WAITING: my_gds->cmd_abort = 1; return 0; break; default: return 0; break; } break; default: break; } return -1; } void gdGdcReset() { #ifdef LOG LOGFF(0); #endif GDS *my_gds; my_gds = get_GDS(); if (IN8(G1_ATA_DMA_STATUS)) { OUT8(G1_ATA_DMA_ENABLE, 0); while (IN8(G1_ATA_DMA_STATUS)); my_gds->dma_in_progress = 0; } OUT8(G1_ATA_COMMAND_REG, 8); while (IN8(G1_ATA_ALTSTATUS) & G1_ATA_SR_BSY); } void gdGdcSetPioCallback(void *callback, int callback_param) { #ifdef LOG LOGFF("%08X %08X\n", callback, callback_param); #endif GDS *my_gds; my_gds = get_GDS(); if (callback) { my_gds->callback = callback; my_gds->callback_param = callback_param; } else { my_gds->callback = 0; my_gds->callback_param = 0; } } int gdGdcCheckPioTrans(int gd_chn, int *size) { #ifdef LOG LOGFF(0); #endif GDS *my_gds; my_gds = get_GDS(); if (gd_chn != my_gds->gd_chn) { return -1; } if (my_gds->gd_cmd_stat != CMD_STAT_WAITING) { return -1; } if (my_gds->piosize) { *size = my_gds->transfered; return 1; } *size = my_gds->requested; return 0; } int gdGdcReqPioTrans(int gd_chn, uint32_t *params) /* _8c003374 */ { #ifdef LOG LOGFF("%08X %d\n", params[0], params[1]); #endif GDS *my_gds; my_gds = get_GDS(); if (gd_chn != my_gds->gd_chn) { return -1; } if (my_gds->gd_cmd_stat != CMD_STAT_WAITING) { return -1; } if(params[1] > my_gds->requested) { return -1; } my_gds->requested -= params[1]; my_gds->pioaddr = (short *) params[0]; my_gds->piosize = params[1]; return 0; } /*void Init_GDS() { #ifdef LOG LOGFF(0); #endif GDS *my_gds = get_GDS(); my_gds->gd_cmd = 0; my_gds->gd_cmd_err = GDCMD_OK; my_gds->gd_cmd_err2 = 0; my_gds->transfered = 0; my_gds->ata_status = 0; my_gds->drv_stat = 0; my_gds->cmd_abort = 0; my_gds->requested = 0; my_gds->gd_chn = 1; my_gds->dma_in_progress = 0; my_gds->need_reinit = 0; my_gds->callback = 0; my_gds->callback_param = 0; my_gds->pioaddr = 0; my_gds->piosize = 0; my_gds->param[0] = 0; my_gds->param[1] = 0; my_gds->param[2] = 0; my_gds->param[3] = 0; my_gds->gd_cmd_stat = CMD_STAT_NO_ACTIVE; while(1) { if (my_gds->gd_cmd_stat == CMD_STAT_COMPLETED) { my_gds->gd_cmd_stat = CMD_STAT_PROCESSING; my_gds->gd_cmd_err = GDCMD_OK; my_gds->gd_cmd_err2 = 0; my_gds->transfered = 0; if (my_gds->need_reinit == 1 && my_gds->gd_cmd != 24) { my_gds->gd_cmd_err = GDCMD_NOT_INITED; } else { gd_do_cmd(my_gds->param, my_gds, my_gds->gd_cmd); } // 8с003742 сюда мы попадаем после отработки команды my_gds->gd_cmd_stat = CMD_STAT_ABORTED; my_gds->cmd_abort = 0; if (my_gds->gd_cmd_err == GDCMD_NOT_INITED) { my_gds->need_reinit = 1; } } Exit_to_game(); // эта функция вернёт нас в игру // 8с003756 сюда мы попадаем при первой отработке любой комнды gdGdcExecServer'ом } }*/ int dma_abort(GDS *my_gds) { if (IN8(G1_ATA_DMA_STATUS)) { OUT8(G1_ATA_DMA_ENABLE, 0); while (IN8(G1_ATA_DMA_STATUS)); } my_gds->dma_in_progress = 0; return lock_gdsys(0); } void g1_ata_wait_nbsy(GDS *my_gds) { while( IN8(G1_ATA_ALTSTATUS) & G1_ATA_SR_BSY ) { my_gds->ata_status = 4; Exit_to_game(); } my_gds->ata_status = 0; } void g1_ata_wait_bsydrq(GDS *my_gds) { while (1) { if (!(IN8(G1_ATA_ALTSTATUS) & 0x88)) { my_gds->ata_status = 0; return; } else { my_gds->ata_status = 2; Exit_to_game(); } } } void wait_gddma_irq(GDS *my_gds) { do { my_gds->ata_status = 1; Exit_to_game(); } while (!(IN32(EXT_INT_STAT) & 1)); my_gds->ata_status = 0; } void transfer_loop(int dma, GDS *my_gds) { while (1) { if(my_gds->cmd_abort != 0) { break; } my_gds->ata_status = 1; Exit_to_game(); if (dma) { my_gds->transfered = IN32(G1_ATA_DMA_LEND); } if((IN32(EXT_INT_STAT) & 1) != 0) { break; } } my_gds->ata_status = 0; } void gd_cmd_abort(GDS *my_gds) { #ifdef LOG LOGFF(0); #endif dma_abort(my_gds); my_gds->requested = 0; OUT8(G1_ATA_DEVICE_SELECT, 0x10); OUT8(G1_ATA_FEATURES, 0); g1_ata_wait_nbsy(my_gds); OUT8(G1_ATA_COMMAND_REG, 0); g1_ata_wait_bsydrq(my_gds); } uint8_t gd_read_abort(int *param, GDS *my_gds) { #ifdef LOG LOGFF(0); #endif (void) param; dma_abort(my_gds); my_gds->requested = 0; OUT8(G1_ATA_DEVICE_SELECT, 0x10); OUT8(G1_ATA_FEATURES, 0); OUT8(G1_ATA_COMMAND_REG, 0); wait_gddma_irq(my_gds); return IN8(G1_ATA_STATUS_REG); } void lba_tranlator(int dma, GDS *my_gds) { uint32_t lba; uint16_t seccnt = (uint16_t) my_gds->param[1] << 2; // uint8_t cmd; my_gds->currentLBA = my_gds->param[0] + my_gds->param[1]; if ( /*my_gds->drv_media == 0x20 ||((*/my_gds->param[0] < 45150 /*) && my_gds->dtrkLBA[0])*/ ) { lba = ((my_gds->param[0] - 150) << 2) + my_gds->dtrkLBA[0]; my_gds->currentLBA += 0x01000000; } else if (my_gds->dtrkLBA[2] && my_gds->param[0] >= (my_gds->TOC.entry[((my_gds->TOC.last >> 16) & 0xFF)-1] & 0x00FFFFFF)) { lba = ((my_gds->param[0] - (my_gds->TOC.entry[((my_gds->TOC.last >> 16) & 0xFF)-1] & 0x00FFFFFF)) << 2) + my_gds->dtrkLBA[2]; my_gds->currentLBA += (my_gds->TOC.last << 8); } else // track03 { lba = ((my_gds->param[0] - 45150) << 2) + my_gds->dtrkLBA[1]; my_gds->currentLBA += 0x03000000; } // if (seccnt > 256 || lba >= 0x10000000) // { // cmd = (dma == 0) ? ATA_CMD_READ_SECTORS_EXT : ATA_CMD_READ_DMA_EXT; OUT8(G1_ATA_DEVICE_SELECT, 0xF0); do {} while ((IN8(G1_ATA_STATUS_REG) & (G1_ATA_SR_DRDY | G1_ATA_SR_BSY)) != G1_ATA_SR_DRDY); //OUT8(G1_ATA_CTL, 0x80); OUT8(G1_ATA_SECTOR_COUNT, (uint8_t)(seccnt >> 8)); OUT8(G1_ATA_LBA_LOW, lba >> 24); OUT8(G1_ATA_LBA_MID, 0); OUT8(G1_ATA_LBA_HIGH, 0); // } /* else { cmd = (dma == 0) ? ATA_CMD_READ_SECTORS : ATA_CMD_READ_DMA; OUT8(G1_ATA_DEVICE_SELECT, (0xF0 | ((lba >> 24) & 0xF))); do {} while ((IN8(G1_ATA_STATUS_REG) & (G1_ATA_SR_DRDY | G1_ATA_SR_BSY)) != G1_ATA_SR_DRDY); }*/ //OUT8(G1_ATA_CTL, 0); OUT8(G1_ATA_SECTOR_COUNT, (seccnt & 0xff)); OUT8(G1_ATA_LBA_LOW, (lba & 0xff)); OUT8(G1_ATA_LBA_MID, ((lba >> 8) & 0xff)); OUT8(G1_ATA_LBA_HIGH, ((lba >> 16) & 0xff)); OUT8(G1_ATA_COMMAND_REG, dma ? ATA_CMD_READ_DMA_EXT:ATA_CMD_READ_SECTORS_EXT); //do {} while ((IN8(G1_ATA_ALTSTATUS) & 0xC0) != 0x40); } /* void pio_read_internal(uint16_t *buffer, GDS *my_gds) { #ifdef LOG LOGFF("%08X %d %d %08X\n", my_gds->param[2], my_gds->param[1], my_gds->param[0], my_gds->param[3]); #endif lba_tranlator(0, my_gds); my_gds->ata_status = 1; uint32_t len = my_gds->param[1] << 2; for (uint32_t i = 0; i < len; i++) { if (my_gds->cmd_abort != 0) { break; } for(int n = 0; n < 4; n++) IN8(G1_ATA_ALTSTATUS); do {} while((IN8(G1_ATA_STATUS_REG) & (G1_ATA_SR_BSY | G1_ATA_SR_DRQ)) != G1_ATA_SR_DRQ); for (uint32_t j = 0; j < 256; j++) { *buffer++ = IN16(G1_ATA_DATA); } my_gds->transfered += 512; if (i && !(i % 4)) { Exit_to_game(); } } IN8(G1_ATA_STATUS_REG); my_gds->ata_status = 0; } */ void pio_read_internal(short *buffer, GDS *my_gds) { #ifdef LOG LOGFF("%08X %d %d %08X\n", my_gds->param[2], my_gds->param[1], my_gds->param[0], my_gds->param[3]); #endif uint8_t status, status2; lba_tranlator(0, my_gds); #if 0 //def LOG LOGF("lba translated\n"); #endif do { transfer_loop(0, my_gds); #if 0 //def LOG LOGF("transfer_loop\n"); #endif if(my_gds->cmd_abort == 0) { status = IN8(G1_ATA_STATUS_REG); } else { my_gds->cmd_abort = 2; status = gd_read_abort(0, my_gds); } status2 = status & G1_ATA_SR_DRQ; if (status2 == G1_ATA_SR_DRQ) { #if 0 //def LOG LOGF("read sector\n"); #endif OUT8(G1_ATA_CTL, 2); int sec_cnt; if ((my_gds->requested - my_gds->transfered) >= 0xF000) { sec_cnt = 119; } else { sec_cnt = ((my_gds->requested - my_gds->transfered) >> 9) - 1; } for (int j = 0; j <= sec_cnt; j++) { if (j == sec_cnt) { OUT8(G1_ATA_CTL, 0); } if (j) do {} while((IN8(G1_ATA_ALTSTATUS) & (G1_ATA_SR_BSY | G1_ATA_SR_DRQ)) != G1_ATA_SR_DRQ); for (int i = 0; i < 256; i++) { buffer[i] = IN16(G1_ATA_DATA); } buffer = &buffer[256]; my_gds->transfered += 512; } } //g1_ata_wait_nbsy(my_gds); } while(status2 == G1_ATA_SR_DRQ); (void) IN8(G1_ATA_STATUS_REG); #if 0 //def LOG LOGFF("done\n"); #endif } void pio_stream_internal(GDS *my_gds) { #ifdef LOG LOGFF("%08X %08X %08X %08X\n", my_gds->param[2], my_gds->param[1], my_gds->param[0], my_gds->param[3]); #endif uint8_t status, status2; lba_tranlator(0, my_gds); do { transfer_loop(0, my_gds); if(my_gds->cmd_abort == 0) { status = IN8(G1_ATA_STATUS_REG); } else { read_abort: my_gds->cmd_abort = 2; status = gd_read_abort(0, my_gds); } status2 = status & G1_ATA_SR_DRQ; if (status2 == G1_ATA_SR_DRQ) { OUT8(G1_ATA_CTL, 2); int len = 2048; /*if ((my_gds->requested - my_gds->transfered) >= 0xF000) { len = 0xF000; } else { len = my_gds->requested - my_gds->transfered; }*/ while (len >= 1) { if (len == 512) { OUT8(G1_ATA_CTL, 0); } if (len && !(len % 512)) { do {} while((IN8(G1_ATA_ALTSTATUS) & (G1_ATA_SR_BSY | G1_ATA_SR_DRQ)) != G1_ATA_SR_DRQ); } if(my_gds->piosize > 1) { *my_gds->pioaddr = IN16(G1_ATA_DATA); my_gds->pioaddr++; my_gds->transfered += 2; my_gds->piosize -= 2; len -= 2; } else { if(my_gds->callback != 0) { void (*callback)() = (void (*)())(my_gds->callback); callback(my_gds->callback_param); } while (my_gds->piosize == 0) { if(my_gds->cmd_abort != 0) goto read_abort; Exit_to_game(); } } } } //g1_ata_wait_nbsy(my_gds); } while(status2 == G1_ATA_SR_DRQ); (void) IN8(G1_ATA_STATUS_REG); } void gd_dmaread_stream2(uint32_t *params, GDS *my_gds) { #ifdef LOG LOGFF("%08X %d %d %08X\n", params[2], params[1], params[0], params[3]); #endif /* dma abort, stop cdda unlock gdsys */ dma_abort(my_gds); if (lock_gdsys(1)) { #if 0 //def LOG LOGFF("ERROR, can't lock gdsys\n"); #endif my_gds->gd_cmd_err = GDCMD_GDSYS_LOCKED; return; } my_gds->gd_cmd_stat = CMD_STAT_WAITING; my_gds->requested = params[1] << 11; lba_tranlator(1, my_gds); my_gds->dma_in_progress = 1; transfer_loop(1, my_gds); my_gds->transfered = IN32(G1_ATA_DMA_LEND); if(my_gds->cmd_abort != 0) { if ( !my_gds->requested && (my_gds->transfered + 512) < IN32(G1_ATA_DMA_LENGTH)) { wait_gddma_irq(my_gds); my_gds->dma_in_progress = 0; } else { my_gds->cmd_abort = 2; uint8_t stat = gd_read_abort(0, my_gds); if (stat & G1_ATA_SR_ERR) { if (IN8(G1_ATA_ERROR) & G1_ATA_ER_ABRT) { return; } } wait_gddma_irq(my_gds); (void) IN8(G1_ATA_STATUS_REG); g1_ata_wait_bsydrq(my_gds); return; } } (void) IN8(G1_ATA_STATUS_REG); dma_abort(my_gds); /* g1_ata_wait_bsydrq(my_gds); lock_gdsys(0);*/ } void gd_dmaread(uint32_t *params, GDS *my_gds) /* _8c001b2c */ { #ifdef LOG LOGFF("%08X %d %d %d\n", params[2], params[1], params[0], params[3]); #endif dma_abort(my_gds); if (lock_gdsys(1)) { my_gds->gd_cmd_err = GDCMD_GDSYS_LOCKED; return; } OUT32(G1_ATA_DMA_PRO, G1_ATA_DMA_PRO_SYSMEM); OUT32(G1_ATA_DMA_ADDRESS, params[2]); OUT32(G1_ATA_DMA_LENGTH, params[1] << 11); OUT8(G1_ATA_DMA_DIRECTION, 1); lba_tranlator(1, my_gds); my_gds->dma_in_progress = 1; OUT8(G1_ATA_DMA_ENABLE, 1); OUT8(G1_ATA_DMA_STATUS, 1); transfer_loop(1, my_gds); /* if (my_gds->cmd_abort != 0) { if ((my_gds->transfered + 2048) > IN32(G1_ATA_DMA_LENGTH)) { wait_gddma_irq(my_gds); } else { my_gds->cmd_abort = 2; uint8_t stat = gd_read_abort(0, my_gds); if (stat & G1_ATA_SR_ERR) { if (IN8(G1_ATA_ERROR) & G1_ATA_ER_ABRT) return; } wait_gddma_irq(my_gds); (void) IN8(G1_ATA_STATUS_REG); g1_ata_wait_bsydrq(my_gds); return; } }*/ (void) IN8(G1_ATA_STATUS_REG); dma_abort(my_gds); /* g1_ata_wait_bsydrq(my_gds); lock_gdsys(0);*/ } /* void gd_set_mode() { #ifdef LOG LOGFF(0); #endif } void gd_req_mode() { #ifdef LOG LOGFF(0); #endif } */ /* void dummy_read(GDS *my_gds) { OUT8(G1_ATA_DEVICE_SELECT, 0xF0); do {} while ((IN8(G1_ATA_STATUS_REG) & (G1_ATA_SR_DRDY | G1_ATA_SR_BSY)) != G1_ATA_SR_DRDY); OUT8(G1_ATA_CTL, 0); OUT8(G1_ATA_SECTOR_COUNT, 1); OUT8(G1_ATA_LBA_LOW, 0xff); OUT8(G1_ATA_LBA_MID, 0); OUT8(G1_ATA_LBA_HIGH, 0); OUT8(G1_ATA_COMMAND_REG, ATA_CMD_READ_SECTORS); transfer_loop(0, my_gds); do {} while((IN8(G1_ATA_ALTSTATUS) & (G1_ATA_SR_BSY | G1_ATA_SR_DRQ)) != G1_ATA_SR_DRQ); for (int i = 0; i < 256; i++) { (void) IN16(G1_ATA_DATA); } g1_ata_wait_nbsy(my_gds); transfer_loop(0, my_gds); }*/ /* void gd_cd_open_tray() { #ifdef LOG LOGFF("WARNING\n"); #endif } */ /* void gd_gettoc() { #ifdef LOG LOGFF("WARNING\n"); #endif } */ void gd_gettoc2(uint32_t *params, GDS *my_gds) { #ifdef LOG LOGFF(0); #endif if(my_gds->drv_media == TYPE_GDROM /*&& !params[0]*/) { if (!params[0]) { toc_t *toc = (toc_t *) params[1]; toc->entry[0] = my_gds->TOC.entry[0]; toc->entry[1] = my_gds->TOC.entry[1]; for (int i = 2; i < 99; i++) { toc->entry[i] = (uint32_t) -1; } toc->first = 0x41010000; toc->last = 0x01020000; toc->leadout_sector = 0x01001A2C; } else { uint8_t *src = (uint8_t *) my_gds->TOC.entry; uint8_t *dst = (uint8_t *) params[1]; for (int i = 0; i < 408; i++) { dst[i] = src[i]; } } return; } my_gds->gd_cmd_stat = CMD_STAT_ERROR; } void gd_gettracks(int *param, GDS *my_gds) { #ifdef LOG LOGFF(0); #endif //dummy_read(my_gds); uint8_t *buf = (uint8_t *) param[2]; uint32_t lba = my_gds->TOC.leadout_sector; buf[0] = STAT_PAUSE; buf[1] = 0; buf[2] = 1; buf[3] = (lba >> 16) & 0xFF; buf[4] = (lba >> 8) & 0xFF; buf[5] = lba & 0xFF; my_gds->transfered = 6; } void gd_getstat(uint32_t *params, GDS *my_gds) { //dummy_read(my_gds); uint8_t track = ((uint8_t *) &my_gds->currentLBA)[3]; uint32_t lba = my_gds->currentLBA & 0xFFFFFF; *((uint32_t *)params[0]) = STAT_PAUSE; *((uint32_t *)params[1]) = track; *((uint32_t *)params[2]) = lba + 0x41000000; *((uint32_t *)params[3]) = 1; } static uint8_t scd_all[100] = { 0x00, 0x15, 0x00, 0x64, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x00, 0x40, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 }; static uint8_t scd_media[24] = { 0x00, 0x15, 0x00, 0x18, 0x02, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00 }; static uint8_t scd_isrc[24] = { 0x00, 0x15, 0x00, 0x18, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00 }; void gd_getscd(uint32_t *param, GDS *my_gds) { #ifdef LOG LOGFF("%08X %08X %08X\n", param[0], param[1], param[2]); #endif //dummy_read(my_gds); uint8_t *buf = (uint8_t *)param[2]; switch(param[0] & 0xF) { case SCD_REQ_ALL_SUBCODE: { for (int i = 0; i < scd_all[SCD_DATA_SIZE_INDEX]; i++) { buf[i] = scd_all[i]; } buf[1] = SCD_AUDIO_STATUS_PAUSED; my_gds->transfered = scd_all[SCD_DATA_SIZE_INDEX]; break; } case SCD_REQ_Q_SUBCODE: { uint8_t track = ((uint8_t*) &my_gds->currentLBA)[3]; uint32_t lba = my_gds->currentLBA & 0xFFFFFF; uint32_t offset = lba - 150; buf[0] = 0x00; // Reserved buf[1] = SCD_AUDIO_STATUS_NO_INFO; // Audio Status buf[2] = 0x00; // DATA Length MSB buf[3] = 0x0E; // DATA Length LSB buf[4] = 0x41; // Track flags (CTRL and ADR) buf[5] = track; // Track NO buf[6] = track; // 00: Pause area 01-99: Index number buf[7] = (uint8_t)(offset >> 16); buf[8] = (uint8_t)(offset >> 8); buf[9] = (uint8_t) offset; buf[10] = 0x00; // Reserved buf[11] = (uint8_t)(lba >> 16); buf[12] = (uint8_t)(lba >> 8); buf[13] = (uint8_t) lba; my_gds->transfered = 0xE; break; } case SCD_REQ_MEDIA_CATALOG: { for (int i = 0; i < scd_media[SCD_DATA_SIZE_INDEX]; i++) { buf[i] = scd_media[i]; } // buf[0] = 0x00; // Reserved buf[1] = SCD_AUDIO_STATUS_PAUSED; // Audio Status // buf[2] = 0x00; // DATA Length MSB // buf[3] = 0x18; // DATA Length LSB // buf[4] = 0x02; // Format Code my_gds->transfered = scd_media[SCD_DATA_SIZE_INDEX]; break; } case SCD_REQ_ISRC: { for (int i = 0; i < scd_isrc[SCD_DATA_SIZE_INDEX]; i++) { buf[i] = scd_isrc[i]; } // buf[0] = 0x00; // Reserved buf[1] = SCD_AUDIO_STATUS_PAUSED; // Audio Status // buf[2] = 0x00; // DATA Length MSB // buf[3] = 0x18; // DATA Length LSB // buf[4] = 0x03; // Format Code my_gds->transfered = scd_isrc[SCD_DATA_SIZE_INDEX]; break; } // case SCD_REQ_RESERVED: // break; default: break; } if (res_count > 1) { my_gds->gd_cmd_err = GDCMD_NOT_INITED; } } void gd_init(int *param, GDS *my_gds) { (void) param; #ifdef LOG scif_init(); LOGFF("dt = %02X\n", my_gds->drv_media); #endif if (disc_id[0]) { my_gds->dtrkLBA[1] = disc_id[disc_id[0]]; } my_gds->cmd_abort = 0; my_gds->requested = 0; dma_abort(my_gds); uint8_t stat = IN8(G1_ATA_STATUS_REG); if (stat & G1_ATA_SR_BSY) { gd_cmd_abort(my_gds); } else if (stat & G1_ATA_SR_DRQ) { if (IN32(EXT_INT_STAT) & 1) { (void) IN8(G1_ATA_STATUS_REG); } gd_read_abort(0, my_gds); } disc_id[0] = 0; my_gds->need_reinit = 0; my_gds->drv_media = TYPE_GDROM; my_gds->gd_cmd_err = 0; my_gds->gd_cmd_err2 = 0; my_gds->transfered = 0x198; my_gds->ata_status = 0; } typedef struct { uint32_t off; uint32_t sz; } fl_inf; static fl_inf fl_parts[5] = { { 0x1a000, 0x02000 }, { 0x18000, 0x02000 }, { 0x1c000, 0x04000 }, { 0x10000, 0x08000 }, { 0 , 0x10000 } }; int flashrom_info(int part, uint32_t *buffer) { #ifdef LOG LOGFF(0); #endif if (part < 0 || part >= 5) return -1; buffer[0] = fl_parts[part].off; buffer[1] = fl_parts[part].sz; return 0; } uint8_t region_str[3][6] = { { "00000" }, { "00110" }, { "00211" } }; int flashrom_read(uint32_t offset, uint8_t *dst, uint32_t size) { #ifdef LOG LOGFF("%08X %d\n", offset, size); #endif if (flashrom_lock() != 0) return -1; uint8_t *src; if (offset == 0x1A000 && *((uint8_t *)0x8C000020) != 0) { src = region_str[*((uint8_t *)0x8C000020) - 1]; #ifdef LOG LOGF("%s\n", (char *) src); #endif } else { src = (uint8_t *) (0xA0200000 + offset); } for (; size; size--) { *dst++ = *src++; } flashrom_unlock(); return 0; } int gd_do_bioscall_tmp(int nu1, int nu2, int nu3, int cmd) { (void) nu1; (void) nu2; (void) nu3; switch (cmd) { case 0: return 0; break; case 1: case 4: return 4; break; default: break; } return -1; } static uint32_t saved_irq = 0; void hide_gd_vector(int restore) { uint32_t oldsr = irq_disable(); uint32_t reg = 0xA05F6904; uint32_t shift; uint32_t tmp; if (restore) { gd_vector2 = 0x8C0010F0; for (int i = 0; i < 3; i++) { shift = saved_irq; reg += 12; tmp = shift >> i; OUT32(reg, IN32(reg) | (tmp & 0x4000)); reg += 4; OUT32(reg, IN32(reg) | (tmp & 1)); } (void) IN32(reg); reg = 0xA05F6900; OUT32(reg, IN32(reg) & 0x4000); } else { gd_vector2 = (uint32_t) &gd_do_bioscall_tmp; tmp = 0; for (int i = 0; i < 3; i++) { reg += 12; tmp |= ((IN32(reg) & 0x4000) << i); OUT32(reg, IN32(reg) & 0xFFFFBFFF); reg += 4; tmp |= ((IN32(reg) & 1) << i); OUT32(reg, IN32(reg) & 0xFFFFFFFE); } (void) IN32(reg); saved_irq = tmp; gd_gdrom_syscall(0, 0, 0, 3); } irq_restore(oldsr); } /* int sys_do_bioscall(int param) { #ifdef LOG LOGFF("%d\n", param); #endif return 0; } */ static int req_id; int syBtCheckDisc() { #ifdef LOG LOGFF(0); #endif int disc = (int) disc_type; if (disc < 0) { gd_gdrom_syscall(0, 0, 0, 2); } switch (disc) { case -8: disc = 0; break; case -7: case -4: { static uint32_t stat[4]; (void) stat; int ret = gd_gdrom_syscall(req_id, stat, 0, 1); if (ret == CMD_STAT_NO_ACTIVE || ret == CMD_STAT_COMPLETED) { disc -= 1; } break; } case -6: break; case -5: { static uint32_t cmd[4] = { 45150, 7, 0x8C008100, 0 }; req_id = gd_gdrom_syscall(17, cmd, 0, 0); disc = -7; break; } case -3: break; case -2: { req_id = gd_gdrom_syscall(24, 0, 0, 0); disc = -4; break; } case -1: break; case 0: { hide_gd_vector(0); // hide display_cable |= 1; disc = -2; break; } } if (disc >= 0) { hide_gd_vector(1); // restore } disc_type = (short) disc; return disc; } #ifdef LOG void syBtExit(uint32_t pr, uint32_t *stack) { LOGFF("pr = %08X\n", pr); for (int i = 0; i < 32; i++) { if (i == 8 || i == 16 || i == 24) { LOGF("\n"); } LOGF("%08X ", stack[i]); } LOGF("\n"); } #else uint32_t reset_regs[12] = { 0xA05F6808, 0xA05F6820, 0xA05F6C14, 0xA05F7414, 0xA05F7814, 0xA05F7834, 0xA05F7854, 0xA05F7874, 0xA05F7C14, 0xFFA0001C, 0xFFA0002C, 0xFFA0003C }; void syBtExit() { //#ifdef LOG // LOGFF(0); //#endif flush_cache(); OUT32(0xFF000010, 0); OUT32(0xFF00001C, 0x929); uint32_t addr1 = 0xA05F6938; uint32_t addr2 = 0xFFD0000C; for (int i = 3; i; i--) { OUT32(addr1, 0); addr1 -= 4; OUT32(addr1, 0); addr1 -= 4; OUT32(addr1, 0); addr1 -= 8; OUT32(addr2, 0); addr2 -= 4; } OUT32(addr2, 0); (void) IN32(addr1); addr1 -= 8; (void) IN32(addr1); OUT32(0xA05F8044, (IN32(0xA05F8044) & 0xFFFFFFFE)); for (int i = 0; i < 12; i++) { OUT32(reset_regs[i], (IN32(reset_regs[i]) & 0xFFFFFFFE)); for (int j = 0; j < 127; j++) { if (!(IN32(reset_regs[i]) & 0xFFFFFFFE)) { break; } } } GDS *my_gds = get_GDS(); if (my_gds->dsLBA) { uint32_t *addr = (uint32_t *) 0x8C010000; my_gds->requested = ((my_gds->dsseccnt>>11)<<11)+2048; my_gds->transfered = 0; my_gds->param[0] = 150; my_gds->param[1] = (my_gds->dsseccnt >> 11)+1; my_gds->param[2] = (uint32_t) addr; my_gds->param[3] = 0; my_gds->dtrkLBA[0] = my_gds->dsLBA; lba_tranlator(0, my_gds); for (uint32_t j = 0; j < (my_gds->param[1]<<2); j++) { do {} while((IN8(G1_ATA_ALTSTATUS) & G1_ATA_SR_BSY)); do {} while(!(IN8(G1_ATA_STATUS_REG) & G1_ATA_SR_DRQ)); for (uint32_t i = 0; i < 256; i++) { ((uint16_t *)addr)[i+(j*256)] = IN16(G1_ATA_DATA); } } OUT8(G1_ATA_DEVICE_SELECT, 0x10); OUT8(G1_ATA_COMMAND_REG, 8); OUT8(G1_ATA_DEVICE_SELECT, 0); for (uint32_t i = 0; i < (my_gds->dsseccnt >> 2); i++) { if(addr[i] == 0xA05F74E4) addr[i] = 0xA05F74EC; } typedef void (*trampoline_func)(); trampoline_func trampoline = (trampoline_func) 0x8C010000; trampoline(); } OUT32(0xA05F6890, 0x7611); while(1); } #endif <file_sep>/include/network/http.h /** * \file http.h * \brief HTTP protocol * \date 2007-2014 * \author SWAT www.dc-swat.ru */ #ifndef _DS_HTTP_H #define _DS_HTTP_H #include <kos/net.h> #include <sys/socket.h> /* File systems */ int tcpfs_init(); void tcpfs_shutdown(); int httpfs_init(); void httpfs_shutdown(); /* DSN utils */ int dns_init(const uint8 *ip); int dns(const char *name, struct in_addr* addr); int ds_gethostbyname(const struct sockaddr_in * dnssrv, const char *name, uint8 *ipout); /* URL utils */ void _url_split(char *proto, int proto_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url); /* httpd server */ int httpd_init(int port); void httpd_shutdown(); #endif /* _DS_HTTP_H */<file_sep>/lib/SDL_image/Makefile # KallistiOS ##version## # # SDL_image Makefile # SWAT # FMT_INCS = -I$(KOS_BASE)/../kos-ports/include/jpeg \ -I$(KOS_BASE)/../kos-ports/include/png \ -I$(KOS_BASE)/../kos-ports/include/zlib FMTS = -DLOAD_BMP=1 -DLOAD_PNG=1 -DLOAD_TGA=1 -DLOAD_PNM=1 -DLOAD_GIF=1 \ -DLOAD_PCX=1 -DLOAD_JPG=1 -DLOAD_LBM=1 -DLOAD_XCF=1 -DLOAD_XPM=1 \ -DLOAD_XV=1 -DLOAD_PVR=1 #-DLOAD_WEBP=1 KOS_CFLAGS += $(FMT_INCS) $(FMTS) $(KOS_CSTD) -I./ -I../../include/SDL #KOS_CFLAGS += -DDEBUG_IMGLIB=1 TARGET = ../libSDL_image_1.2.12.a OBJS = \ IMG.o \ IMG_bmp.o \ IMG_gif.o \ IMG_jpg.o \ IMG_lbm.o \ IMG_pcx.o \ IMG_png.o \ IMG_pnm.o \ IMG_tga.o \ IMG_tif.o \ IMG_xcf.o \ IMG_xpm.o \ IMG_xv.o \ IMG_webp.o \ IMG_pvr.o #IMG_ImageIO.o include ../../sdk/Makefile.library <file_sep>/lib/SDL_gui/Surface.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" #include "SDL_gfxBlitFunc.h" #include "SDL_gfxPrimitives.h" extern "C" { SDL_Surface *SDL_ImageLoad(const char *filename, SDL_Rect *selection); } GUI_Surface::~GUI_Surface(void) { if (surface) SDL_FreeSurface(surface); } GUI_Surface::GUI_Surface(const char *aname, SDL_Surface *image) : GUI_Object(aname) { //assert(image != NULL); if(image) surface = image; } GUI_Surface::GUI_Surface(const char *fn) : GUI_Object(fn) { surface = IMG_Load(fn); if (surface == NULL) { /*throw*/ GUI_Exception("Failed to load image \"%s\" (%s)", fn, IMG_GetError()); }/* else { SDL_Surface *tmp = SDL_DisplayFormat(surface); SDL_FreeSurface(surface); surface = tmp; }*/ } GUI_Surface::GUI_Surface(const char *fn, SDL_Rect *selection) : GUI_Object(fn) { surface = SDL_ImageLoad(fn, selection); if (surface == NULL) { /*throw*/ GUI_Exception("Failed to load image \"%s\" (%s)", fn, IMG_GetError()); }/* else { SDL_Surface *tmp = SDL_DisplayFormat(surface); SDL_FreeSurface(surface); surface = tmp; }*/ } GUI_Surface::GUI_Surface(const char *aname, int f, int w, int h, int d, int rm, int bm, int gm, int am) : GUI_Object(aname) { surface = SDL_AllocSurface(f, w, h, d, rm, bm, gm, am); if (surface == NULL) /*throw*/ GUI_Exception("Failed to allocate surface (f=%d, w=%d, h=%d, d=%d)", f, w, h, d); } void GUI_Surface::Blit(SDL_Rect *src_r, GUI_Surface *dst, SDL_Rect *dst_r) { SDL_BlitSurface(surface, src_r, dst->surface, dst_r); } void GUI_Surface::UpdateRect(int x, int y, int w, int h) { SDL_UpdateRect(surface, x, y, w, h); } void GUI_Surface::UpdateRects(int n, SDL_Rect *rects) { SDL_UpdateRects(surface, n, rects); } void GUI_Surface::Fill(SDL_Rect *r, Uint32 c) { SDL_FillRect(surface, r, c); } void GUI_Surface::BlitRGBA(SDL_Rect * srcrect, GUI_Surface * dst, SDL_Rect * dstrect) { SDL_gfxBlitRGBA(surface, srcrect, dst->surface, dstrect); } void GUI_Surface::Pixel(Sint16 x, Sint16 y, Uint32 c) { pixelColor(surface, x, y, c); } void GUI_Surface::Line(Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 c) { lineColor(surface, x1, y1, x2, y2, c); } void GUI_Surface::LineAA(Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 c) { aalineColor(surface, x1, y1, x2, y2, c); } void GUI_Surface::LineH(Sint16 x1, Sint16 x2, Sint16 y, Uint32 c) { hlineColor(surface, x1, x2, y, c); } void GUI_Surface::LineV(Sint16 x1, Sint16 y1, Sint16 y2, Uint32 c) { vlineColor(surface, x1, y1, y2, c); } void GUI_Surface::ThickLine(Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint8 width, Uint32 c) { thickLineColor(surface, x1, y1, x2, y2, width, c); } void GUI_Surface::Rectagle(Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 c) { rectangleColor(surface, x1, y1, x2, y2, c); } void GUI_Surface::RectagleRouded(Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 rad, Uint32 c) { roundedRectangleColor(surface, x1, y1, x2, y2, rad, c); } void GUI_Surface::Box(Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 c) { boxColor(surface, x1, y1, x2, y2, c); } void GUI_Surface::BoxRouded(Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 rad, Uint32 c) { roundedBoxColor(surface, x1, y1, x2, y2, rad, c); } void GUI_Surface::Circle(Sint16 x, Sint16 y, Sint16 rad, Uint32 c) { circleColor(surface, x, y, rad, c); } void GUI_Surface::CircleAA(Sint16 x, Sint16 y, Sint16 rad, Uint32 c) { aacircleColor(surface, x, y, rad, c); } void GUI_Surface::CircleFill(Sint16 x, Sint16 y, Sint16 rad, Uint32 c) { filledCircleColor(surface, x, y, rad, c); } void GUI_Surface::Arc(Sint16 x, Sint16 y, Sint16 rad, Sint16 start, Sint16 end, Uint32 c) { arcColor(surface, x, y, rad, start, end, c); } void GUI_Surface::Ellipse(Sint16 x, Sint16 y, Sint16 rx, Sint16 ry, Uint32 c) { ellipseColor(surface, x, y, rx, ry, c); } void GUI_Surface::EllipseAA(Sint16 x, Sint16 y, Sint16 rx, Sint16 ry, Uint32 c) { aaellipseColor(surface, x, y, rx, ry, c); } void GUI_Surface::EllipseFill(Sint16 x, Sint16 y, Sint16 rx, Sint16 ry, Uint32 c) { filledEllipseColor(surface, x, y, rx, ry, c); } void GUI_Surface::Pie(Sint16 x, Sint16 y, Sint16 rad, Sint16 start, Sint16 end, Uint32 c) { pieColor(surface, x, y, rad, start, end, c); } void GUI_Surface::PieFill(Sint16 x, Sint16 y, Sint16 rad, Sint16 start, Sint16 end, Uint32 c) { filledPieColor(surface, x, y, rad, start, end, c); } void GUI_Surface::Trigon(Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 x3, Sint16 y3, Uint32 c) { trigonColor(surface, x1, y1, x2, y2, x3, y3, c); } void GUI_Surface::TrigonAA(Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 x3, Sint16 y3, Uint32 c) { aatrigonColor(surface, x1, y1, x2, y2, x3, y3, c); } void GUI_Surface::TrigonFill(Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 x3, Sint16 y3, Uint32 c) { filledTrigonColor(surface, x1, y1, x2, y2, x3, y3, c); } void GUI_Surface::Polygon(const Sint16 * vx, const Sint16 * vy, int n, Uint32 c) { polygonColor(surface, vx, vy, n, c); } void GUI_Surface::PolygonAA(const Sint16 * vx, const Sint16 * vy, int n, Uint32 c) { aapolygonColor(surface, vx, vy, n, c); } void GUI_Surface::PolygonFill(const Sint16 * vx, const Sint16 * vy, int n, Uint32 c) { filledPolygonColor(surface, vx, vy, n, c); } void GUI_Surface::PolygonTextured(const Sint16 * vx, const Sint16 * vy, int n, GUI_Surface *texture, int texture_dx, int texture_dy) { texturedPolygon(surface, vx, vy, n, texture->surface, texture_dx, texture_dy); } void GUI_Surface::Bezier(const Sint16 * vx, const Sint16 * vy, int n, int s, Uint32 c) { bezierColor(surface, vx, vy, n, s, c); } int GUI_Surface::GetWidth(void) { return surface->w; } int GUI_Surface::GetHeight(void) { return surface->h; } SDL_Surface *GUI_Surface::GetSurface(void) { return surface; } Uint32 GUI_Surface::MapRGB(int r, int g, int b) { return SDL_MapRGB(surface->format, r, g, b); } Uint32 GUI_Surface::MapRGBA(int r, int g, int b, int a) { return SDL_MapRGBA(surface->format, r, g, b, a); } int GUI_Surface::IsDoubleBuffered(void) { return (surface->flags & SDL_DOUBLEBUF) != 0; } int GUI_Surface::IsHardware(void) { return (surface->flags & SDL_HWSURFACE) != 0; } void GUI_Surface::Flip(void) { SDL_Flip(surface); } void GUI_Surface::DisplayFormat(void) { SDL_Surface *temp = SDL_DisplayFormat(surface); if (!temp) /*throw*/ GUI_Exception("Failed to format surface for display: %s", SDL_GetError()); SDL_FreeSurface(surface); surface = temp; } void GUI_Surface::SetAlpha(Uint32 flag, Uint8 alpha) { SDL_SetAlpha(surface, flag, alpha); } void GUI_Surface::SetColorKey(Uint32 c) { if (SDL_SetColorKey(surface, SDL_RLEACCEL | SDL_SRCCOLORKEY, c) < 0) /*throw*/ GUI_Exception("Failed to set color key for surface: %s", SDL_GetError()); } void GUI_Surface::SaveBMP(const char *filename) { SDL_SaveBMP(surface, filename); } void GUI_Surface::SavePNG(const char *filename) { SDL_SavePNG(surface, filename); } extern "C" { void GUI_SurfaceSaveBMP(GUI_Surface *src, const char *filename) { src->SaveBMP(filename); } void GUI_SurfaceSavePNG(GUI_Surface *src, const char *filename) { src->SavePNG(filename); } GUI_Surface *GUI_SurfaceLoad(const char *fn) { return new GUI_Surface(fn); } GUI_Surface *GUI_SurfaceLoad_Rect(const char *fn, SDL_Rect *selection) { return new GUI_Surface(fn, selection); } void GUI_SurfaceFlip(GUI_Surface *src) { src->Flip(); } GUI_Surface *GUI_SurfaceCreate(const char *aname, int f, int w, int h, int d, int rm, int gm, int bm, int am) { return new GUI_Surface(aname, f, w, h, d, rm, gm, bm, am); } GUI_Surface *GUI_SurfaceFrom(const char *aname, SDL_Surface *src) { return new GUI_Surface(aname, src); } void GUI_SurfaceBlit(GUI_Surface *src, SDL_Rect *src_r, GUI_Surface *dst, SDL_Rect *dst_r) { src->Blit(src_r, dst, dst_r); } void GUI_SurfaceUpdateRects(GUI_Surface *surface, int n, SDL_Rect *rects) { surface->UpdateRects(n, rects); } void GUI_SurfaceUpdateRect(GUI_Surface *surface, int x, int y, int w, int h) { surface->UpdateRect(x,y,w,h); } void GUI_SurfaceFill(GUI_Surface *surface, SDL_Rect *r, Uint32 c) { surface->Fill(r, c); } int GUI_SurfaceGetWidth(GUI_Surface *surface) { return surface->GetWidth(); } int GUI_SurfaceGetHeight(GUI_Surface *surface) { return surface->GetHeight(); } Uint32 GUI_SurfaceMapRGB(GUI_Surface *surface, int r, int g, int b) { return surface->MapRGB(r, g, b); } Uint32 GUI_SurfaceMapRGBA(GUI_Surface *surface, int r, int g, int b, int a) { return surface->MapRGBA(r, g, b, a); } SDL_Surface *GUI_SurfaceGet(GUI_Surface *surface) { return surface->GetSurface(); } void GUI_SurfaceSetAlpha(GUI_Surface *surface, Uint32 flag, Uint8 alpha) { surface->SetAlpha(flag, alpha); } void GUI_SurfaceBlitRGBA(GUI_Surface *surface, SDL_Rect * srcrect, GUI_Surface * dst, SDL_Rect * dstrect) { surface->BlitRGBA(srcrect, dst, dstrect); } void GUI_SurfacePixel(GUI_Surface *surface, Sint16 x, Sint16 y, Uint32 c) { surface->Pixel(x, y, c); } void GUI_SurfaceLine(GUI_Surface *surface, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 c) { surface->Line(x1, y1, x2, y2, c); } void GUI_SurfaceLineAA(GUI_Surface *surface, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 c) { surface->LineAA(x1, y1, x2, y2, c); } void GUI_SurfaceLineH(GUI_Surface *surface, Sint16 x1, Sint16 x2, Sint16 y, Uint32 c) { surface->LineH(x1, x2, y, c); } void GUI_SurfaceLineV(GUI_Surface *surface, Sint16 x1, Sint16 y1, Sint16 y2, Uint32 c) { surface->LineV(x1, y1, y2, c); } void GUI_SurfaceThickLine(GUI_Surface *surface, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint8 width, Uint32 c) { surface->ThickLine(x1, y1, x2, y2, width, c); } void GUI_SurfaceRectagle(GUI_Surface *surface, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 c) { surface->Rectagle(x1, y1, x2, y2, c); } void GUI_SurfaceRectagleRouded(GUI_Surface *surface, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 rad, Uint32 c) { surface->RectagleRouded(x1, y1, x2, y2, rad, c); } void GUI_SurfaceBox(GUI_Surface *surface, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 c) { surface->Box(x1, y1, x2, y2, c); } void GUI_SurfaceBoxRouded(GUI_Surface *surface, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 rad, Uint32 c) { surface->BoxRouded(x1, y1, x2, y2, rad, c); } void GUI_SurfaceCircle(GUI_Surface *surface, Sint16 x, Sint16 y, Sint16 rad, Uint32 c) { surface->Circle(x, y, rad, c); } void GUI_SurfaceCircleAA(GUI_Surface *surface, Sint16 x, Sint16 y, Sint16 rad, Uint32 c) { surface->CircleAA(x, y, rad, c); } void GUI_SurfaceCircleFill(GUI_Surface *surface, Sint16 x, Sint16 y, Sint16 rad, Uint32 c) { surface->CircleFill(x, y, rad, c); } void GUI_SurfaceArc(GUI_Surface *surface, Sint16 x, Sint16 y, Sint16 rad, Sint16 start, Sint16 end, Uint32 c) { surface->Arc(x, y, rad, start, end, c); } void GUI_SurfaceEllipse(GUI_Surface *surface, Sint16 x, Sint16 y, Sint16 rx, Sint16 ry, Uint32 c) { surface->Ellipse(x, y, rx, ry, c); } void GUI_SurfaceEllipseAA(GUI_Surface *surface, Sint16 x, Sint16 y, Sint16 rx, Sint16 ry, Uint32 c) { surface->EllipseAA(x, y, rx, ry, c); } void GUI_SurfaceEllipseFill(GUI_Surface *surface, Sint16 x, Sint16 y, Sint16 rx, Sint16 ry, Uint32 c) { surface->EllipseFill(x, y, rx, ry, c); } void GUI_SurfacePie(GUI_Surface *surface, Sint16 x, Sint16 y, Sint16 rad, Sint16 start, Sint16 end, Uint32 c) { surface->Pie(x, y, rad, start, end, c); } void GUI_SurfacePieFill(GUI_Surface *surface, Sint16 x, Sint16 y, Sint16 rad, Sint16 start, Sint16 end, Uint32 c) { surface->PieFill(x, y, rad, start, end, c); } void GUI_SurfaceTrigon(GUI_Surface *surface, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 x3, Sint16 y3, Uint32 c) { surface->Trigon(x1, y1, x2, y2, x3, y3, c); } void GUI_SurfaceTrigonAA(GUI_Surface *surface, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 x3, Sint16 y3, Uint32 c) { surface->TrigonAA(x1, y1, x2, y2, x3, y3, c); } void GUI_SurfaceTrigonFill(GUI_Surface *surface, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 x3, Sint16 y3, Uint32 c) { surface->TrigonFill(x1, y1, x2, y2, x3, y3, c); } void GUI_SurfacePolygon(GUI_Surface *surface, const Sint16 * vx, const Sint16 * vy, int n, Uint32 c) { surface->Polygon(vx, vy, n, c); } void GUI_SurfacePolygonAA(GUI_Surface *surface, const Sint16 * vx, const Sint16 * vy, int n, Uint32 c) { surface->PolygonAA(vx, vy, n, c); } void GUI_SurfacePolygonFill(GUI_Surface *surface, const Sint16 * vx, const Sint16 * vy, int n, Uint32 c) { surface->PolygonFill(vx, vy, n, c); } void GUI_SurfacePolygonTextured(GUI_Surface *surface, const Sint16 * vx, const Sint16 * vy, int n, GUI_Surface *texture, int texture_dx, int texture_dy) { surface->PolygonTextured(vx, vy, n, texture, texture_dx, texture_dy); } void GUI_SurfaceBezier(GUI_Surface *surface, const Sint16 * vx, const Sint16 * vy, int n, int s, Uint32 c) { surface->Bezier(vx, vy, n, s, c); } }; <file_sep>/firmware/isoldr/loader/kos/src/printf.c /* printf.c $Id: printf.c,v 1.3 2002/06/29 12:57:04 quad Exp $ DESCRIPTION An implementation of printf. CREDIT I stole it from somewhere. I can't remember where though. Sorry! TODO Cleanup the printf implementation. See if it's possible to compress its size - remove textualization modes we don't need. */ #include <arch/types.h> #include <string.h> #include <stdio.h> #define do_div(n, base) ({ int32 __res; __res = ((unsigned long) n) % (unsigned) base; n = ((unsigned long) n) / (unsigned) base; __res; }) static int32 skip_atoi (const char **s) { int32 i; i = 0; while (check_digit (**s)) i = i*10 + *((*s)++) - '0'; return i; } char* printf_number (char *str, long num, int32 base, int32 size, int32 precision, int32 type) { int32 i; char c; char sign; char tmp[66]; const char *digits = "0123456789abcdefghijklmnopqrstuvwxyz"; if (type & N_LARGE) digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; if (type & N_LEFT) type &= ~N_ZEROPAD; if (base < 2 || base > 36) return 0; c = (type & N_ZEROPAD) ? '0' : ' '; sign = 0; if (type & N_SIGN) { if (num < 0) { sign = '-'; num = -num; size--; } else if (type & N_PLUS) { sign = '+'; size--; } else if (type & N_SPACE) { sign = ' '; size--; } } if (type & N_SPECIAL) { if (base == 16) size -= 2; else if (base == 8) size--; } i = 0; if (num == 0) tmp[i++] = '0'; else while (num != 0) tmp[i++] = digits[do_div (num,base)]; if (i > precision) precision = i; size -= precision; if (!(type & (N_ZEROPAD + N_LEFT))) { while (size-- > 0) *str++ = ' '; } if (sign) *str++ = sign; if (type & N_SPECIAL) { if (base == 8) { *str++ = '0'; } else if (base == 16) { *str++ = '0'; *str++ = digits[33]; } } if (!(type & N_LEFT)) { while (size-- > 0) *str++ = c; } while (i < precision--) *str++ = '0'; while (i-- > 0) *str++ = tmp[i]; while (size-- > 0) *str++ = ' '; return str; } int vsnprintf (char *buf, int size, const char *fmt, va_list args) { int len; unsigned long num; int i; int base; char *str; const char *s; int flags; /* NOTE: Flags to printf_number (). */ int field_width; /* NOTE: Width of output field. */ int precision; /* NOTE: min. # of digits for integers; max number of chars for from string. */ int qualifier; /* NOTE: 'h', 'l', or 'L' for integer fields. */ for (str = buf; *fmt && ((str - buf) < (size - 1)); ++fmt) { /* STAGE: If it's not specifying an option, just pass it on through. */ if (*fmt != '%') { *str++ = *fmt; continue; } /* STAGE: Process the flags. */ flags = 0; repeat: ++fmt; /* NOTE: This also skips first '%' */ switch (*fmt) { case '-' : flags |= N_LEFT; goto repeat; case '+' : flags |= N_PLUS; goto repeat; case ' ' : flags |= N_SPACE; goto repeat; case '#' : flags |= N_SPECIAL; goto repeat; case '0' : flags |= N_ZEROPAD; goto repeat; } /* STAGE: Get field width. */ field_width = -1; if (check_digit (*fmt)) { field_width = skip_atoi (&fmt); } else if (*fmt == '*') { ++fmt; /* STAGE: Specified on the next argument. */ field_width = va_arg (args, int); if (field_width < 0) { field_width = -field_width; flags |= N_LEFT; } } /* STAGE: Get the precision. */ precision = -1; if (*fmt == '.') { ++fmt; if (check_digit (*fmt)) { precision = skip_atoi (&fmt); } else if (*fmt == '*') { ++fmt; /* STAGE: Specified on the next argument */ precision = va_arg (args, int); } /* STAGE: Paranoia on the precision value. */ if (precision < 0) precision = 0; } /* STAGE: Get the conversion qualifier. */ qualifier = -1; if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L') { qualifier = *fmt; ++fmt; } /* NOTE: The default base. */ base = 10; /* STAGE: Handle all the other formatting types. */ switch (*fmt) { /* STAGE: Character type. */ case 'c' : { if (!(flags & N_LEFT)) { while (--field_width > 0) *str++ = ' '; } *str++ = (unsigned char) va_arg (args, int); while (--field_width > 0) *str++ = ' '; continue; } /* STAGE: String type. */ case 's' : { s = va_arg (args, char *); if (!s) s = "<NULL>"; len = strnlen (s, precision); if (!(flags & N_LEFT)) { while (len < field_width--) *str++ = ' '; } for (i = 0; i < len; ++i) *str++ = *s++; while (len < field_width--) *str++ = ' '; continue; } case 'p' : { if (field_width == -1) { field_width = 2 * sizeof (void *); flags |= N_ZEROPAD; } str = printf_number (str, (unsigned long) va_arg (args, void *), 16, field_width, precision, flags); continue; } case 'n' : { if (qualifier == 'l') { long *ip; ip = va_arg (args, long *); *ip = (str - buf); } else { int *ip; ip = va_arg (args, int *); *ip = (str - buf); } continue; } /* NOTE: Integer number formats - set up the flags and "break". */ /* STAGE: Octal. */ case 'o' : base = 8; break; /* STAGE: Uppercase hexidecimal. */ case 'X' : flags |= N_LARGE; base = 16; break; /* STAGE: Lowercase hexidecimal. */ case 'x' : base = 16; break; /* STAGE: Signed decimal/integer. */ case 'd' : case 'i' : flags |= N_SIGN; /* STAGE: Unsigned decimal/integer. */ case 'u' : break; default : { if (*fmt != '%') *str++ = '%'; if (*fmt) *str++ = *fmt; else --fmt; continue; } } /* STAGE: Handle number formats with the various modifying qualifiers. */ if (qualifier == 'l') { num = va_arg (args, unsigned long); } else if (qualifier == 'h') { /* NOTE: The int16 should work, but the compiler promotes the datatype and complains if I don't handle it directly. */ if (flags & N_SIGN) { // num = va_arg (args, int16); num = va_arg (args, int32); } else { // num = va_arg (args, uint16); num = va_arg (args, uint32); } } else if (flags & N_SIGN) { num = va_arg (args, int); } else { num = va_arg (args, unsigned int); } /* STAGE: And after all that work, actually convert the integer into text. */ str = printf_number (str, num, base, field_width, precision, flags); } *str = '\0'; return str - buf; } /* int snprintf (char *buf, int size, const char *fmt, ...) { va_list args; int i; va_start (args, fmt); i = vsnprintf (buf,size,fmt,args); va_end (args); return i; } */<file_sep>/modules/ffmpeg/xvid.c #include "libavcodec/avcodec.h" #include "libavformat/avformat.h" #include "xvid.h" typedef struct context { xvid_dec_create_t dec_param; xvid_dec_frame_t frame; xvid_dec_stats_t stats; xvid_gbl_init_t param; } context_t; static int decode_init(AVCodecContext * avctx) { context_t * ctx = (context_t *) avctx->priv_data; int w, h; ctx->param.version = XVID_VERSION; ctx->param.cpu_flags = 0; ctx->param.debug = XVID_DEBUG_DEBUG; if(xvid_global(NULL, XVID_GBL_INIT, &ctx->param, NULL)) { printf("xvid_decode_init: error\n"); return -1; } ctx->dec_param.version = XVID_VERSION; w = ctx->dec_param.width = avctx->width; h = ctx->dec_param.height = avctx->height; if (xvid_decore(NULL, XVID_DEC_CREATE, &ctx->dec_param, NULL)) return -1; /* w = avctx->width = ctx->dec_param.width; */ /* h = avctx->height = ctx->dec_param.height; */ printf("xvid_decode_init : %dx%d\n", avctx->width, avctx->height); ctx->frame.version = XVID_VERSION; ctx->frame.general = XVID_LOWDELAY; /* ? */ ctx->stats.version = XVID_VERSION; ctx->frame.output.csp = XVID_CSP_INTERNAL; /* ctx->frame.output.csp = XVID_CSP_I420; */ /* ctx->frame.output.plane[0] = malloc(w*h); */ /* ctx->frame.output.stride[0] = w; */ /* ctx->frame.output.plane[1] = malloc(w*h/4); */ /* ctx->frame.output.stride[1] = w/4; */ /* ctx->frame.output.plane[2] = malloc(w*h/4); */ /* ctx->frame.output.stride[2] = w/4; */ /* ctx->frame.output.plane[2] = NULL; */ /* ctx->frame.output.stride[2] = 0; */ return 0; } static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t * buf, int buf_size) { context_t * ctx = (context_t *) avctx->priv_data; AVFrame * frame = (AVFrame *) data; int res; int i; ctx->frame.bitstream = buf; ctx->frame.length = buf_size; if (avctx->width) res = xvid_decore(ctx->dec_param.handle, XVID_DEC_DECODE, &ctx->frame, NULL); else { res = xvid_decore(ctx->dec_param.handle, XVID_DEC_DECODE, &ctx->frame, &ctx->stats); if (ctx->stats.type == XVID_TYPE_VOL) { printf("xvid_decode_frame: STATE %dx%d\n", ctx->stats.data.vol.width, ctx->stats.data.vol.height); avctx->width = ctx->stats.data.vol.width; avctx->height = ctx->stats.data.vol.height; } } if (res <= 0) { printf("xvid_decode_frame ERROR = %d\n", res); *data_size = 0; return res; } /* if (res != buf_size) */ /* printf("res = %d (%d)\n", res, buf_size); */ //printf("%x %d\n", ctx->frame.output.plane[0], ctx->frame.output.stride[0]); for (i=0; i<4; i++) { frame->data[i] = ctx->frame.output.plane[i]; frame->linesize[i] = ctx->frame.output.stride[i]; } *data_size = 1; return res; } static int decode_end(AVCodecContext * avctx) { context_t * ctx = (context_t *) avctx->priv_data; xvid_decore(ctx->dec_param.handle, XVID_DEC_DESTROY, NULL, NULL); /* int i; */ /* for (i=0; i<4; i++) { */ /* if (ctx->frame.output.plane[i]) { */ /* free(ctx->frame.output.plane[i]); */ /* ctx->frame.output.plane[i] = NULL; */ /* } */ /* } */ return 0; } AVCodec mpeg4_decoder = { "mpeg4", CODEC_TYPE_VIDEO, CODEC_ID_MPEG4, sizeof(context_t), decode_init, NULL, decode_end, decode_frame, (CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | 0), .flush= NULL,//flush, .long_name= "Xvid video", }; <file_sep>/applications/vmu_manager/modules/fs_vmd.c /* KallistiOS ##version## fs_vmd.c Copyright (C) 2003 <NAME> Copyright (C) 2012, 2013, 2014 <NAME> Copyright (C) 2015 megavolt85 */ #include <kos.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <malloc.h> #include <errno.h> #include <time.h> #include <arch/types.h> #include <kos/mutex.h> #include "fs_vmd.h" #include <sys/queue.h> #include <errno.h> #include "ds.h" /* At the moment this FS is kind of a hack because of the simplicity (and weirdness) of the VMD file system. For one, all files must be pretty small, so it loads and caches the entire file on open. For two, all files are a multiple of 512 bytes in size (no way around this one). On top of it all, files may have an obnoxious header and you can't just read and write them with abandon like a normal file system. We'll have to find ways around this later on, but for now it gives the file data to you raw. Note: this new version now talks directly to the vmdfs module and doesn't do any block-level I/O anymore. This layer and that one are interchangeable and may be used pretty much simultaneously in the same program. */ /* Enable this if you want copious debug output */ #define VMDFS_DEBUG #define VMD_DIR 0 #define VMD_FILE 1 #define VMD_ANY -1 /* Used for checking validity */ char vmdfile[NAME_MAX]; /* File handles */ typedef struct vmd_fh_str { uint32 strtype; /* 0==dir, 1==file */ TAILQ_ENTRY(vmd_fh_str) listent; /* list entry */ int mode; /* mode the file was opened with */ char path[17]; /* full path of the file */ char name[13]; /* name of the file */ off_t loc; /* current position in the file (bytes) */ uint32 filesize; /* file length from dirent (in 512-byte blks) */ uint8 *data; /* copy of the whole file */ } vmd_fh_t; /* Directory handles */ typedef struct vmd_dh_str { uint32 strtype; /* 0==dir, 1==file */ TAILQ_ENTRY(vmd_dh_str) listent; /* list entry */ int rootdir; /* 1 if we're reading /vmd */ dirent_t dirent; /* Dirent to pass back */ vmd_dir_t *dirblocks; /* Copy of all directory blocks */ uint16 entry; /* Current dirent */ uint16 dircnt; /* Count of dir entries */ } vmd_dh_t; /* Linked list of open files (controlled by "mutex") */ TAILQ_HEAD(vmd_fh_list, vmd_fh_str) vmd_fh; /* Thread mutex for vmd_fh access */ static mutex_t fh_mutex; /* opendir function */ static vmd_fh_t *vmd_open_dir() { vmd_dir_t * dirents; int dircnt; vmd_dh_t * dh; /* Read the VMD's directory */ if(vmdfs_readdir(vmdfile, &dirents, &dircnt) < 0){ return NULL; } /* Allocate a handle for the dir blocks */ dh = malloc(sizeof(vmd_dh_t)); dh->strtype = VMD_DIR; dh->dirblocks = dirents; dh->rootdir = 0; dh->entry = 0; dh->dircnt = dircnt; return (vmd_fh_t *)dh; } /* openfile function */ static vmd_fh_t *vmd_open_file(const char *path, int mode) { vmd_fh_t * fd; /* file descriptor */ int realmode, rv; void * data; int datasize; /* Malloc a new fh struct */ fd = malloc(sizeof(vmd_fh_t)); /* Fill in the filehandle struct */ fd->strtype = VMD_FILE; fd->mode = mode; strcpy(fd->path, "/"); strncpy(fd->name, path + 1, 12); fd->loc = 0; /* What mode are we opening in? If we're reading or writing without O_TRUNC then we need to read the old file if there is one. */ realmode = mode & O_MODE_MASK; if(realmode == O_RDONLY || ((realmode == O_RDWR || realmode == O_WRONLY) && !(mode & O_TRUNC))) { /* Try to open it */ rv = vmdfs_read(vmdfile, fd->name, &data, &datasize); if(rv < 0) { if(realmode == O_RDWR || realmode == O_WRONLY) { /* In some modes failure is ok -- just setup a blank first block. */ data = malloc(512); datasize = 512; memset(data, 0, 512); } else { free(fd); return NULL; } } } else { /* We're writing with truncate... just setup a blank first block. */ data = malloc(512); datasize = 512; memset(data, 0, 512); } fd->data = (uint8 *)data; fd->filesize = datasize / 512; if(fd->filesize == 0) { dbglog(DBG_WARNING, "VMDFS: can't open zero-length file %s\n", path); free(fd); return NULL; } return fd; } /* open function */ static void * vmd_open(vfs_handler_t * vfs, const char *path, int mode) { if(strlen(vmdfile) < 2) return 0; vmd_fh_t *fh; (void)vfs; /* Check for open as dir */ if(strlen(path) == 0 || (strlen(path) == 1 && path[0] == '/')) { if(!(mode & O_DIR)) return 0; fh = vmd_open_dir(); }else{ if(mode & O_DIR) return 0; fh = vmd_open_file(path, mode); } if(fh == NULL) return 0; /* link the fh onto the top of the list */ mutex_lock(&fh_mutex); TAILQ_INSERT_TAIL(&vmd_fh, fh, listent); mutex_unlock(&fh_mutex); return (void *)fh; } /* Verify that a given hnd is actually in the list */ static int vmd_verify_hnd(void * hnd, int type) { vmd_fh_t *cur; int rv = 0; mutex_lock(&fh_mutex); TAILQ_FOREACH(cur, &vmd_fh, listent) { if((void *)cur == hnd) { rv = 1; break; } } mutex_unlock(&fh_mutex); if(rv) return type == VMD_ANY ? 1 : ((int)cur->strtype == type); else return 0; } /* close a file */ static int vmd_close(void * hnd) { vmd_fh_t *fh; int retval = 0;//, st; /* Check the handle */ if(!vmd_verify_hnd(hnd, VMD_ANY)) { errno = EBADF; return -1; } fh = (vmd_fh_t *)hnd; switch(fh->strtype) { case VMD_DIR: { vmd_dh_t * dir = (vmd_dh_t *)hnd; if(dir->dirblocks) free(dir->dirblocks); break; } case VMD_FILE: /* if((fh->mode & O_MODE_MASK) == O_WRONLY || (fh->mode & O_MODE_MASK) == O_RDWR) { if ((st = vmd_write_close(hnd))) { if (st == -7) errno = ENOSPC; else errno = EIO; retval = -1; } }*/ free(fh->data); break; } /* Look for the one to get rid of */ mutex_lock(&fh_mutex); TAILQ_REMOVE(&vmd_fh, fh, listent); mutex_unlock(&fh_mutex); free(fh); return retval; } /* read function */ static ssize_t vmd_read(void * hnd, void *buffer, size_t cnt) { vmd_fh_t *fh; /* Check the handle */ if(!vmd_verify_hnd(hnd, VMD_FILE)) return -1; fh = (vmd_fh_t *)hnd; /* make sure we're opened for reading */ if((fh->mode & O_MODE_MASK) != O_RDONLY && (fh->mode & O_MODE_MASK) != O_RDWR) return 0; /* Check size */ cnt = (fh->loc + cnt) > (fh->filesize * 512) ? (fh->filesize * 512 - fh->loc) : cnt; /* Reads past EOF return 0 */ if((long)cnt < 0) return 0; /* Copy out the data */ memcpy(buffer, fh->data + fh->loc, cnt); fh->loc += cnt; return cnt; } /* read a directory handle */ static dirent_t *vmd_readdir(void * fd) { vmd_dh_t *dh; vmd_dir_t *dir; /* Check the handle */ if(!vmd_verify_hnd(fd, VMD_DIR)) { errno = EBADF; return NULL; } dh = (vmd_dh_t*)fd; /* Check if we have any entries left */ if(dh->entry >= dh->dircnt) return NULL; /* Ok, extract it and fill the dirent struct */ dir = dh->dirblocks + dh->entry; if(dh->rootdir) { dh->dirent.size = -1; dh->dirent.attr = O_DIR; } else { dh->dirent.size = dir->filesize * 512; dh->dirent.attr = 0; } strncpy(dh->dirent.name, dir->filename, 12); dh->dirent.name[12] = 0; dh->dirent.time = 0; /* FIXME */ /* Move to the next entry */ dh->entry++; return &dh->dirent; } static int vmd_rewinddir(void * fd) { vmd_dh_t *dh; /* Check the handle */ if(!vmd_verify_hnd(fd, VMD_DIR)) { errno = EBADF; return -1; } /* Rewind to the beginning of the directory. */ dh = (vmd_dh_t*)fd; dh->entry = 0; /* TODO: Technically, we need to re-scan the directory here, but for now we will punt on that requirement. */ return 0; } /* handler interface */ static vfs_handler_t vh = { /* Name handler */ { "/vmd", /* name */ 0, /* tbfi */ 0x00010000, /* Version 1.0 */ 0, /* flags */ NMMGR_TYPE_VFS, /* VFS handler */ NMMGR_LIST_INIT }, 0, NULL, /* In-kernel, privdata */ vmd_open, vmd_close, vmd_read, NULL, /* write */ NULL, /* seek */ NULL, /* tell */ NULL, /* total */ vmd_readdir, NULL, /* ioctl */ NULL, /* rename/move */ NULL, /* unlink */ NULL, /* mmap */ NULL, /* complete */ NULL, /* stat */ NULL, /* mkdir */ NULL, /* rmdir */ NULL, /* fcntl */ NULL, /* poll */ NULL, /* link */ NULL, /* symlink */ NULL, /* seek64 */ NULL, /* tell64 */ NULL, /* total64 */ NULL, /* readlink */ vmd_rewinddir }; int fs_vmd_init() { vmdfs_init(); TAILQ_INIT(&vmd_fh); mutex_init(&fh_mutex, MUTEX_TYPE_NORMAL); return nmmgr_handler_add(&vh.nmmgr); } int fs_vmd_shutdown() { vmd_fh_t * c, * n; c = TAILQ_FIRST(&vmd_fh); while(c) { n = TAILQ_NEXT(c, listent); switch(c->strtype) { case VMD_DIR: { vmd_dh_t * dir = (vmd_dh_t *)c; free(dir->dirblocks); break; } case VMD_FILE: if((c->mode & O_MODE_MASK) == O_WRONLY || (c->mode & O_MODE_MASK) == O_RDWR) { dbglog(DBG_ERROR, "fs_vmd_shutdown: still-open file '%s' not written!\n", c->path); } free(c->data); break; } free(c); c = n; } mutex_destroy(&fh_mutex); vmdfs_shutdown(); return nmmgr_handler_remove(&vh.nmmgr); } void fs_vmd_vmdfile(const char *infile){ sprintf(vmdfile,"%s",infile); } <file_sep>/modules/isoldr/module.c /* DreamShell ##version## DreamShell ISO Loader module Copyright (C)2009-2023 SWAT */ #include "ds.h" #include "isoldr.h" #include "fs.h" static uint8 kos_hdr[8] = {0x2D, 0xD0, 0x02, 0x01, 0x12, 0x20, 0x2B, 0xD0}; static uint8 ron_hdr[8] = {0x1B, 0xD0, 0x1A, 0xD1, 0x1B, 0x20, 0x2B, 0x40}; static uint8 win_hdr[4] = {0x45, 0x43, 0x45, 0x43}; void isoldr_exec_at(const void *image, uint32 length, uint32 address, uint32 params_len); DEFAULT_MODULE_EXPORTS_CMD(isoldr, "Runs the games images"); static void get_ipbin_info(isoldr_info_t *info, file_t fd, uint8 *sec, char *psec) { uint32 len; if(fs_ioctl(fd, ISOFS_IOCTL_GET_BOOT_SECTOR_DATA, sec) < 0) { ds_printf("DS_ERROR: Can't get boot sector data\n"); } else { // kos_md5(sec, sizeof(sec), info->md5); if(sec[0x60] != 0 && sec[0x60] != 0x20) { strncpy(info->exec.file, psec + 0x60, sizeof(info->exec.file)); for(len = 0; len < sizeof(info->exec.file); len++) { if(info->exec.file[len] == 0x20) { info->exec.file[len] = '\0'; break; } } } else { info->exec.file[0] = 0; } } } static int is_homebrew(file_t fd) { uint8 src[sizeof(kos_hdr)]; fs_seek(fd, 0, SEEK_SET); fs_read(fd, src, sizeof(kos_hdr)); fs_seek(fd, 0, SEEK_SET); /* Check for unscrambled homebrew */ if(!memcmp(src, kos_hdr, sizeof(kos_hdr)) || !memcmp(src, ron_hdr, sizeof(ron_hdr))) { return 1; } /* TODO: Check for scrambled homebrew */ return 0; } static int is_wince_rom(file_t fd) { uint8 src[sizeof(win_hdr)]; fs_seek(fd, 64, SEEK_SET); fs_read(fd, src, sizeof(win_hdr)); fs_seek(fd, 0, SEEK_SET); return !memcmp(src, win_hdr, sizeof(win_hdr)); } static int get_executable_info(isoldr_info_t *info, file_t fd) { if(!strncasecmp(info->exec.file, "0WINCEOS.BIN", 12)) { info->exec.type = BIN_TYPE_WINCE; info->exec.lba++; info->exec.size -= 2048; } else if(is_wince_rom(fd)) { info->exec.type = BIN_TYPE_WINCE; } else if(is_homebrew(fd)) { info->exec.type = BIN_TYPE_KOS; } else { // By default is KATANA // FIXME: detect KATANA and set scrambled homebrew by default info->exec.type = BIN_TYPE_KATANA; } return 0; } static int get_image_info(isoldr_info_t *info, const char *iso_file, int use_gdtex) { file_t fd; char fn[NAME_MAX]; char mount[8] = "/isoldr"; uint8 sec[2048]; char *psec = (char *)sec; mount[7] = '\0'; int len = 0; SDL_Surface *gd_tex = NULL; fd = fs_open(mount, O_DIR | O_RDONLY); if(fd != FILEHND_INVALID) { fs_close(fd); if(fs_iso_unmount(mount) < 0) { ds_printf("DS_ERROR: Can't unmount %s\n", mount); return -1; } } if(fs_iso_mount(mount, iso_file) < 0) { ds_printf("DS_ERROR: Can't mount %s to %s\n", iso_file, mount); return -1; } if(use_gdtex) { snprintf(fn, NAME_MAX, "%s/0GDTEX.PVR", mount); fd = fs_open(fn, O_RDONLY); if(fd != FILEHND_INVALID) { get_ipbin_info(info, fd, sec, psec); fs_close(fd); gd_tex = IMG_Load(fn); if(gd_tex != NULL) { info->gdtex = (uint32)gd_tex->pixels; } } else { fd = fs_iso_first_file(mount); if(fd != FILEHND_INVALID) { get_ipbin_info(info, fd, sec, psec); fs_close(fd); } } } else { fd = fs_iso_first_file(mount); if(fd != FILEHND_INVALID) { get_ipbin_info(info, fd, sec, psec); fs_close(fd); } } memset_sh4(&sec, 0, sizeof(sec)); if(info->exec.file[0] == 0) { strncpy(info->exec.file, "1ST_READ.BIN", 12); info->exec.file[12] = '\0'; } snprintf(fn, NAME_MAX, "%s/%s", mount, info->exec.file); fd = fs_open(fn, O_RDONLY); if(fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open %s\n", fn); goto image_error; } /* TODO check errors */ fs_ioctl(fd, ISOFS_IOCTL_GET_FD_LBA, &info->exec.lba); fs_ioctl(fd, ISOFS_IOCTL_GET_IMAGE_TYPE, &info->image_type); fs_ioctl(fd, ISOFS_IOCTL_GET_DATA_TRACK_LBA, &info->track_lba[0]); fs_ioctl(fd, ISOFS_IOCTL_GET_DATA_TRACK_SECTOR_SIZE, &info->sector_size); fs_ioctl(fd, ISOFS_IOCTL_GET_TOC_DATA, &info->toc); if(info->image_type == ISOFS_IMAGE_TYPE_CDI) { uint32 *offset = (uint32 *)sec; fs_ioctl(fd, ISOFS_IOCTL_GET_CDDA_OFFSET, offset); memcpy_sh4(&info->cdda_offset, offset, sizeof(info->cdda_offset)); memset_sh4(&sec, 0, sizeof(sec)); fs_ioctl(fd, ISOFS_IOCTL_GET_DATA_TRACK_OFFSET, &info->track_offset); } if(info->image_type == ISOFS_IMAGE_TYPE_CSO || info->image_type == ISOFS_IMAGE_TYPE_ZSO) { uint32 ptr = 0; if(!fs_ioctl(fd, ISOFS_IOCTL_GET_IMAGE_HEADER_PTR, &ptr) && ptr != 0) { memcpy_sh4(&info->ciso, (void*)ptr, sizeof(CISO_header_t)); } } if(info->image_type == ISOFS_IMAGE_TYPE_GDI) { fs_ioctl(fd, ISOFS_IOCTL_GET_DATA_TRACK_FILENAME, sec); fs_ioctl(fd, ISOFS_IOCTL_GET_DATA_TRACK_FILENAME2, info->image_second); fs_ioctl(fd, ISOFS_IOCTL_GET_DATA_TRACK_LBA2, &info->track_lba[1]); psec = strchr(psec + 1, '/'); } else { psec = strchr(iso_file + 1, '/'); } if(psec == NULL) { goto image_error; } len = strlen(psec); if(len > NAME_MAX) { len = NAME_MAX - 1; } strncpy(info->image_file, psec, len); info->image_file[len] = '\0'; info->exec.lba += 150; info->exec.size = fs_total(fd); if(get_executable_info(info, fd) < 0) { ds_printf("DS_ERROR: Can't get executable info\n"); goto image_error; } fs_close(fd); fs_iso_unmount(mount); return 0; image_error: if(fd != FILEHND_INVALID) { fs_close(fd); } fs_iso_unmount(mount); if(gd_tex) SDL_FreeSurface(gd_tex); return -1; } static int get_device_info(isoldr_info_t *info, const char *iso_file) { if(!strncasecmp(iso_file, "/pc/", 4)) { strncpy(info->fs_dev, ISOLDR_DEV_DCLOAD, 3); info->fs_dev[3] = '\0'; } else if(!strncasecmp(iso_file, "/cd/", 4)) { strncpy(info->fs_dev, ISOLDR_DEV_GDROM, 2); info->fs_dev[2] = '\0'; } else if(!strncasecmp(iso_file, "/sd", 3)) { strncpy(info->fs_dev, ISOLDR_DEV_SDCARD, 2); info->fs_dev[2] = '\0'; if(iso_file[3] != '/') { info->fs_part = (iso_file[3] - '0'); } } else if(!strncasecmp(iso_file, "/ide", 4)) { strncpy(info->fs_dev, ISOLDR_DEV_G1ATA, 3); info->fs_dev[3] = '\0'; if(iso_file[4] != '/') { info->fs_part = (iso_file[4] - '0'); } } else { ds_printf("DS_ERROR: isoldr doesn't support this device\n"); return -1; } info->fs_type[0] = '\0'; return 0; } isoldr_info_t *isoldr_get_info(const char *file, int use_gdtex) { isoldr_info_t *info = NULL; if(!FileExists(file)) { goto error; } info = (isoldr_info_t *) malloc(sizeof(*info)); if(info == NULL) { ds_printf("DS_ERROR: No free memory\n"); goto error; } memset_sh4(info, 0, sizeof(*info)); // info->emu_async = 8; info->track_lba[0] = 150; info->sector_size = 2048; if(get_image_info(info, file, use_gdtex) < 0) { goto error; } if(get_device_info(info, file) < 0) { goto error; } // Keep interface version 0.6.x up to 0.8.x loaders if (VER_MAJOR == 0 && VER_MINOR <= 8 && VER_MINOR >= 6) { snprintf(info->magic, 12, "DSISOLDR%d%d%d", VER_MAJOR, 6, VER_MICRO); } else { snprintf(info->magic, 12, "DSISOLDR%d%d%d", VER_MAJOR, VER_MINOR, VER_MICRO); } info->magic[11] = '\0'; info->exec.addr = 0xac010000; return info; error: if(info) free(info); return NULL; } static int patch_loader_addr(uint8 *loader, uint32 size, uint32 addr) { uint32 i = 0, a = 0; int skip = 0; EXPT_GUARD_BEGIN; for(i = 3; i < size - 1; i++) { if(loader[i] == 0xE0 && loader[i + 1] == 0x8C/* && loader[i - 1] < 0x10*/) { memcpy(&a, loader + i - 2, sizeof(uint32)); // printf("0x%08lx -> ", a); a -= ISOLDR_DEFAULT_ADDR; if(a == 0 && skip++) { // printf("skip\n"); continue; } // printf("0x%04lx -> ", a); a += addr; // printf("0x%08lx at offset %ld\n", a, i); memcpy(loader + i - 2, &a, sizeof(uint32)); } } EXPT_GUARD_CATCH; ds_printf("DS_ERROR: Loader memory patch failed\n"); EXPT_GUARD_RETURN -1; EXPT_GUARD_END; return 0; } static void set_loader_type(isoldr_info_t *info) { if (info->emu_vmu != 0 || info->syscalls != 0 || info->scr_hotkey != 0) { strncpy(info->fs_type, ISOLDR_TYPE_FULL, 4); info->fs_type[4] = '\0'; } else if (info->emu_cdda != CDDA_MODE_DISABLED || info->use_irq != 0) { strncpy(info->fs_type, ISOLDR_TYPE_EXTENDED, 3); info->fs_type[3] = '\0'; } else { info->fs_type[0] = '\0'; } } void isoldr_exec(isoldr_info_t *info, uint32 addr) { char fn[NAME_MAX]; if (strcmp(info->fs_dev, ISOLDR_DEV_DCLOAD) == 0 || strcmp(info->fs_dev, ISOLDR_DEV_GDROM) == 0 || strcmp(info->fs_dev, ISOLDR_DEV_SDCARD) == 0 || strcmp(info->fs_dev, ISOLDR_DEV_G1ATA) == 0 ) { set_loader_type(info); } if(info->fs_type[0] != '\0') { snprintf(fn, NAME_MAX, "%s/firmware/%s/%s_%s.bin", getenv("PATH"), lib_get_name(), info->fs_dev, info->fs_type); } else { snprintf(fn, NAME_MAX, "%s/firmware/%s/%s.bin", getenv("PATH"), lib_get_name(), info->fs_dev); } file_t fd = fs_open(fn, O_RDONLY); if(fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open file: %s\n", fn); return; } size_t sc_len = 0; size_t len = fs_total(fd) + ISOLDR_PARAMS_SIZE; ds_printf("DS_PROCESS: Loading %s (%d) ...\n", fn, len); uint8 *loader = (uint8 *) malloc(len < 0x20000 ? 0x20000 : len); if(loader == NULL) { fs_close(fd); ds_printf("DS_ERROR: No free memory, needed %d bytes\n", len); return; } memset_sh4(loader, 0, len < 0x20000 ? 0x20000 : len); if(fs_read(fd, loader + ISOLDR_PARAMS_SIZE, len) != (len - ISOLDR_PARAMS_SIZE)) { fs_close(fd); ds_printf("DS_ERROR: Can't load %s\n", fn); return; } fs_close(fd); if (info->syscalls == 1) { snprintf(fn, NAME_MAX, "%s/firmware/%s/syscalls.bin", getenv("PATH"), lib_get_name()); fd = fs_open(fn, O_RDONLY); if (fd < 0) { info->syscalls = 0; } else { sc_len = fs_total(fd); ds_printf("DS_PROCESS: Loading %s (%d) ...\n", fn, sc_len); uint8 *buff = loader + len + 0x1000; // Keep some for a loader heap if (fs_read(fd, buff, sc_len) != sc_len) { ds_printf("DS_ERROR: Can't load %s\n", fn); info->syscalls = 0; } else { dcache_flush_range((uint32)buff, sc_len); addr = ISOLDR_DEFAULT_ADDR; info->syscalls = (uint32)buff; info->heap = HEAP_MODE_BEHIND; info->emu_cdda = 0; info->emu_vmu = 0; info->use_irq = 0; if (sc_len < 0x4000) { sc_len = 0x5000; } else { sc_len += 0x1000; } } fs_close(fd); } } if(addr != ISOLDR_DEFAULT_ADDR) { if(patch_loader_addr(loader + ISOLDR_PARAMS_SIZE, len - ISOLDR_PARAMS_SIZE, addr)) { free(loader); return; } } memcpy_sh4(loader, info, sizeof(*info)); // free(info); ds_printf("DS_PROCESS: Executing at 0x%08lx...\n", addr); ShutdownDS(); isoldr_exec_at(loader, len + sc_len, addr, ISOLDR_PARAMS_SIZE); } int builtin_isoldr_cmd(int argc, char *argv[]) { if(argc < 2) { ds_printf("\n ## ISO Loader v%d.%d.%d build %d ##\n\n" "Usage: %s options args\n" "Options: \n", VER_MAJOR, VER_MINOR, VER_MICRO, VER_BUILD, argv[0]); ds_printf(" -s, --fast -Don't show loader text and disc texture on screen\n", " -i, --verbose -Show additional info\n", " -a, --dma -Use DMA transfer if available\n" " -q, --irq -Use IRQ hooking\n" " -c, --cdda -Emulate CDDA audio (cddamode=1 by default)\n" " -l, --low -Use low-level syscalls emulation (disabled by default).\n"); ds_printf("Arguments: \n" " -e, --async -Emulate async reading, 0=none default, >0=sectors per frame\n" " -d, --device -Loader device (sd/ide/cd), default auto\n" " -p, --fspart -Device partition (0-3), default auto\n" " -t, --fstype -Device filesystem (fat, ext2, raw), default auto\n"); ds_printf(" -x, --lmem -Any valid address for the loader (default auto)\n" " -f, --file -ISO image file path\n" " -j, --jmp -Boot mode:\n" " 0 = from executable (default)\n" " 1 = from IP.BIN\n" " 2 = from truncated IP.BIN\n"); ds_printf(" -o, --os -Executable OS:\n" " 0 = auto (default)\n" " 1 = KallistiOS\n" " 2 = KATANA\n" " 3 = WINCE\n"); ds_printf(" -r, --addr -Executable memory address (default 0xac010000)\n" " -b, --boot -Executable file name (default from IP.BIN)\n"); ds_printf(" -h, --heap -Heap mode or memory address\n" " 0 = auto address selection (default)\n" " 1 = behind the loader\n" " 2 = ingame memory allocation (KATANA only)\n" " 3 = maple DMA buffer (keep some for devices)\n" " 0x8cXXXXXX = address (specify valid address)\n"); ds_printf(" -g, --cddamode -CDDA emulation mode\n" " 0 = Disabled (default)\n" " 1 = DMA and TMU2\n" " 2 = DMA and TMU1\n" " 3 = SQ and TMU2\n" " 4 = SQ and TMU1\n"); ds_printf(" -v, --vmu -Emulate VMU on port A1.\n" " 0 = disabled (default)\n" " 1 = number for VMU dump /vmu/vmudump001.vmd\n" " 999 = max number\n"); ds_printf(" -k, --scrhot -Screenshots from video frame buffer\n" " 0 = disabled (default)\n" " XXXX = bit mask for pad buttons to me pressed\n"); ds_printf(" --pa1 -Patch address 1\n" " --pa2 -Patch address 2\n" " --pv1 -Patch value 1\n" " --pv2 -Patch value 2\n\n" "Example: %s -f /sd/game.iso\n\n", argv[0]); return CMD_NO_ARG; } uint32 p_addr[2] = {0, 0}; uint32 p_value[2] = {0, 0}; uint32 addr = 0, use_dma = 0, lex = 0, heap = HEAP_MODE_AUTO; char *file = NULL, *bin_file = NULL, *device = NULL, *fstype = NULL; uint32 emu_async = 0, emu_cdda = 0, boot_mode = BOOT_MODE_DIRECT; uint32 bin_type = BIN_TYPE_AUTO, fast_boot = 0, verbose = 0; uint32 cdda_mode = CDDA_MODE_DISABLED, use_irq = 0, emu_vmu = 0; uint32 low_level = 0, scr_hotkey = 0; int fspart = -1; isoldr_info_t *info; struct cfg_option options[] = { {"verbose", 'i', NULL, CFG_BOOL, (void *) &verbose, 0}, {"dma", 'a', NULL, CFG_BOOL, (void *) &use_dma, 0}, {"device", 'd', NULL, CFG_STR, (void *) &device, 0}, {"fspart", 'p', NULL, CFG_INT, (void *) &fspart, 0}, {"fstype", 't', NULL, CFG_STR, (void *) &fstype, 0}, {"memory", 'x', NULL, CFG_ULONG, (void *) &lex, 0}, {"addr", 'r', NULL, CFG_ULONG, (void *) &addr, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, {"async", 'e', NULL, CFG_ULONG, (void *) &emu_async, 0}, {"cdda", 'c', NULL, CFG_BOOL, (void *) &emu_cdda, 0}, {"cddamode", 'g', NULL, CFG_ULONG, (void *) &cdda_mode, 0}, {"heap", 'h', NULL, CFG_ULONG, (void *) &heap, 0}, {"jmp", 'j', NULL, CFG_ULONG, (void *) &boot_mode, 0}, {"os", 'o', NULL, CFG_ULONG, (void *) &bin_type, 0}, {"boot", 'b', NULL, CFG_STR, (void *) &bin_file, 0}, {"fast", 's', NULL, CFG_BOOL, (void *) &fast_boot, 0}, {"irq", 'q', NULL, CFG_BOOL, (void *) &use_irq, 0}, {"vmu", 'v', NULL, CFG_ULONG, (void *) &emu_vmu, 0}, {"low", 'l', NULL, CFG_BOOL, (void *) &low_level, 0}, {"scrhot", 'k', NULL, CFG_ULONG, (void *) &scr_hotkey, 0}, {"pa1", '\0', NULL, CFG_ULONG, (void *) &p_addr[0], 0}, {"pa2", '\0', NULL, CFG_ULONG, (void *) &p_addr[1], 0}, {"pv1", '\0', NULL, CFG_ULONG, (void *) &p_value[0], 0}, {"pv2", '\0', NULL, CFG_ULONG, (void *) &p_value[1], 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(file == NULL) { ds_printf("DS_ERROR: Too few arguments (ISO file) \n"); return CMD_ERROR; } if(!lex) { if(boot_mode != BOOT_MODE_DIRECT) { lex = ISOLDR_DEFAULT_ADDR_HIGH; } else { lex = ISOLDR_DEFAULT_ADDR_MIN; } } info = isoldr_get_info(file, fast_boot); if(info == NULL) { return CMD_ERROR; } if(device != NULL && strncasecmp(device, "auto", 4)) { strcpy(info->fs_dev, device); info->fs_dev[strlen(info->fs_dev)] = '\0'; } else { if(!strncasecmp(file, "/pc/", 4) && lex < 0x8c010000) { lex = ISOLDR_DEFAULT_ADDR_HIGH; ds_printf("DS_WARNING: Using dc-load as file system, forced loader address: 0x%08lx\n", lex); } } if(fstype != NULL && strncasecmp(fstype, "auto", 4)) { strcpy(info->fs_type, fstype); info->fs_type[strlen(info->fs_type)] = '\0'; } if(fspart > -1 && fspart < 4) { info->fs_part = fspart; } if(bin_file != NULL) { strncpy(info->exec.file, bin_file, 12); info->exec.file[12] = '\0'; } if(bin_type) { info->exec.type = bin_type; } if(addr) { info->exec.addr = addr; } info->boot_mode = boot_mode; info->emu_async = emu_async; info->use_dma = use_dma; info->fast_boot = fast_boot; info->heap = heap; info->use_irq = use_irq; info->emu_vmu = emu_vmu; info->syscalls = low_level; info->scr_hotkey = scr_hotkey; if (cdda_mode > CDDA_MODE_DISABLED) { info->emu_cdda = cdda_mode; } else if(emu_cdda) { info->emu_cdda = CDDA_MODE_DMA_TMU2; } else { info->emu_cdda = CDDA_MODE_DISABLED; } info->patch_addr[0] = p_addr[0]; info->patch_addr[1] = p_addr[1]; info->patch_value[0] = p_value[0]; info->patch_value[1] = p_value[1]; if(verbose) { ds_printf("Params size: %d\n", sizeof(isoldr_info_t)); ds_printf("\n--- Executable info ---\n" "Name: %s\n" "OS: %d\n" "Size: %d Kb\n" "LBA: %d\n" "Address: 0x%08lx\n" "Boot mode: %d\n", info->exec.file, info->exec.type, info->exec.size/1024, info->exec.lba, info->exec.addr, info->boot_mode); ds_printf("--- ISO info ---\n" "File: %s (%s)\n" "Format: %d\n" "LBA: %d (%d)\n" "Sector size: %d\n", info->image_file, info->image_second, info->image_type, info->track_lba[0], info->track_lba[1], info->sector_size); ds_printf("--- Loader info ---\n" "Device: %s\n" "Type: %s\n" "Partition: %d\n" "Address: 0x%08lx\n" "DMA: %d\n" "IRQ: %d\n" "Heap: %lx\n", info->fs_dev, info->fs_dev[0] != '\0' ? info->fs_type : "normal", info->fs_part, lex, info->use_dma, info->use_irq, info->heap); ds_printf("Emu async: %d\n" "Emu CDDA: %d\n" "Emu VMU: %d\n" "Syscalls: %lx\n\n", info->emu_async, info->emu_cdda, info->emu_vmu, info->syscalls); } isoldr_exec(info, lex); return CMD_ERROR; } <file_sep>/modules/tolua++/tolua++/Makefile # DreamShell ##version## # by SWAT # libtolua++ Makefile TARGET = libtolua++.a OBJS = src/lib/tolua_event.o src/lib/tolua_is.o src/lib/tolua_map.o \ src/lib/tolua_push.o src/lib/tolua_to.o KOS_CFLAGS += -I./include -I../../../include -I../../../include/lua -I./src/lib include ../../../lib/Makefile.prefab <file_sep>/include/network/lftpd.h #pragma once typedef struct { char* directory; int socket; int data_socket; } lftpd_client_t; typedef struct { const char* directory; int port; int server_socket; lftpd_client_t* client; } lftpd_t; /** * @brief Create a server on port and start listening for client * connections. This function blocks for the life of the server and * only returns when lftpd_stop() is called with the same lftpd_t. */ int lftpd_start(const char* directory, int port, lftpd_t* lftpd); /** * @brief Stop a previously started server. This kills any active client * connections, shuts down the listener, and returns. After this * function returns, lftpd_start() will also return. */ int lftpd_stop(lftpd_t* lftpd); <file_sep>/src/lua/lua.c /**************************** * DreamShell ##version## * * lua.c * * DreamShell LUA * * Created by SWAT * ****************************/ #include "lua.h" #include "list.h" #include "module.h" #include "utils.h" #include "console.h" #include "exceptions.h" static lua_State *DSLua = NULL; static Item_list_t *lua_libs; void LuaOpenlibs(lua_State *L) { /* Open stock libs */ luaL_openlibs(L); /* Open additional libs */ lua_packlibopen(L); /* Custom functions */ RegisterLuaFunctions(L); Item_t *i; LuaRegLibOpen *openFunc; SLIST_FOREACH(i, lua_libs, list) { openFunc = (LuaRegLibOpen *) i->data; if(openFunc != NULL) { //ds_printf("DS_PROCESS: Opening lua library: %s\n", i->name); EXPT_GUARD_BEGIN; openFunc(L); EXPT_GUARD_CATCH; ds_printf("DS_ERROR: Can't open lua library: %s\n", i->name); EXPT_GUARD_END; } } } int InitLua() { //ds_printf("DS_PROCESS: Init lua library...\n"); luaB_set_fputs((void (*)(const char *))ds_printf); DSLua = luaL_newstate();//lua_open(); if (DSLua == NULL) { ds_printf("DS_ERROR_LUA: Invalid state.. giving up\n"); return -1; } if((lua_libs = listMake()) == NULL) { return -1; } LuaOpenlibs(DSLua); //ds_printf("DS_OK: Lua library inited.\n"); return 0; } void ShutdownLua() { listDestroy(lua_libs, (listFreeItemFunc *) free); lua_close(DSLua); } void ResetLua() { ds_printf("DS_PROCESS: Reset lua state...\n"); lua_close(DSLua); DSLua = luaL_newstate(); LuaOpenlibs(DSLua); } int RegisterLuaLib(const char *name, LuaRegLibOpen *func) { if(listAddItem(lua_libs, LIST_ITEM_LUA_LIB, name, func, sizeof(LuaRegLibOpen)) != NULL){ return 1; } return 0; } int UnregisterLuaLib(const char *name) { Item_t *i = listGetItemByName(lua_libs, name); if(i == NULL) { return 0; } listRemoveItem(lua_libs, i, NULL); return 1; } int lua_report (lua_State *L, int status) { if (status && !lua_isnil(L, -1)) { const char *msg = lua_tostring(L, -1); if (msg == NULL) msg = "(error object is not a string)"; ds_printf(msg); lua_pop(L, 1); } return status; } int lua_traceback(lua_State *L) { if (!lua_isstring(L, 1)) /* 'message' not a string? */ return 1; /* keep it intact */ lua_getfield(L, LUA_GLOBALSINDEX, "debug"); if (!lua_istable(L, -1)) { lua_pop(L, 1); return 1; } lua_getfield(L, -1, "traceback"); if (!lua_isfunction(L, -1)) { lua_pop(L, 2); return 1; } lua_pushvalue(L, 1); /* pass error message */ lua_pushinteger(L, 2); /* skip this function and traceback */ lua_call(L, 2, 1); /* call debug.traceback */ return 1; } int lua_docall (lua_State *L, int narg, int clear) { int status; int base = lua_gettop(L) - narg; /* function index */ lua_pushcfunction(L, lua_traceback); /* push traceback function */ lua_insert(L, base); /* put it under chunk and args */ status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base); lua_remove(L, base); /* remove traceback function */ /* force a complete garbage collection in case of errors */ if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0); return status; } static int dofile (lua_State *L, const char *name) { int status = luaL_loadfile(L, name) || lua_docall(L, 0, 1); return lua_report(L, status); } static int dostring (lua_State *L, const char *s, const char *name) { int status = luaL_loadbuffer(L, s, strlen(s), name) || lua_docall(L, 0, 1); return lua_report(L, status); } static int dolibrary (lua_State *L, const char *name) { lua_getglobal(L, "require"); lua_pushstring(L, name); return lua_report(L, lua_docall(L, 1, 1)); } int LuaDo(int type, const char *str_or_file, lua_State *lu) { int res = LUA_ERRRUN; EXPT_GUARD_BEGIN; if(type == LUA_DO_FILE) { res = dofile(lu, str_or_file); } else if(type == LUA_DO_STRING) { res = dostring(lu, str_or_file, "=(DreamShell)"); } else if(type == LUA_DO_LIBRARY) { res = dolibrary(lu, str_or_file); } else { ds_printf("DS_ERROR: LuaDo type error: %d\n", type); } EXPT_GUARD_CATCH; res = LUA_ERRRUN; ds_printf("DS_ERROR: Exception in lua script: %s\n", str_or_file); EXPT_GUARD_END; /* Lua gives no message in such cases, so lua.c provides one */ if (res == LUA_ERRMEM) { ds_printf("LUA: Memory allocation error!\n"); } else if (res == LUA_ERRFILE) ds_printf("LUA: Can't open lua file %s\n", str_or_file); else if (res == LUA_ERRSYNTAX) ds_printf("LUA: Syntax error in lua script %s\n", str_or_file); else if (res == LUA_ERRRUN) ds_printf("LUA: Error at management chunk!\n"); else if (res == LUA_ERRERR) ds_printf("LUA: Error in error message!\n"); return res; } void LuaPushArgs(lua_State *L, char *argv[]) { int i; lua_newtable(L); for (i=0; argv[i]; i++) { /* arg[i] = argv[i] */ lua_pushnumber(L, i); lua_pushstring(L, argv[i]); lua_settable(L, -3); } /* argv.n = maximum index in table `argv' */ lua_pushstring(L, "n"); lua_pushnumber(L, i-1); lua_settable(L, -3); } void LuaAddArgs(lua_State *L, char *argv[]) { LuaPushArgs(L, argv); lua_setglobal(L, "argv"); } int RunLuaScript(char *fn, char *argv[]) { lua_State *L = NewLuaThread(); if(L == NULL) { ds_printf("DS_ERROR: LUA: Invalid state.. giving up\n"); return 0; } if(argv != NULL) { LuaPushArgs(L, argv); lua_setglobal(L, "argv"); } LuaDo(LUA_DO_FILE, fn, L); lua_close(L); return 1; } lua_State *GetLuaState() { return DSLua; } void SetLuaState(lua_State *l) { DSLua = l; } lua_State *NewLuaThread() { return lua_newthread(DSLua); //lua_State *L = lua_open(); //LuaOpenlibs(L); //return L; } <file_sep>/modules/SDL_net/lib/SDLnet.c /* SDL_net: An example cross-platform network library for use with SDL Copyright (C) 1997-2012 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* $Id$ */ #include <string.h> #include "SDL_endian.h" #include "SDLnetsys.h" #include "SDL_net.h" const SDL_version *SDLNet_Linked_Version(void) { static SDL_version linked_version; SDL_NET_VERSION(&linked_version); return(&linked_version); } /* Since the UNIX/Win32/BeOS code is so different from MacOS, we'll just have two completely different sections here. */ static int SDLNet_started = 0; #ifndef __USE_W32_SOCKETS #include <signal.h> #endif #ifndef __USE_W32_SOCKETS int SDLNet_GetLastError(void) { return errno; } void SDLNet_SetLastError(int err) { errno = err; } #endif /* Initialize/Cleanup the network API */ int SDLNet_Init(void) { if ( !SDLNet_started ) { #ifdef __USE_W32_SOCKETS /* Start up the windows networking */ WORD version_wanted = MAKEWORD(1,1); WSADATA wsaData; if ( WSAStartup(version_wanted, &wsaData) != 0 ) { SDLNet_SetError("Couldn't initialize Winsock 1.1\n"); return(-1); } #else /* SIGPIPE is generated when a remote socket is closed */ /* void (*handler)(int); handler = signal(SIGPIPE, SIG_IGN); if ( handler != SIG_DFL ) { signal(SIGPIPE, handler); }*/ #endif } ++SDLNet_started; return(0); } void SDLNet_Quit(void) { if ( SDLNet_started == 0 ) { return; } if ( --SDLNet_started == 0 ) { #ifdef __USE_W32_SOCKETS /* Clean up windows networking */ if ( WSACleanup() == SOCKET_ERROR ) { if ( WSAGetLastError() == WSAEINPROGRESS ) { #ifndef _WIN32_WCE WSACancelBlockingCall(); #endif WSACleanup(); } } #else /* Restore the SIGPIPE handler */ /* void (*handler)(int); handler = signal(SIGPIPE, SIG_DFL); if ( handler != SIG_IGN ) { signal(SIGPIPE, handler); }*/ #endif } } /* Resolve a host name and port to an IP address in network form */ int SDLNet_ResolveHost(IPaddress *address, const char *host, Uint16 port) { int retval = 0; /* Perform the actual host resolution */ if ( host == NULL ) { address->host = INADDR_ANY; } else { address->host = inet_addr(host); if ( address->host == INADDR_NONE ) { struct hostent *hp; hp = gethostbyname(host); if ( hp ) { memcpy(&address->host,hp->h_addr,hp->h_length); } else { retval = -1; } } } address->port = SDL_SwapBE16(port); /* Return the status */ return(retval); } /* Resolve an ip address to a host name in canonical form. If the ip couldn't be resolved, this function returns NULL, otherwise a pointer to a static buffer containing the hostname is returned. Note that this function is not thread-safe. */ /* Written by <NAME>. * Main Programmer of Arianne RPG. * http://come.to/arianne_rpg */ const char *SDLNet_ResolveIP(const IPaddress *ip) { //struct hostent *hp; struct in_addr in; /* hp = gethostbyaddr((const char *)&ip->host, sizeof(ip->host), AF_INET); if ( hp != NULL ) { return hp->h_name; } */ in.s_addr = ip->host; return inet_ntoa(in); } int SDLNet_GetLocalAddresses(IPaddress *addresses, int maxcount) { int count = 0; #ifdef SIOCGIFCONF /* Defined on Mac OS X */ #ifndef _SIZEOF_ADDR_IFREQ #define _SIZEOF_ADDR_IFREQ sizeof #endif SOCKET sock; struct ifconf conf; char data[4096]; struct ifreq *ifr; struct sockaddr_in *sock_addr; sock = socket(AF_INET, SOCK_DGRAM, 0); if ( sock == INVALID_SOCKET ) { return 0; } conf.ifc_len = sizeof(data); conf.ifc_buf = (caddr_t) data; if ( ioctl(sock, SIOCGIFCONF, &conf) < 0 ) { closesocket(sock); return 0; } ifr = (struct ifreq*)data; while ((char*)ifr < data+conf.ifc_len) { if (ifr->ifr_addr.sa_family == AF_INET) { if (count < maxcount) { sock_addr = (struct sockaddr_in*)&ifr->ifr_addr; addresses[count].host = sock_addr->sin_addr.s_addr; addresses[count].port = sock_addr->sin_port; } ++count; } ifr = (struct ifreq*)((char*)ifr + _SIZEOF_ADDR_IFREQ(*ifr)); } closesocket(sock); #elif defined(__WIN32__) PIP_ADAPTER_INFO pAdapterInfo; PIP_ADAPTER_INFO pAdapter; PIP_ADDR_STRING pAddress; DWORD dwRetVal = 0; ULONG ulOutBufLen = sizeof (IP_ADAPTER_INFO); pAdapterInfo = (IP_ADAPTER_INFO *) SDL_malloc(sizeof (IP_ADAPTER_INFO)); if (pAdapterInfo == NULL) { return 0; } if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == ERROR_BUFFER_OVERFLOW) { pAdapterInfo = (IP_ADAPTER_INFO *) SDL_realloc(pAdapterInfo, ulOutBufLen); if (pAdapterInfo == NULL) { return 0; } dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen); } if (dwRetVal == NO_ERROR) { for (pAdapter = pAdapterInfo; pAdapter; pAdapter = pAdapter->Next) { for (pAddress = &pAdapterInfo->IpAddressList; pAddress; pAddress = pAddress->Next) { if (count < maxcount) { addresses[count].host = inet_addr(pAddress->IpAddress.String); addresses[count].port = 0; } ++count; } } } SDL_free(pAdapterInfo); #endif return count; } #if !SDL_DATA_ALIGNED /* function versions for binary compatibility */ /* Write a 16 bit value to network packet buffer */ #undef SDLNet_Write16 void SDLNet_Write16(Uint16 value, void *areap) { (*(Uint16 *)(areap) = SDL_SwapBE16(value)); } /* Write a 32 bit value to network packet buffer */ #undef SDLNet_Write32 void SDLNet_Write32(Uint32 value, void *areap) { *(Uint32 *)(areap) = SDL_SwapBE32(value); } /* Read a 16 bit value from network packet buffer */ #undef SDLNet_Read16 Uint16 SDLNet_Read16(void *areap) { return (SDL_SwapBE16(*(Uint16 *)(areap))); } /* Read a 32 bit value from network packet buffer */ #undef SDLNet_Read32 Uint32 SDLNet_Read32(void *areap) { return (SDL_SwapBE32(*(Uint32 *)(areap))); } #endif /* !SDL_DATA_ALIGNED */ <file_sep>/modules/mp3/libmp3/xingmp3/cdct.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** cdct.c *************************************************** mod 5/16/95 first stage in 8 pt dct does not drop last sb mono MPEG audio decoder, dct portable C ******************************************************************/ #include <float.h> #include <math.h> #include "L3.h" #include "mhead.h" #ifdef ASM_X86 extern void fdct32_asm(float *coef32, float*a, float*b); extern void fdct32_dual_asm(float *coef32, float*a, float*b); #endif /* ASM_X86 */ /*------------------------------------------------------------*/ float *dct_coef_addr(MPEG *m) { return m->cdct.coef32; } /*------------------------------------------------------------*/ static void forward_bf(int m, int n, float x[], float f[], float coef[]) { int i, j, n2; int p, q, p0, k; p0 = 0; n2 = n >> 1; for (i = 0; i < m; i++, p0 += n) { k = 0; p = p0; q = p + n - 1; for (j = 0; j < n2; j++, p++, q--, k++) { f[p] = x[p] + x[q]; f[n2 + p] = coef[k] * (x[p] - x[q]); } } } /*------------------------------------------------------------*/ static void back_bf(int m, int n, float x[], float f[]) { int i, j, n2, n21; int p, q, p0; p0 = 0; n2 = n >> 1; n21 = n2 - 1; for (i = 0; i < m; i++, p0 += n) { p = p0; q = p0; for (j = 0; j < n2; j++, p += 2, q++) f[p] = x[q]; p = p0 + 1; for (j = 0; j < n21; j++, p += 2, q++) f[p] = x[q] + x[q + 1]; f[p] = x[q]; } } /*------------------------------------------------------------*/ void fdct32(MPEG *m, float x[], float c[]) { float a[32]; /* ping pong buffers */ float b[32]; int p, q; float *src = x; int i; if (m->eq.enableEQ) { for(i=0; i<32; i++) b[i] = x[i] * m->eq.equalizer[i]; src = b; } #ifdef ASM_X86 fdct32_asm(m->cdct.coef32, src, c); #else /* special first stage */ for (p = 0, q = 31; p < 16; p++, q--) { a[p] = src[p] + src[q]; a[16 + p] = m->cdct.coef32[p] * (src[p] - src[q]); } forward_bf(2, 16, a, b, m->cdct.coef32 + 16); forward_bf(4, 8, b, a, m->cdct.coef32 + 16 + 8); forward_bf(8, 4, a, b, m->cdct.coef32 + 16 + 8 + 4); forward_bf(16, 2, b, a, m->cdct.coef32 + 16 + 8 + 4 + 2); back_bf(8, 4, a, b); back_bf(4, 8, b, a); back_bf(2, 16, a, b); back_bf(1, 32, b, c); #endif } /*------------------------------------------------------------*/ void fdct32_dual(MPEG *m, float x[], float c[]) { #ifdef ASM_X86 fdct32_dual_asm(m->cdct.coef32, x, c); #else float a[32]; /* ping pong buffers */ float b[32]; int p, pp, qq; /* special first stage for dual chan (interleaved x) */ pp = 0; qq = 2 * 31; for (p = 0; p < 16; p++, pp += 2, qq -= 2) { a[p] = x[pp] + x[qq]; a[16 + p] = m->cdct.coef32[p] * (x[pp] - x[qq]); } forward_bf(2, 16, a, b, m->cdct.coef32 + 16); forward_bf(4, 8, b, a, m->cdct.coef32 + 16 + 8); forward_bf(8, 4, a, b, m->cdct.coef32 + 16 + 8 + 4); forward_bf(16, 2, b, a, m->cdct.coef32 + 16 + 8 + 4 + 2); back_bf(8, 4, a, b); back_bf(4, 8, b, a); back_bf(2, 16, a, b); back_bf(1, 32, b, c); #endif } /*---------------convert dual to mono------------------------------*/ void fdct32_dual_mono(MPEG *m, float x[], float c[]) { float a[32]; /* ping pong buffers */ float b[32]; float t1, t2; int p, pp, qq; /* special first stage */ pp = 0; qq = 2 * 31; for (p = 0; p < 16; p++, pp += 2, qq -= 2) { t1 = 0.5F * (x[pp] + x[pp + 1]); t2 = 0.5F * (x[qq] + x[qq + 1]); a[p] = t1 + t2; a[16 + p] = m->cdct.coef32[p] * (t1 - t2); } forward_bf(2, 16, a, b, m->cdct.coef32 + 16); forward_bf(4, 8, b, a, m->cdct.coef32 + 16 + 8); forward_bf(8, 4, a, b, m->cdct.coef32 + 16 + 8 + 4); forward_bf(16, 2, b, a, m->cdct.coef32 + 16 + 8 + 4 + 2); back_bf(8, 4, a, b); back_bf(4, 8, b, a); back_bf(2, 16, a, b); back_bf(1, 32, b, c); } /*------------------------------------------------------------*/ /*---------------- 16 pt fdct -------------------------------*/ void fdct16(MPEG *m, float x[], float c[]) { float a[16]; /* ping pong buffers */ float b[16]; int p, q; /* special first stage (drop highest sb) */ a[0] = x[0]; a[8] = m->cdct.coef32[16] * x[0]; for (p = 1, q = 14; p < 8; p++, q--) { a[p] = x[p] + x[q]; a[8 + p] = m->cdct.coef32[16 + p] * (x[p] - x[q]); } forward_bf(2, 8, a, b, m->cdct.coef32 + 16 + 8); forward_bf(4, 4, b, a, m->cdct.coef32 + 16 + 8 + 4); forward_bf(8, 2, a, b, m->cdct.coef32 + 16 + 8 + 4 + 2); back_bf(4, 4, b, a); back_bf(2, 8, a, b); back_bf(1, 16, b, c); } /*------------------------------------------------------------*/ /*---------------- 16 pt fdct dual chan---------------------*/ void fdct16_dual(MPEG *m, float x[], float c[]) { float a[16]; /* ping pong buffers */ float b[16]; int p, pp, qq; /* special first stage for interleaved input */ a[0] = x[0]; a[8] = m->cdct.coef32[16] * x[0]; pp = 2; qq = 2 * 14; for (p = 1; p < 8; p++, pp += 2, qq -= 2) { a[p] = x[pp] + x[qq]; a[8 + p] = m->cdct.coef32[16 + p] * (x[pp] - x[qq]); } forward_bf(2, 8, a, b, m->cdct.coef32 + 16 + 8); forward_bf(4, 4, b, a, m->cdct.coef32 + 16 + 8 + 4); forward_bf(8, 2, a, b, m->cdct.coef32 + 16 + 8 + 4 + 2); back_bf(4, 4, b, a); back_bf(2, 8, a, b); back_bf(1, 16, b, c); } /*------------------------------------------------------------*/ /*---------------- 16 pt fdct dual to mono-------------------*/ void fdct16_dual_mono(MPEG *m, float x[], float c[]) { float a[16]; /* ping pong buffers */ float b[16]; float t1, t2; int p, pp, qq; /* special first stage */ a[0] = 0.5F * (x[0] + x[1]); a[8] = m->cdct.coef32[16] * a[0]; pp = 2; qq = 2 * 14; for (p = 1; p < 8; p++, pp += 2, qq -= 2) { t1 = 0.5F * (x[pp] + x[pp + 1]); t2 = 0.5F * (x[qq] + x[qq + 1]); a[p] = t1 + t2; a[8 + p] = m->cdct.coef32[16 + p] * (t1 - t2); } forward_bf(2, 8, a, b, m->cdct.coef32 + 16 + 8); forward_bf(4, 4, b, a, m->cdct.coef32 + 16 + 8 + 4); forward_bf(8, 2, a, b, m->cdct.coef32 + 16 + 8 + 4 + 2); back_bf(4, 4, b, a); back_bf(2, 8, a, b); back_bf(1, 16, b, c); } /*------------------------------------------------------------*/ /*---------------- 8 pt fdct -------------------------------*/ void fdct8(MPEG *m, float x[], float c[]) { float a[8]; /* ping pong buffers */ float b[8]; int p, q; /* special first stage */ b[0] = x[0] + x[7]; b[4] = m->cdct.coef32[16 + 8] * (x[0] - x[7]); for (p = 1, q = 6; p < 4; p++, q--) { b[p] = x[p] + x[q]; b[4 + p] = m->cdct.coef32[16 + 8 + p] * (x[p] - x[q]); } forward_bf(2, 4, b, a, m->cdct.coef32 + 16 + 8 + 4); forward_bf(4, 2, a, b, m->cdct.coef32 + 16 + 8 + 4 + 2); back_bf(2, 4, b, a); back_bf(1, 8, a, c); } /*------------------------------------------------------------*/ /*---------------- 8 pt fdct dual chan---------------------*/ void fdct8_dual(MPEG *m, float x[], float c[]) { float a[8]; /* ping pong buffers */ float b[8]; int p, pp, qq; /* special first stage for interleaved input */ b[0] = x[0] + x[14]; b[4] = m->cdct.coef32[16 + 8] * (x[0] - x[14]); pp = 2; qq = 2 * 6; for (p = 1; p < 4; p++, pp += 2, qq -= 2) { b[p] = x[pp] + x[qq]; b[4 + p] = m->cdct.coef32[16 + 8 + p] * (x[pp] - x[qq]); } forward_bf(2, 4, b, a, m->cdct.coef32 + 16 + 8 + 4); forward_bf(4, 2, a, b, m->cdct.coef32 + 16 + 8 + 4 + 2); back_bf(2, 4, b, a); back_bf(1, 8, a, c); } /*------------------------------------------------------------*/ /*---------------- 8 pt fdct dual to mono---------------------*/ void fdct8_dual_mono(MPEG *m, float x[], float c[]) { float a[8]; /* ping pong buffers */ float b[8]; float t1, t2; int p, pp, qq; /* special first stage */ t1 = 0.5F * (x[0] + x[1]); t2 = 0.5F * (x[14] + x[15]); b[0] = t1 + t2; b[4] = m->cdct.coef32[16 + 8] * (t1 - t2); pp = 2; qq = 2 * 6; for (p = 1; p < 4; p++, pp += 2, qq -= 2) { t1 = 0.5F * (x[pp] + x[pp + 1]); t2 = 0.5F * (x[qq] + x[qq + 1]); b[p] = t1 + t2; b[4 + p] = m->cdct.coef32[16 + 8 + p] * (t1 - t2); } forward_bf(2, 4, b, a, m->cdct.coef32 + 16 + 8 + 4); forward_bf(4, 2, a, b, m->cdct.coef32 + 16 + 8 + 4 + 2); back_bf(2, 4, b, a); back_bf(1, 8, a, c); } /*------------------------------------------------------------*/ <file_sep>/modules/luaSocket/module.c /* DreamShell ##version## module.c - luaSocket module Copyright (C)2011-2014 SWAT */ #include "ds.h" #include <kos/exports.h> DEFAULT_MODULE_HEADER(luaSocket); int luaopen_socket_core(lua_State *L); int lib_open(klibrary_t * lib) { luaopen_socket_core(GetLuaState()); RegisterLuaLib(lib_get_name(), (LuaRegLibOpen *)luaopen_socket_core); return nmmgr_handler_add(&ds_luaSocket_hnd.nmmgr); } int lib_close(klibrary_t * lib) { UnregisterLuaLib(lib_get_name()); return nmmgr_handler_remove(&ds_luaSocket_hnd.nmmgr); } <file_sep>/firmware/bios/bootstrap/makefonts.py #!/usr/bin/env python fd = open("font.bin", "r").read() for i in range(0, len(fd), 12): sub = map(lambda x:ord(x), fd[i:i+12]) print "\t.byte\t0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x" % \ (sub[0], sub[1], sub[2], sub[3], sub[4], sub[5], sub[6], sub[7], sub[8], \ sub[9], sub[10], sub[11]) <file_sep>/modules/mp3/libmp3/xingmp3/csbtb.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** csbtb.c *************************************************** include to csbt.c MPEG audio decoder, dct and window - byte (8 pcm bit output) portable C ******************************************************************/ /*============================================================*/ /*============================================================*/ void windowB(MPEG *m, float *, int , unsigned char *pcm); void windowB_dual(MPEG *m, float *, int , unsigned char *pcm); void windowB16(MPEG *m, float *, int , unsigned char *pcm); void windowB16_dual(MPEG *m, float *, int , unsigned char *pcm); void windowB8(MPEG *m, float *, int , unsigned char *pcm); void windowB8_dual(MPEG *m, float *, int , unsigned char *pcm); /*============================================================*/ void sbtB_mono(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct32(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ void sbtB_dual(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct32_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); fdct32_dual(m,sample + 1, m->csbt.vbuf2 + m->csbt.vb_ptr); windowB_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); windowB_dual(m,m->csbt.vbuf2, m->csbt.vb_ptr, pcm + 1); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 64; } } /*------------------------------------------------------------*/ /* convert dual to mono */ void sbtB_dual_mono(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct32_dual_mono(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /* convert dual to left */ void sbtB_dual_left(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct32_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /* convert dual to right */ void sbtB_dual_right(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; sample++; /* point to right chan */ for (i = 0; i < n; i++) { fdct32_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /*---------------- 16 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ void sbtB16_mono(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct16(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void sbtB16_dual(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct16_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); fdct16_dual(m,sample + 1, m->csbt.vbuf2 + m->csbt.vb_ptr); windowB16_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); windowB16_dual(m,m->csbt.vbuf2, m->csbt.vb_ptr, pcm + 1); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 32; } } /*------------------------------------------------------------*/ void sbtB16_dual_mono(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct16_dual_mono(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void sbtB16_dual_left(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct16_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void sbtB16_dual_right(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; sample++; for (i = 0; i < n; i++) { fdct16_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ /*---------------- 8 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ void sbtB8_mono(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct8(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void sbtB8_dual(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct8_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); fdct8_dual(m,sample + 1, m->csbt.vbuf2 + m->csbt.vb_ptr); windowB8_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); windowB8_dual(m,m->csbt.vbuf2, m->csbt.vb_ptr, pcm + 1); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 16; } } /*------------------------------------------------------------*/ void sbtB8_dual_mono(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct8_dual_mono(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void sbtB8_dual_left(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct8_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void sbtB8_dual_right(MPEG *m, float *sample, unsigned char *pcm, int n) { int i; sample++; for (i = 0; i < n; i++) { fdct8_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); windowB8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ <file_sep>/lib/SDL_gfx/Makefile # DreamShell ##version## # (с) 2008-2014 SWAT # http://www.dc-swat.ru # TARGET = ../libSDL_gfx_2.0.25.a SRCS = \ SDL_framerate.c \ SDL_gfxPrimitives.c \ SDL_imageFilter.c \ SDL_rotozoom.c \ SDL_gfxBlitFunc.c KOS_CFLAGS += -I../../include -I../../include/SDL OBJS = $(SRCS:.c=.o) include ../../sdk/Makefile.library <file_sep>/firmware/isoldr/loader/ubc.c /** * DreamShell ISO Loader * SH4 UBC * (c)2013-2023 SWAT <http://www.dc-swat.ru> * Based on Netplay VOOT code by <NAME> <<EMAIL>> */ #include <main.h> #include <ubc.h> #include <exception.h> extern void ubc_wait(void); void *maple_dma_handler(void *passer, register_stack *stack, void *current_vector); static void *ubc_handler(register_stack *stack, void *current_vector) { if(ubc_is_channel_break(UBC_CHANNEL_A)) { // ubc_clear_channel(UBC_CHANNEL_A); ubc_clear_break(UBC_CHANNEL_B); // LOGF("UBC: A\n"); // dump_regs(stack); #ifdef HAVE_MAPLE if(IsoInfo->emu_vmu) { maple_dma_handler(current_vector, stack, current_vector); } #else (void)stack; #endif } if(ubc_is_channel_break(UBC_CHANNEL_B)) { // ubc_clear_channel(UBC_CHANNEL_A); ubc_clear_break(UBC_CHANNEL_B); // LOGF("UBC: B\n"); // dump_regs(stack); } return current_vector; } void ubc_init() { UBC_R_BBRA = UBC_R_BBRB = 0; UBC_R_BAMRA = UBC_R_BAMRB = UBC_BAMR_NOASID; UBC_R_BRCR = UBC_BRCR_UBDE | UBC_BRCR_PCBA | UBC_BRCR_PCBB; /* set DBR here */ dbr_set(ubc_handler_lowlevel); exception_table_entry entry; entry.type = EXP_TYPE_GEN; entry.code = EXP_CODE_UBC; entry.handler = ubc_handler; exception_add_handler(&entry, NULL); } int ubc_configure_channel(ubc_channel channel, uint32 breakpoint, uint16 options) { switch (channel) { case UBC_CHANNEL_A: UBC_R_BARA = breakpoint; UBC_R_BBRA = options; break; case UBC_CHANNEL_B: UBC_R_BARB = breakpoint; UBC_R_BBRB = options; break; default : return 0; } ubc_wait(); return 1; } void ubc_clear_channel(ubc_channel channel) { switch (channel) { case UBC_CHANNEL_A: UBC_R_BBRA = 0; ubc_clear_break(channel); break; case UBC_CHANNEL_B: UBC_R_BBRB = 0; ubc_clear_break(channel); break; default: return; } ubc_wait(); } void ubc_clear_break(ubc_channel channel) { switch (channel) { case UBC_CHANNEL_A: UBC_R_BRCR &= ~(UBC_BRCR_CMFA); break; case UBC_CHANNEL_B: UBC_R_BRCR &= ~(UBC_BRCR_CMFB); break; default: break; } } int ubc_is_channel_break(ubc_channel channel) { switch (channel) { case UBC_CHANNEL_A : return !!(UBC_R_BRCR & UBC_BRCR_CMFA); break; case UBC_CHANNEL_B: return !!(UBC_R_BRCR & UBC_BRCR_CMFB); break; default: return 0; } } <file_sep>/include/module.h /** * \file module.h * \brief DreamShell module system * \date 2006-2015 * \author SWAT www.dc-swat.ru */ #ifndef _DS_MODULE_H #define _DS_MODULE_H #include <kos.h> #include "utils.h" /** * \brief Addons for KallistiOS exports and library */ /** \brief Look up a symbol by name and path. \param name The name to look up \param path The path to look up \return The export structure, or NULL on failure */ export_sym_t * export_lookup_ex(const char *name, const char *path); /** \brief Look up a symbol by addr. \param name The addr to look up \return The export structure, or NULL on failure */ export_sym_t *export_lookup_by_addr(uint32 addr); /** \brief Look up a library by file name. This function looks up a library by its file name without trying to actually load or open it. This is useful if you want to open a library but not keep around a handle to it (which isn't necessarily encouraged). \param fn The file name of the library to search for \return The library, if found. NULL if not found, errno set as appropriate. \par Error Conditions: \em ENOENT - the library was not found */ klibrary_t *library_lookup_fn(const char * fn); /** * \brief DreamShell module system */ typedef klibrary_t Module_t; int InitModules(); void ShutdownModules(); Module_t *OpenModule(const char *fn); int CloseModule(Module_t *m); int PrintModuleList(int (*pf)(const char *fmt, ...)); #define GetModuleById library_by_libid #define GetModuleByName library_lookup #define GetModuleByFileName library_lookup_fn #define GetModuleName(m) m->lib_get_name() #define GetModuleVersion(m) m->lib_get_version() #define GetModuleId(m) library_get_libid(m) #define GetModuleRefCnt(m) library_get_refcnt(m) uint32 GetExportSymAddr(const char *name, const char *path); const char *GetExportSymName(uint32 addr); #define GET_EXPORT_ADDR(sym_name) GetExportSymAddr(sym_name, NULL) #define GET_EXPORT_ADDR_EX(sym_name, path_name) GetExportSymAddr(sym_name, path_name) #define GET_EXPORT_NAME(sym_addr) GetExportSymName(sym_addr) #define DEFAULT_MODULE_HEADER(name) \ extern export_sym_t ds_##name##_symtab[]; \ static symtab_handler_t ds_##name##_hnd = { \ { "sym/ds/"#name, \ 0, 0x00010000, 0, \ NMMGR_TYPE_SYMTAB, \ NMMGR_LIST_INIT }, \ ds_##name##_symtab \ }; \ char *lib_get_name() { \ return ds_##name##_hnd.nmmgr.pathname + 7; \ } \ uint32 lib_get_version() { \ return DS_MAKE_VER(VER_MAJOR, VER_MINOR, \ VER_MICRO, VER_BUILD); \ } #define DEFAULT_MODULE_EXPORTS(name) \ DEFAULT_MODULE_HEADER(name); \ int lib_open(klibrary_t * lib) { \ return nmmgr_handler_add(&ds_##name##_hnd.nmmgr); \ } \ int lib_close(klibrary_t * lib) { \ return nmmgr_handler_remove(&ds_##name##_hnd.nmmgr); \ } #define DEFAULT_MODULE_EXPORTS_CMD(name, descr) \ DEFAULT_MODULE_HEADER(name); \ int builtin_##name##_cmd(int argc, char *argv[]); \ int lib_open(klibrary_t * lib) { \ AddCmd(lib_get_name(), descr, \ (CmdHandler *) builtin_##name##_cmd); \ return nmmgr_handler_add(&ds_##name##_hnd.nmmgr); \ } \ int lib_close(klibrary_t * lib) { \ RemoveCmd(GetCmdByName(lib_get_name())); \ return nmmgr_handler_remove(&ds_##name##_hnd.nmmgr); \ } #endif <file_sep>/firmware/isoldr/loader/fs/fat/src/diskio.c /** * DreamShell ISO Loader * disk I/O for FatFs * (c)2009-2017 SWAT <http://www.dc-swat.ru> */ #include <main.h> #include "diskio.h" #ifdef DEV_TYPE_SD #include "../dev/sd/sd.h" #endif #ifdef DEV_TYPE_IDE #include <ide/ide.h> #endif /*-------------------------------------------------------------------------- Public Functions ---------------------------------------------------------------------------*/ DWORD get_fattime () { #if 0 ulong now; struct _time_block *tm; DWORD tmr; now = rtc_secs(); tm = conv_gmtime(now); tmr = (((DWORD)tm->year - 60) << 25) | ((DWORD)tm->mon << 21) | ((DWORD)tm->day << 16) | (WORD)(tm->hour << 11) | (WORD)(tm->min << 5) | (WORD)(tm->sec >> 1); return tmr; #else return 0; #endif } /*-----------------------------------------------------------------------*/ /* Inidialize a Drive */ DSTATUS disk_initialize ( BYTE drv /* Physical drive nmuber (0..) */ ) { (void)drv; #ifdef DEV_TYPE_SD return sd_init() ? STA_NOINIT : 0; #endif #ifdef DEV_TYPE_IDE return g1_bus_init() ? STA_NOINIT : 0; #endif return STA_NOINIT; } /*-----------------------------------------------------------------------*/ /* Return Disk Status */ DSTATUS disk_status ( BYTE drv /* Physical drive nmuber (0..) */ ) { (void)drv; #ifdef DEV_TYPE_SD return 0; #endif #ifdef DEV_TYPE_IDE return 0; #endif } /*-----------------------------------------------------------------------*/ /* Read Sector(s) */ DRESULT disk_read ( BYTE drv, /* Physical drive nmuber (0..) */ BYTE *buff, /* Data buffer to store read data */ DWORD sector, /* Sector address (LBA) */ DWORD count /* Number of sectors to read */ ) { (void)drv; #ifdef DEV_TYPE_SD return sd_read_blocks(sector, count, buff, 1) ? RES_ERROR : RES_OK; #endif #ifdef DEV_TYPE_IDE return g1_ata_read_blocks(sector, count, buff, 1) ? RES_ERROR : RES_OK; #endif } DRESULT disk_read_async ( BYTE drv, /* Physical drive nmuber (0..) */ BYTE *buff, /* Data buffer to store read data */ DWORD sector, /* Sector address (LBA) */ DWORD count /* Number of sectors to read */ ) { (void)drv; #ifdef DEV_TYPE_SD return sd_read_blocks(sector, count, buff, 0) ? RES_ERROR : RES_OK; #endif #ifdef DEV_TYPE_IDE return g1_ata_read_blocks(sector, count, buff, 0) ? RES_ERROR : RES_OK; #endif } #ifdef DEV_TYPE_IDE DRESULT disk_read_part ( BYTE drv, /* Physical drive nmuber (0..) */ BYTE *buff, /* Data buffer to store read data */ DWORD sector, /* Sector address (LBA) */ DWORD bytes /* Bytes to read */ ) { (void)drv; return g1_ata_read_lba_dma_part((uint64_t)sector, bytes, buff) ? RES_ERROR : RES_OK; } #endif DRESULT disk_pre_read ( BYTE drv, /* Physical drive nmuber (0..) */ DWORD sector, /* Sector address (LBA) */ DWORD count /* Number of sectors to read */ ) { (void)drv; #ifdef DEV_TYPE_SD (void)sector; (void)count; return RES_OK; #endif #ifdef DEV_TYPE_IDE return g1_ata_pre_read_lba(sector, count) ? RES_ERROR : RES_OK; #endif } /*-----------------------------------------------------------------------*/ /* Write Sector(s) */ #if _FS_READONLY == 0 DRESULT disk_write ( BYTE drv, /* Physical drive nmuber (0..) */ const BYTE *buff, /* Data to be written */ DWORD sector, /* Sector address (LBA) */ DWORD count /* Number of sectors to write */ ) { (void)drv; #ifdef DEV_TYPE_SD return sd_write_blocks(sector, count, buff, 1) ? RES_ERROR : RES_OK; #endif #ifdef DEV_TYPE_IDE return g1_ata_write_blocks(sector, count, buff, fs_dma_enabled()) ? RES_ERROR : RES_OK; #endif } #endif /* _READONLY */ /*-----------------------------------------------------------------------*/ /* Miscellaneous Functions */ DRESULT disk_ioctl ( BYTE drv, /* Physical drive nmuber (0..) */ BYTE ctrl, /* Control code */ void *buff /* Buffer to send/receive control data */ ) { (void)drv; switch (ctrl) { #if _USE_MKFS && !_FS_READONLY case GET_SECTOR_COUNT : /* Get number of sectors on the disk (ulong) */ #ifdef DEV_TYPE_SD *(ulong*)buff = (ulong)(sd_get_size() / 512); #endif #ifdef DEV_TYPE_IDE *(ulong*)buff = (ulong)g1_ata_max_lba(); #endif return RES_OK; #endif /* _USE_MKFS && !_FS_READONLY */ case GET_SECTOR_SIZE : /* Get sectors on the disk (ushort) */ *(ushort*)buff = 512; return RES_OK; #if _FS_READONLY == 0 case CTRL_SYNC : /* Make sure that data has been written */ #ifdef DEV_TYPE_IDE return g1_ata_flush() ? RES_ERROR : RES_OK; #else return RES_OK; #endif #endif default: return RES_PARERR; } } /*-----------------------------------------------------------------------*/ /* Disk Polling */ int disk_poll ( BYTE drv /* Physical drive nmuber (0..) */ ) { (void)drv; #ifdef DEV_TYPE_SD return sd_poll(fs_dma_enabled()); #endif #ifdef DEV_TYPE_IDE return g1_ata_poll(); #endif } /*-----------------------------------------------------------------------*/ /* Disk Aborting */ DRESULT disk_abort ( BYTE drv /* Physical drive nmuber (0..) */ ) { (void)drv; #ifdef DEV_TYPE_SD return sd_abort(); #endif #ifdef DEV_TYPE_IDE g1_ata_abort(); return 0; #endif } <file_sep>/lib/SDL_gui/Picture.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_Picture::GUI_Picture(const char *aname, int x, int y, int w, int h) : GUI_Widget(aname, x, y, w, h), image(NULL) { SetTransparent(1); SetAlign(WIDGET_HORIZ_CENTER | WIDGET_VERT_CENTER); caption = 0; } GUI_Picture::GUI_Picture(const char *aname, int x, int y, int w, int h, GUI_Surface *an_image) : GUI_Widget(aname, x, y, w, h), image(an_image) { SetTransparent(1); SetAlign(WIDGET_HORIZ_CENTER | WIDGET_VERT_CENTER); image->IncRef(); caption = 0; } GUI_Picture::~GUI_Picture() { if (image) image->DecRef(); if (caption) caption->DecRef(); } void GUI_Picture::Update(int force) { GUI_Widget::Update(force); if (caption) caption->DoUpdate(force); } void GUI_Picture::DrawWidget(const SDL_Rect *clip) { if (parent == 0) return; if (image) { SDL_Rect dr; SDL_Rect sr; sr.w = dr.w = image->GetWidth(); sr.h = dr.h = image->GetHeight(); sr.x = sr.y = 0; switch (flags & WIDGET_HORIZ_MASK) { case WIDGET_HORIZ_CENTER: dr.x = area.x + (area.w - dr.w) / 2; break; case WIDGET_HORIZ_LEFT: dr.x = area.x; break; case WIDGET_HORIZ_RIGHT: dr.x = area.x + area.w - dr.w; break; } switch (flags & WIDGET_VERT_MASK) { case WIDGET_VERT_CENTER: dr.y = area.y + (area.h - dr.h) / 2; break; case WIDGET_VERT_TOP: dr.y = area.y; break; case WIDGET_VERT_BOTTOM: dr.y = area.y + area.h - dr.h; break; } if (GUI_ClipRect(&sr, &dr, clip)) parent->Draw(image, &sr, &dr); } } int GUI_Picture::Event(const SDL_Event *event, int xoffset, int yoffset) { if (caption) { if (caption->Event(event, xoffset + area.x, yoffset + area.y)) return 1; } return GUI_Widget::Event(event, xoffset, yoffset); } void GUI_Picture::SetImage(GUI_Surface *an_image) { if (GUI_ObjectKeep((GUI_Object **) &image, an_image)) MarkChanged(); } void GUI_Picture::SetCaption(GUI_Widget *a_caption) { Keep(&caption, a_caption); } extern "C" { GUI_Widget *GUI_PictureCreate(const char *name, int x, int y, int w, int h, GUI_Surface *image) { return new GUI_Picture(name, x, y, w, h, image); } int GUI_PictureCheck(GUI_Widget *widget) { // FIXME not implemented return 0; } void GUI_PictureSetImage(GUI_Widget *widget, GUI_Surface *image) { ((GUI_Picture *) widget)->SetImage(image); } void GUI_PictureSetCaption(GUI_Widget *widget, GUI_Widget *caption) { ((GUI_Picture *) widget)->SetCaption(caption); } } <file_sep>/commands/vmode/main.c /* DreamShell ##version## vmode.c Copyright (C) 2011-2014 SWAT */ #include "ds.h" int main(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s option args...\n\n" "Options: \n" " -m, --mode - Set video mode\n" " -l, --list - Show list of video modes\n" " -c, --clear - Clear the display with color\n" " -e, --empty - Clear VRAM\n" " -o, --border - Set video border color\n\n" "Arguments: \n" " -d, --display - Display mode from list\n" " -p, --pixel - Pixel mode from list\n" " -r, --red - Red color for clear screen\n" " -g, --green - green color for clear screen\n" " -b, --blue - Blue color for clear screen\n\n" "Example: %s -m -d 1 -p 1\n", argv[0], argv[0]); return CMD_NO_ARG; } int mode = 0, list = 0, clear = 0, empty = 0, border = 0, display = 0, pixel = PM_RGB565; int r = 0, g = 0, b = 0; struct cfg_option options[] = { {"mode", 'm', NULL, CFG_BOOL, (void *) &mode, 0}, {"clear", 'c', NULL, CFG_BOOL, (void *) &clear, 0}, {"empty", 'e', NULL, CFG_BOOL, (void *) &empty, 0}, {"border", 'o', NULL, CFG_BOOL, (void *) &border, 0}, {"list", 'l', NULL, CFG_BOOL, (void *) &list, 0}, {"pixel", 'p', NULL, CFG_INT, (void *) &pixel, 0}, {"display",'d', NULL, CFG_INT, (void *) &display,0}, {"red", 'r', NULL, CFG_INT, (void *) &r, 0}, {"green", 'g', NULL, CFG_INT, (void *) &g, 0}, {"blue", 'b', NULL, CFG_INT, (void *) &b, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(mode) { if(pixel == PM_RGB565) { SetVideoMode(display); } else { vid_set_mode(display, pixel); } return CMD_OK; } if(clear) { vid_clear(r, g, b); return CMD_OK; } if(empty) { vid_empty(); return CMD_OK; } if(border) { vid_border_color(r, g, b); return CMD_OK; } if(list) { ds_printf( " Pixel modes: \n" " 0 - RGB555 pixel mode (15-bit)\n" " 1 - RGB565 pixel mode (16-bit), default\n" " 3 - RGB888 pixel mode (24-bit)\n\n"); ds_printf( " Display modes: \n" " 1 - 320x240 VGA 60Hz \n" " 2 - 320x240 NTSC 60Hz \n" " 3 - 640x480 VGA 60Hz \n" " 4 - 640x480 NTSC Interlaced 60Hz \n" " 5 - 800x608 VGA 60Hz \n" " 6 - 640x480 PAL Interlaced 50Hz \n" " 7 - 256x256 PAL Interlaced 50Hz \n" " 8 - 768x480 NTSC Interlaced 60Hz \n" " 9 - 768x576 PAL Interlaced 50Hz \n" " 10 - 768x480 PAL Interlaced 50Hz \n"); ds_printf( " 11 - 320x240 PAL 50Hz \n" " 12 - 320x240 VGA 60Hz, 4FBs \n" " 13 - 320x240 NTSC 60Hz, 4FBs \n" " 14 - 640x480 VGA 60Hz, 4FBs \n" " 15 - 640x480 NTSC IL 60Hz, 4FBs \n" " 16 - 800x608 VGA 60Hz, 4FBs \n" " 17 - 640x480 PAL IL 50Hz, 4FBs \n" " 18 - 256x256 PAL IL 50Hz, 4FBs \n" " 19 - 768x480 NTSC IL 60Hz, 4FBs \n" " 20 - 768x576 PAL IL 50Hz, 4FBs \n" " 21 - 768x480 PAL IL 50Hz, 4FBs \n" " 22 - 320x240 PAL 50Hz, 4FBs \n\n"); return CMD_OK; } ds_printf("DS_ERROR: There is no option.\n"); return CMD_NO_ARG; } <file_sep>/firmware/isoldr/loader/kos/net/core.c /* KallistiOS ##version## kos/net/core.c Copyright (C)2002,2004 <NAME> Copyright (C)2010-2014 SWAT */ #include <main.h> #include <net/net.h> #include <dc/net/broadband_adapter.h> #include <dc/net/lan_adapter.h> /* This module, and others in this tree, handle the architecture-independent part of the networking system of KOS. They serve the following purposes: - Specific network card drivers may register themselves using the functions here, if their hardware is present - Link-level messages will be handled here, such as ARP - The whole networking system can be enabled or disabled from here */ // This static table is for Slinkie. static netif_t * netifs[] = { &bba_if, &la_if, NULL }; netif_t * nif = NULL; // Static packet rx/tx buffers, to save space. uint8 net_rxbuf[1514], net_txbuf[1514]; // Our IP address, if we know it. uint32 net_ip = 0; // Host PC's IP, MAC address, and port, if we know it. uint32 net_host_ip = 0; uint16 net_host_port = 0; uint8 net_host_mac[6] = {0}; volatile int net_exit_loop = 0; volatile int net_rpc_ret = 0; int net_bcast_input(netif_t * drv, uint8 * pkt, int size) { eth_hdr_t * eth; eth = (eth_hdr_t *)(net_rxbuf + 0); (void)pkt; DBG("bcast packet\n"); // Is it an ARP packet? if (eth->type[1] == 0x06) { DBG("arp packet\n"); return net_arp_input(drv, net_rxbuf, size); } return 0; } int net_to_me_input(netif_t * drv, uint8 * pkt, int size) { eth_hdr_t * eth; ip_hdr_t * ip; int i; eth = (eth_hdr_t *)(pkt + 0); ip = (ip_hdr_t *)(pkt + sizeof(eth_hdr_t)); // Ignore non-IPv4 packets if (eth->type[1] != 0x00) return 0; // Ignore fragments if (ntohs(ip->flags_frag_offs) & 0x3fff) { DBG("net_to_me_input: fragmented packet\n"); return 0; } // Check the IP checksum i = ip->checksum; ip->checksum = 0; ip->checksum = net_checksum((uint16 *)ip, 2*(ip->version_ihl & 0x0f)); if (i != ip->checksum) { DBG("net_to_me_input: ip with invalid checksum\n"); return 0; } // What protocol are we looking at? switch (ip->protocol) { case 1: // ICMP DBG("icmp packet\n"); return net_icmp_input(drv, net_rxbuf, size); case 17: // UDP DBG("udp packet\n"); return net_udp_input(drv, net_rxbuf, size); } return 0; } static uint8 bcast[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; int net_input(struct knetif * drv, int size) { eth_hdr_t * eth; eth = (eth_hdr_t *)(net_rxbuf + 0); // Ignore non-IP packets. if (eth->type[0] != 0x08) { DBG("ignoring non-IP packet\n"); return 0; } // Is it a broadcast packet? if (!memcmp(eth->dest, bcast, 6)) return net_bcast_input(drv, net_rxbuf, size); return net_to_me_input(drv, net_rxbuf, size); } /* Perform an IP-style checksum on a block of data */ uint16 net_checksum(uint16 *data, int words) { uint32 sum; int i; sum = 0; for (i=0; i<words; i++) { sum += data[i]; if (sum & 0xffff0000) { sum &= 0xffff; sum++; } } return ~(sum & 0xffff); } uint8 * net_resp_build() { eth_hdr_t * srceth, * dsteth; ip_hdr_t * srcip, * dstip; udp_pkt_t * srcudp, * dstudp; // Copy over the ethernet header, swapping the src/dest. srceth = (eth_hdr_t *)(net_rxbuf + 0); dsteth = (eth_hdr_t *)(net_txbuf + 0); memcpy(dsteth->dest, srceth->src, 6); memcpy(dsteth->src, srceth->dest, 6); memcpy(dsteth->type, srceth->type, 2); // Copy over the IP header, swapping the src/dest. srcip = (ip_hdr_t *)(net_rxbuf + sizeof(eth_hdr_t)); dstip = (ip_hdr_t *)(net_txbuf + sizeof(eth_hdr_t)); dstip->version_ihl = 0x45; dstip->tos = 0; dstip->length = 0; dstip->packet_id = 0; dstip->flags_frag_offs = htons(0x4000); dstip->ttl = 0x40; dstip->protocol = srcip->protocol; dstip->checksum = 0; dstip->src = srcip->dest; dstip->dest = srcip->src; // Copy over the UDP header, swapping the src/dest. srcudp = (udp_pkt_t *)(net_rxbuf + sizeof(eth_hdr_t) + 4*(srcip->version_ihl & 0x0f)); dstudp = (udp_pkt_t *)(net_txbuf + sizeof(eth_hdr_t) + 4*(dstip->version_ihl & 0x0f)); dstudp->src_port = srcudp->dest_port; dstudp->dest_port = srcudp->src_port; dstudp->checksum = 0; return dstudp->data; } uint8 * net_tx_build() { eth_hdr_t * dsteth; ip_hdr_t * dstip; udp_pkt_t * dstudp; // Build the ethernet header dsteth = (eth_hdr_t *)(net_txbuf + 0); memcpy(dsteth->dest, net_host_mac, 6); memcpy(dsteth->src, nif->mac_addr, 6); dsteth->type[0] = 8; dsteth->type[1] = 0; // Build the IP header dstip = (ip_hdr_t *)(net_txbuf + sizeof(eth_hdr_t)); dstip->version_ihl = 0x45; dstip->tos = 0; dstip->length = 0; dstip->packet_id = 0; dstip->flags_frag_offs = htons(0x4000); dstip->ttl = 0x40; dstip->protocol = 17; dstip->checksum = 0; dstip->src = htonl(net_ip); dstip->dest = htonl(net_host_ip); // Build the UDP header dstudp = (udp_pkt_t *)(net_txbuf + sizeof(eth_hdr_t) + 4*(dstip->version_ihl & 0x0f)); dstudp->src_port = htons(31313); dstudp->dest_port = htons(net_host_port); dstudp->checksum = 0; return dstudp->data; } void net_resp_complete(int length) { ip_hdr_t * ip; udp_pkt_t * udp; udp_pseudo_pkt_t * pseudo; // Get pointers ip = (ip_hdr_t *)(net_txbuf + sizeof(eth_hdr_t)); udp = (udp_pkt_t *)(net_txbuf + sizeof(eth_hdr_t) + 4*(ip->version_ihl & 0x0f)); // Finish up length fields ip->length = htons(sizeof(ip_hdr_t) + sizeof(udp_pkt_t) + length); udp->length = htons(sizeof(udp_pkt_t) + length); // RX should be free now, so we'll work in there. Copy stuff over // for the UDP pseudo packet. pseudo = (udp_pseudo_pkt_t *)net_rxbuf; pseudo->src_ip = ip->src; pseudo->dest_ip = ip->dest; pseudo->zero = 0; pseudo->protocol = ip->protocol; pseudo->udp_length = udp->length; pseudo->src_port = udp->src_port; pseudo->dest_port = udp->dest_port; pseudo->length = udp->length; pseudo->checksum = 0; memcpy(pseudo->data, udp->data, length); pseudo->data[length] = 0; // Do the UDP checksum. udp->checksum = net_checksum((uint16 *)pseudo, (sizeof(udp_pseudo_pkt_t) + length + 1) / 2); if (udp->checksum == 0) udp->checksum = 0xffff; // Now do the IP checksum as well. ip->checksum = 0; ip->checksum = net_checksum((uint16 *)ip, 2 * (ip->version_ihl & 0x0f)); // Transmit the full packet. nif->if_tx(nif, net_txbuf, sizeof(eth_hdr_t) + sizeof(ip_hdr_t) + sizeof(udp_pkt_t) + length); } uint16 ntohs(uint16 n) { return ((n & 0xff) << 8) | ((n >> 8) & 0xff); } uint32 ntohl(uint32 n) { return (((n >> 0) & 0xff) << 24) | (((n >> 8) & 0xff) << 16) | (((n >> 16) & 0xff) << 8) | (((n >> 24) & 0xff) << 0); } int net_loop() { net_exit_loop = 0; while (!net_exit_loop) { nif->if_rx_poll(nif); } return 0; } // Thanks to dcload-ip for this super-simple parse algorithm. /* void net_setup_ip() { int i, c; uint8 * ip = (uint8 *)&net_ip; for (net_ip=0,i=3,c=0; DREAMCAST_IP[c]; c++) { if (DREAMCAST_IP[c] != '.') { ip[i] *= 10; ip[i] += DREAMCAST_IP[c] - '0'; } else i--; } //DBG("our IP is (%s) %08lx\n", DREAMCAST_IP, net_ip); }*/ #include "main.h" static void _setup_ip(const char *cip, uint8 * ip) { int i, c; for (net_ip=0,i=3,c=0; cip[c]; c++) { if (cip[c] != '.') { ip[i] *= 10; ip[i] += cip[c] - '0'; } else i--; } } void net_setup_ip() { /* int i, c; uint8 * ip = (uint8 *)&net_ip; for (net_ip=0,i=3,c=0; IsoInfo.ip[c]; c++) { if (IsoInfo.ip[c] != '.') { ip[i] *= 10; ip[i] += IsoInfo.ip[c] - '0'; } else i--; }*/ uint8 * ip = (uint8 *)&net_ip; uint8 * host = (uint8 *)&net_host_ip; _setup_ip("192.168.1.110", ip); _setup_ip("192.168.1.100", host); net_host_port = 31313; DBG("Our IP is %08lx", net_ip); DBG("Host IP is %08lx", net_host_ip); } /* Device detect / init */ int net_init() { int i; // If we know our IP then set it up. net_setup_ip(); bba_init(); la_init(); for (i=0; netifs[i]; i++) { nif = netifs[i]; /* Make sure we have one */ if (nif->if_detect(nif) < 0) { DBG("'%s' failed detect\n", nif->descr); continue; } /* Ok, we do -- initialize it */ if (nif->if_init(nif) < 0) { DBG("'%s' failed init\n", nif->descr); continue; } /* It's initialized, so now enable it */ if (nif->if_start(nif) < 0) { DBG("'%s' failed start\n", nif->descr); nif->if_shutdown(nif); continue; } return 0; } nif = NULL; return -1; } <file_sep>/lib/SDL_gui/Label.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" // // A label which favors memory consumption over speed. // GUI_Label::GUI_Label(const char *aname, int x, int y, int w, int h, GUI_Font *afont, const char *s) : GUI_Widget(aname, x, y, w, h), font(afont) { SetTransparent(1); SetAlign(WIDGET_HORIZ_CENTER | WIDGET_VERT_CENTER); textcolor.r = 0; textcolor.g = 0; textcolor.b = 0; text = 0; SetText(s); font->IncRef(); wtype = WIDGET_TYPE_OTHER; } GUI_Label::~GUI_Label() { if (text) delete [] text; font->DecRef(); } void GUI_Label::SetFont(GUI_Font *afont) { if (GUI_ObjectKeep((GUI_Object **) &font, afont)) MarkChanged(); } void GUI_Label::SetTextColor(int r, int g, int b) { textcolor.r = r; textcolor.g = g; textcolor.b = b; MarkChanged(); } void GUI_Label::SetText(const char *s) { delete [] text; text = new char[strlen(s)+1]; strcpy(text, s); MarkChanged(); } char *GUI_Label::GetText() { return text; } void GUI_Label::DrawWidget(const SDL_Rect *clip) { if (parent == 0) return; if (text && font) { GUI_Surface *image = font->RenderQuality(text, textcolor); SDL_Rect dr; SDL_Rect sr; sr.w = dr.w = image->GetWidth(); sr.h = dr.h = image->GetHeight(); sr.x = sr.y = 0; switch (flags & WIDGET_HORIZ_MASK) { case WIDGET_HORIZ_LEFT: dr.x = area.x; break; case WIDGET_HORIZ_RIGHT: dr.x = area.x + area.w - dr.w; break; case WIDGET_HORIZ_CENTER: default: dr.x = area.x + (area.w - dr.w) / 2; break; } switch (flags & WIDGET_VERT_MASK) { case WIDGET_VERT_TOP: dr.y = area.y; break; case WIDGET_VERT_BOTTOM: dr.y = area.y + area.h - dr.h; break; case WIDGET_VERT_CENTER: default: dr.y = area.y + (area.h - dr.h) / 2; break; } if (GUI_ClipRect(&sr, &dr, clip)) { parent->Erase(&area); parent->Draw(image, &sr, &dr); } image->DecRef(); } } extern "C" { GUI_Widget *GUI_LabelCreate(const char *name, int x, int y, int w, int h, GUI_Font *font, const char *text) { return new GUI_Label(name, x, y, w, h, font, text); } int GUI_LabelCheck(GUI_Widget *widget) { // FIXME not implemented return 0; } void GUI_LabelSetFont(GUI_Widget *widget, GUI_Font *font) { ((GUI_Label *) widget)->SetFont(font); } void GUI_LabelSetTextColor(GUI_Widget *widget, int r, int g, int b) { ((GUI_Label *) widget)->SetTextColor(r,g,b); } void GUI_LabelSetText(GUI_Widget *widget, const char *text) { ((GUI_Label *) widget)->SetText(text); } char *GUI_LabelGetText(GUI_Widget *widget) { return ((GUI_Label *) widget)->GetText(); } } <file_sep>/applications/speedtest/modules/app_module.h /* DreamShell ##version## app_module.h - Speedtest app module header Copyright (C)2014 megavolt85 Copyright (C)2014-2023 SWAT http://www.dc-swat.ru */ #include "ds.h" void Speedtest_Run(GUI_Widget *widget); void Speedtest_Init(App_t *app); <file_sep>/lib/libparallax/doc/readme.txt Parallax for KOS ##version## (c)2002 <NAME> What is it? ----------- Parallax is my answer to wanting a nice, simple API with which to write mostly-2D games for KOS. <NAME> and I both needed something like this which is faster (and cuts around much of the properness of things like KGL) for our projects, and so we sat down and came up with a basic list of requirements and specs, and I got to coding. Basic requirements ------------------ These are the basic requirements we shared: - Emphasis on 2D usage, but allow for 3D to be integrated as well without having to fall back to using parts of KGL or whatnot. - Speed is an essential priority for things like submitting sprites and vertices; thus anything in the main code path needs to be inlined or made into macros if at all possible, and even use DR where possible. - Everything should be based around supporting and enhancing the native libraries rather than replacing them. Thus Parallax can be used with the PVR API or inside a KGL program as if it were all straight PVR calls. - Provide typedefs and macros for common DC anachronisms so that if a port is done of the library to another platform later, porting any client code that uses it is a lot easier. - All the basic functionality should be C-based so that it can be easily plugged into various C++ high-level libraries or used from C programs by other programmers. More specific goals / features can be seen in the document "specs.txt". License ------- Parallax is licensed under the same license as KOS (BSD-style). See README.KOS for more specific information. <file_sep>/modules/telnetd/module.c /* DreamShell ##version## module.c - telnetd module Copyright (C)2012-2013 SWAT */ #include "ds.h" #include "network/telnet.h" DEFAULT_MODULE_EXPORTS_CMD(telnetd, "DreamShell telnet server"); int builtin_telnetd_cmd(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s options args\n" "Options: \n" " -s, --start -Start server\n" " -t, --stop -Stop server\n\n" "Arguments: \n" " -p, --port -Server listen port (default 23)\n\n" "Example: %s --start\n\n", argv[0], argv[0]); return CMD_NO_ARG; } int start_srv = 0, stop_srv = 0, port = 0; struct cfg_option options[] = { {"start", 's', NULL, CFG_BOOL, (void *) &start_srv, 0}, {"stop", 't', NULL, CFG_BOOL, (void *) &stop_srv, 0}, {"port", 'p', NULL, CFG_INT, (void *) &port, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(start_srv) { telnetd_init(port); return CMD_OK; } if(stop_srv) { telnetd_shutdown(); return CMD_OK; } return CMD_OK; } <file_sep>/include/vmu.h /** * \file vmu.h * \brief DreamShell VMU utils * \date 2013 * \author SWAT * \copyright http://www.dc-swat.ru */ #ifndef _DS_VMU_H_ #define _DS_VMU_H_ /** * Draw string on VMU LCD */ void vmu_draw_string(const char *str); void vmu_draw_string_xy(const char *str, int x, int y); #endif /* _DS_VMU_H_ */ <file_sep>/include/drivers/bflash.h /** * \file bflash.h * \brief Bios flash chip driver * \date 2009-2014 * \author SWAT www.dc-swat.ru */ #ifndef __BIOS_FLASH_H #define __BIOS_FLASH_H #include <arch/types.h> /** * Currently supported flash chips: * AMD Am29LV800T 1024 KB 3V Am29LV800B 1024 KB 3V Am29LV160DT 2048 KB 3V Am29LV160DB 2048 KB 3V Am29F160DT 2048 KB 5V Am29F160DB 2048 KB 5V STMicroelectronics M29W800T 1024 KB 3V M29W800B 1024 KB 3V M29W160BT 2048 KB 3V M29W160BB 2048 KB 3V Macronix MX29F400 512 KB 5V MX29F1610 2048 KB 5V MX29F016 2048 KB 5V MX29LV160T 2048 KB 3V MX29LV160B 2048 KB 3V MX29LV320T 4096 KB 3V MX29LV320B 4096 KB 3V MX29L3211 4096 KB 3V AMIC A29L160AT 2048 KB 3V A29L160AB 2048 KB 3V ESMT F49L160UA 2048 KB 3V F49L160BA 2048 KB 3V Sega MPR-XXXXX 2048 KB 3V,5V (detect and read only) */ /** * \brief Flash chip base address */ #define BIOS_FLASH_ADDR 0xa0000000 /** \defgroup bflash_flags Flash chip features flags @{ */ #define F_FLASH_READ 0x0001 #define F_FLASH_PROGRAM 0x0002 #define F_FLASH_SLEEP 0x0004 #define F_FLASH_ABORT 0x0008 #define F_FLASH_ERASE_SECTOR 0x0020 #define F_FLASH_ERASE_ALL 0x0040 #define F_FLASH_ERASE_SUSPEND 0x0080 #define F_FLASH_LOGIC_3V 0x0200 #define F_FLASH_LOGIC_5V 0x0400 /** @} */ /** \defgroup prog_method_flags Flash chip programming algorithm flags @{ */ #define F_FLASH_UNKNOWN_PM 0x0000 #define F_FLASH_DATAPOLLING_PM 0x0001 #define F_FLASH_REGPOLLING_PM 0x0002 /** @} */ /** * \brief Flash chip manufacturer info */ typedef struct bflash_manufacturer { char *name; uint16 id; } bflash_manufacturer_t; /** * \brief Flash chip device info */ typedef struct bflash_dev { char *name; uint16 id; uint16 flags; uint16 unlock[2]; uint16 size; /* KBytes */ uint16 page_size; /* Bytes */ uint16 sec_count; uint32 *sectors; uint16 prog_mode; } bflash_dev_t; /** * \brief Internal manufacturers list * Last entry zero filled (except for name) */ extern const bflash_manufacturer_t bflash_manufacturers[]; /** * \brief Internal devices list * Last entry zero filled (except for name) */ extern const bflash_dev_t bflash_devs[]; /** * \brief Find flash manufacturer by id in internal list */ bflash_manufacturer_t *bflash_find_manufacturer(uint16 mfr_id); /** * \brief Find flash chip device by id in internal list */ bflash_dev_t *bflash_find_dev(uint16 dev_id); /** * \brief Return sector index by sector addr */ int bflash_get_sector_index(bflash_dev_t *dev, uint32 addr); /** * \brief Return 0 if detected supported flash chip */ int bflash_detect(bflash_manufacturer_t **mfr, bflash_dev_t **dev); /** * \brief Erase a sector of flash */ int bflash_erase_sector(bflash_dev_t *dev, uint32 addr); /** * \brief Erase the whole flash chip */ int bflash_erase_all(bflash_dev_t *dev); /** * \brief Sector/Chip erase suspend */ int bflash_erase_suspend(bflash_dev_t *dev); /** * \brief Sector/Chip erase resume */ int bflash_erase_resume(bflash_dev_t *dev); /** * \brief The Sleep command allows the device to complete current operations * before going into Sleep mode. */ int bflash_sleep(bflash_dev_t *dev); /** * \brief This mode only stops Page program or Sector/Chip erase operation currently in progress * and puts the device in Sleep mode. */ int bflash_abort(bflash_dev_t *dev); /** * \brief If program-fail or erase-fail happen, reset the device to abort the operation */ void bflash_reset(bflash_dev_t *dev); /** * \brief Write a single flash value, return -1 if we fail or timeout */ int bflash_write_value(bflash_dev_t *dev, uint32 addr, uint8 value); /** * \brief Write a page of flash, return -1 if we fail or timeout */ int bflash_write_page(bflash_dev_t *dev, uint32 addr, uint8 *data); /** * \brief Write a buffer of data */ int bflash_write_data(bflash_dev_t *dev, uint32 addr, void *data, uint32 len); /** * \brief Detecting flash device, erasing needed sectors * (or all chip, use F_BIOS_ERASE* flags value for erase_mode) * and writing firmware file to the flash memory */ int bflash_auto_reflash(const char *file, uint32 start_sector, int erase_mode); #endif /* __BIOS_FLASH_H */ <file_sep>/lib/SDL_gui/Drawable.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" extern "C" { void UpdateActiveMouseCursor(); } static int Inside(int x, int y, SDL_Rect *r) { return (x >= r->x) && (x < r->x + r->w) && (y >= r->y) && (y < r->y + r->h); } GUI_Drawable::GUI_Drawable(const char *aname, int x, int y, int w, int h) : GUI_Object(aname) { flags = 0; status_callback = 0; focused = 0; area.x = x; area.y = y; area.w = w; area.h = h; wtype = WIDGET_TYPE_OTHER; } GUI_Drawable::~GUI_Drawable(void) { } int GUI_Drawable::GetWidth(void) { return area.w; } int GUI_Drawable::GetHeight(void) { return area.h; } void GUI_Drawable::SetWidth(int w) { area.w = w; MarkChanged(); } void GUI_Drawable::SetHeight(int h) { area.h = h; MarkChanged(); } SDL_Rect GUI_Drawable::Adjust(const SDL_Rect *rp) { SDL_Rect r; //assert(rp != NULL); if(rp != NULL) { r.x = rp->x + area.x; r.y = rp->y + area.y; r.w = rp->w; r.h = rp->h; } else { r.x = 0; r.y = 0; r.w = 0; r.h = 0; } return r; } void GUI_Drawable::Draw(GUI_Surface *image, const SDL_Rect *sr, const SDL_Rect *dr) { } void GUI_Drawable::Fill(const SDL_Rect *dr, SDL_Color c) { } void GUI_Drawable::Erase(const SDL_Rect *dr) { } void GUI_Drawable::RemoveWidget(GUI_Widget *widget) { } void GUI_Drawable::Notify(int mask) { flag_delta = mask; if (status_callback) status_callback->Call(this); } void GUI_Drawable::WriteFlags(int andmask, int ormask) { //ds_printf("GUI_Drawable::WriteFlags: %s\n", GetName()); int oldflags = flags; flags = (flags & andmask) | ormask; if (flags != oldflags) Notify(flags ^ oldflags); } void GUI_Drawable::SetFlags(int mask) { WriteFlags(-1, mask); } void GUI_Drawable::ClearFlags(int mask) { WriteFlags(~mask, 0); } int GUI_Drawable::Event(const SDL_Event *event, int xoffset, int yoffset) { GUI_Screen *screen = GUI_GetScreen(); /* FIXME GUI_GetScreen(); */ GUI_Drawable *focus = screen->GetFocusWidget(); /* FIXME screen->GetFocusWidget(); */ switch (event->type) { /* case SDL_KEYDOWN: return GUI_DrawableKeyPressed(object, event->key.keysym.sym, event->key.keysym.unicode); case SDL_KEYUP: return GUI_DrawableKeyReleased(object, event->key.keysym.sym, event->key.keysym.unicode); */ case SDL_MOUSEBUTTONDOWN: { int x = event->button.x - xoffset; int y = event->button.y - yoffset; if ((flags & WIDGET_DISABLED) == 0/* && (flags & WIDGET_HIDDEN) == 0*/) { if (Inside(x, y, &area)) if (focus == 0 || focus == this) { SetFlags(WIDGET_PRESSED); UpdateActiveMouseCursor(); } } break; } case SDL_MOUSEBUTTONUP: { int x = event->button.x - xoffset; int y = event->button.y - yoffset; if ((flags & WIDGET_DISABLED) == 0/* && (flags & WIDGET_HIDDEN) == 0*/) { if (flags & WIDGET_PRESSED) if (Inside(x, y, &area)) if (focus == 0 || focus == this) { // ds_printf("Mouse button: %d\n", event->button.button); if(event->button.button != 1) { Clicked(x, y); } else { ContextClicked(x, y); } } } if (flags & WIDGET_PRESSED) { ClearFlags(WIDGET_PRESSED); UpdateActiveMouseCursor(); } break; } case SDL_MOUSEMOTION: { int x = event->motion.x - xoffset; int y = event->motion.y - yoffset; if (focus == 0 || focus == this) { if ((flags & WIDGET_DISABLED) == 0/* && (flags & WIDGET_HIDDEN) == 0*/ && Inside(x, y, &area)) { if(!focused) { SetFlags(WIDGET_INSIDE); UpdateActiveMouseCursor(); Highlighted(x, y); focused = 1; } } else { if((flags & WIDGET_DISABLED) == 0) { if(focused) { ClearFlags(WIDGET_INSIDE); UpdateActiveMouseCursor(); unHighlighted(x, y); focused = 0; } } } } break; } } return 0; } void GUI_Drawable::Clicked(int x, int y) { } void GUI_Drawable::ContextClicked(int x, int y) { } void GUI_Drawable::Highlighted(int x, int y) { } void GUI_Drawable::unHighlighted(int x, int y) { } void GUI_Drawable::Update(int force) { } GUI_Drawable *GUI_Drawable::GetParent(void) { return NULL; } int GUI_Drawable::GetWType(void) { return wtype; } void GUI_Drawable::DoUpdate(int force) { if (flags & WIDGET_CHANGED) { force = 1; } Update(force); flags &= ~WIDGET_CHANGED; } /* mark as changed so it will be drawn in the next update */ void GUI_Drawable::MarkChanged() { flags |= WIDGET_CHANGED; } /* tile an image over an area on a widget */ void GUI_Drawable::TileImage(GUI_Surface *surface, const SDL_Rect *rp, int x_offset, int y_offset) { SDL_Rect sr, dr; int xp, yp, bw, bh; //assert(surface != NULL); //assert(rp != NULL); if(surface == NULL || rp == NULL) return; bw = surface->GetWidth(); bh = surface->GetHeight(); //ds_printf("GUI_Drawable::TileImage: xo=%d yo=%d\n", x_offset, y_offset); for (xp=0; xp < rp->w; xp += sr.w) { dr.x = rp->x+xp; sr.x = (dr.x + x_offset) % bw; sr.w = dr.w = bw - sr.x; if (dr.x + dr.w > rp->x + rp->w) sr.w = dr.w = rp->x + rp->w - dr.x; for (yp=0; yp < rp->h; yp += sr.h) { dr.y = rp->y+yp; sr.y = (dr.y + y_offset) % bh; sr.h = dr.h = bh - sr.y; if (dr.y + dr.h > rp->y + rp->h) sr.h = dr.h = rp->y + rp->h - dr.y; Draw(surface, &sr, &dr); } } } void GUI_Drawable::CenterImage(GUI_Surface *surface, const SDL_Rect *rp, int x_offset, int y_offset) { SDL_Rect sr, dr; int bw, bh;//, cx, cy; if(surface == NULL) return; // ds_printf("%s: %d %d %d %d\n", __func__, rp->x, rp->y, rp->w, rp->h); bw = surface->GetWidth(); bh = surface->GetHeight(); sr.x = 0; sr.y = 0; sr.w = bw; sr.h = bh; dr.x = (area.w / 2) - (bw / 2) + x_offset; dr.y = (area.h / 2) - (bh / 2) + y_offset; dr.w = bw; dr.h = bh; Draw(surface, &sr, &dr); // dr.x = rp->x; // sr.x = (dr.x + x_offset) % bw; // sr.w = dr.w = bw - sr.x; // // if (dr.x + dr.w > rp->x + rp->w) // sr.w = dr.w = rp->x + rp->w - dr.x; // // dr.y = rp->y; // sr.y = (dr.y + y_offset) % bh; // sr.h = dr.h = bh - sr.y; // // if (dr.y + dr.h > rp->y + rp->h) // sr.h = dr.h = rp->y + rp->h - dr.y; // // cx = (area.w / 2) - (bw / 2) + x_offset; // cy = (area.h / 2) - (bh / 2) + y_offset; // sr.x += cx; // sr.y += cy; // dr.x += cx; // dr.y += cy; // if(sr.x < cx + bw && sr.x >= cx + bw) { // if(sr.y < cy + bh && sr.y >= cy + bh) { // ds_printf("%s: %d %d %d %d -> %d %d %d %d\n", __func__, sr.x, sr.y, sr.w, sr.h, dr.x, dr.y, dr.w, dr.h); // Draw(surface, &sr, &dr); // } // } } void GUI_Drawable::Keep(GUI_Widget **target, GUI_Widget *source) { if (*target != source) { if (source) source->IncRef(); if (*target) { (*target)->SetParent(0); (*target)->DecRef(); } if (source) source->SetParent(this); (*target) = source; MarkChanged(); } } SDL_Rect GUI_Drawable::GetArea() { return area; } void GUI_Drawable::SetPosition(int x, int y) { area.x = x; area.y = y; MarkChanged(); } void GUI_Drawable::SetSize(int w, int h) { area.w = w; area.h = h; MarkChanged(); } void GUI_Drawable::SetStatusCallback(GUI_Callback *callback) { GUI_ObjectKeep((GUI_Object **) &status_callback, callback); } int GUI_Drawable::GetFlagDelta(void) { return flag_delta; } int GUI_Drawable::GetFlags(void) { return flags; } <file_sep>/applications/iso_loader/modules/utils.c /* DreamShell ##version## utils.c - ISO Loader app utils Copyright (C) 2022 SWAT */ #include "ds.h" #include "isoldr.h" #include "app_utils.h" /* Trim begin/end spaces and copy into output buffer */ void trim_spaces(char *input, char *output, int size) { char *p; char *o; p = input; o = output; while(*p == ' ' && input + size > p) { p++; } while(input + size > p) { *o = *p; p++; o++; } *o = '\0'; o--; while(*o == ' ' && o > output) { *o='\0'; o--; } } char *trim_spaces2(char *txt) { int32_t i; while(txt[0] == ' ') { txt++; } int32_t len = strlen(txt); for(i=len; i ; i--) { if(txt[i] > ' ') break; txt[i] = '\0'; } return txt; } char *fix_spaces(char *str) { if(!str) return NULL; int i, len = (int) strlen(str); for(i=0; i<len; i++) { if(str[i] == ' ') str[i] = '\\'; } return str; } int conf_parse(isoldr_conf *cfg, const char *filename) { file_t fd; int i; fd = fs_open(filename, O_RDONLY); if(fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open %s\n", filename); return -1; } size_t size = fs_total(fd); char buf[512]; char *optname = NULL, *value = NULL; if(fs_read(fd, buf, size) != size) { fs_close(fd); ds_printf("DS_ERROR: Can't read %s\n", filename); return -1; } fs_close(fd); while(1) { if(optname == NULL) optname = strtok(buf, "="); else optname = strtok('\0', "="); value = strtok('\0', "\n"); if(optname == NULL || value == NULL) break; for(i=0; cfg[i].conf_type; i++) { if(strncasecmp(cfg[i].name, trim_spaces2(optname), 32)) continue; switch(cfg[i].conf_type) { case CONF_INT: *(int *)cfg[i].pointer = atoi(value); break; case CONF_STR: strcpy((char *)cfg[i].pointer, trim_spaces2(value)); break; } break; } } return 0; } int getDeviceType(const char *dir) { if(!strncasecmp(dir, "/cd", 3)) { return APP_DEVICE_CD; } else if(!strncasecmp(dir, "/sd", 3)) { return APP_DEVICE_SD; } else if(!strncasecmp(dir, "/ide", 4)) { return APP_DEVICE_IDE; } else if(!strncasecmp(dir, "/pc", 3)) { return APP_DEVICE_PC; // } else if(!strncasecmp(dir, "/???", 5)) { // return APP_DEVICE_NET; } else { return -1; } } int checkGDI(char *filepath, const char *fmPath, char *dirname, char *filename) { memset(filepath, 0, NAME_MAX); snprintf(filepath, NAME_MAX, "%s/%s/%s.gdi", fmPath, dirname, filename); if(FileExists(filepath)) { memset(filepath, 0, NAME_MAX); snprintf(filepath, NAME_MAX, "%s/%s.gdi", dirname, filename); return 1; } return 0; } char *makePresetFilename(const char *dir, uint8 *md5) { char dev[8]; static char filename[NAME_MAX]; memset(filename, 0, sizeof(filename)); strncpy(dev, &dir[1], 3); if (dev[2] == '/') { dev[2] = '\0'; } else { dev[3] = '\0'; } snprintf(filename, sizeof(filename), "%s/apps/%s/presets/%s_%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x.cfg", getenv("PATH"), lib_get_name() + 4, dev, md5[0], md5[1], md5[2], md5[3], md5[4], md5[5], md5[6], md5[7], md5[8], md5[9], md5[10], md5[11], md5[12], md5[13], md5[14], md5[15]); return filename; } <file_sep>/firmware/aica/codec/fileinfo.h /* Copyright (C) 2006 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef _FILEINFO_H_ #define _FILEINFO_H_ #define MAX_SONGS 50 enum filetypes {WAV, MP2, MP3, MP4, AAC, UNKNOWN=0}; typedef struct _SONGFILE { char filename[12]; // 8.3 format, not null terminated! } SONGFILE; typedef struct _SONGLIST { SONGFILE list[MAX_SONGS]; unsigned int size; } SONGLIST; typedef struct _SONGINFO { char title[40]; char artist[40]; char album[40]; unsigned int data_start; enum filetypes type; } SONGINFO; void songlist_build(SONGLIST *songlist); char* skip_artist_prefix(char* s); void songlist_sort(SONGLIST *songlist); int compar_song(SONGFILE *a, SONGFILE *b); enum filetypes get_filetype(char * filename); char * get_full_filename(char * filename); int read_song_info_for_song(SONGFILE *song, SONGINFO *songinfo); int read_song_info_mp3(FIL *file, SONGINFO *songinfo); int read_song_info_mp4(FIL *file, SONGINFO *songinfo); #endif /* _FILEINFO_H_ */ <file_sep>/src/commands.c /***************************** * DreamShell ##version## * * commands.c * * DreamShell CMD * * (c)2004-2023 SWAT * * http://www.dc-swat.ru * ****************************/ #include "ds.h" #include "cmd_elf.h" #include "zlib/zlib.h" #include "network/net.h" static Item_list_t *cmds; /* print command list/desc */ static int builtin_help(int argc, char *argv[]) { Cmd_t *c; Item_t *i; char ac[512]; int cnt = 0; if (argc > 1) { if((c = GetCmdByName(argv[1])) == NULL) return CMD_ERROR; ds_printf("%s - %s\n", c->command, c->desc); return CMD_OK; } else { ds_printf("\n Internal commands:\n"); SLIST_FOREACH(i, cmds, list) { //ds_printf("%s, ", b->command); c = (Cmd_t *) i->data; if(!cnt) { strcpy(ac, " "); } else { if(cnt % 6) { strcat(ac, ", "); } else { ds_printf("%s\n", ac); strcpy(ac, " "); } } strcat(ac, c->command); cnt++; //ds_printf("%s, ", c->command); } ds_printf("%s\n", ac); file_t hnd; char dir[NAME_MAX]; snprintf(dir, NAME_MAX, "%s/cmds", getenv("PATH")); hnd = fs_open(dir, O_RDONLY | O_DIR); if(hnd != FILEHND_INVALID) { dirent_t *ent; cnt = 0; memset_sh4(ac, 0, sizeof(ac)); ds_printf("\n External commands:\n"); while ((ent = fs_readdir(hnd)) != NULL) { if(ent->attr != O_DIR) { if(!cnt) { strcpy(ac, " "); } else { if(cnt % 6) { strcat(ac, ", "); } else { ds_printf("%s\n", ac); strcpy(ac, " "); } } strcat(ac, ent->name); cnt++; //ds_printf("%s, ", ent->name); } } fs_close(hnd); ds_printf("%s\n", ac); } ds_printf(" \nEnter 'help command_name' for a description.\n"); return CMD_OK; } return CMD_ERROR; } int CallCmd(int argc, char *argv[]) { Cmd_t *cmd; if((cmd = GetCmdByName(argv[0])) != NULL) { int r = CMD_OK; if(cmd->handler != NULL) { r = cmd->handler(argc, argv); } return r; } else { return CallExtCmd(argc, argv); } return CMD_NOT_EXISTS; } int CheckExtCmdType(const char *fn) { file_t fd; uint8 data[2]; fd = fs_open(fn, O_RDONLY); if(fd == FILEHND_INVALID) { return CMD_TYPE_UKNOWN; } fs_read(fd, data, sizeof(data)); fs_close(fd); if(data[0] == 0x7F && data[1] == 0x45) { return CMD_TYPE_ELF; } else if(data[0] == 0x23 && data[0] == 0x44) { return CMD_TYPE_DSC; } else if(data[0] == 0x2D && data[1] == 0x2D) { return CMD_TYPE_LUA; } else if(data[1] == 0xD0) { return CMD_TYPE_BIN; } else { return CMD_TYPE_UKNOWN; } } int CallExtCmd(int argc, char *argv[]) { dirent_t *ent; file_t hnd; char dir[NAME_MAX]; char fn[NAME_MAX]; int r = CMD_NOT_EXISTS; snprintf(dir, NAME_MAX, "%s/cmds", getenv("PATH")); hnd = fs_open(dir, O_RDONLY | O_DIR); if(hnd < 0) { ds_printf("DS_ERROR: Can't find cmds path\n"); return r; } while ((ent = fs_readdir(hnd)) != NULL) { if(!strncmp(ent->name, argv[0], NAME_MAX) && ent->attr != O_DIR) { snprintf(fn, NAME_MAX, "%s/%s", dir, ent->name); r = CallCmdFile(fn, argc, argv); break; } } fs_close(hnd); return r; } int CallCmdFile(const char *fn, int argc, char *argv[]) { cmd_elf_prog_t *cmd = NULL; uint8 *buff; lua_State *L; file_t fd; int type = -1, r = CMD_NOT_EXISTS; type = CheckExtCmdType(fn); switch(type) { case CMD_TYPE_ELF: cmd = cmd_elf_load(fn); if(cmd == NULL) { break; } int (*cmd_main)(int argc, char *argv[]) = (int (*)(int argc, char *argv[]))cmd->main; r = cmd_main(argc, argv); cmd_elf_free(cmd); break; case CMD_TYPE_LUA: L = NewLuaThread(); if (L == NULL) { ds_printf("DS_ERROR_LUA: Invalid state.. giving up\n"); r = CMD_ERROR; break; } LuaPushArgs(L, argv); lua_setglobal(L, "argv"); LuaDo(LUA_DO_FILE, fn, L); //lua_close(L); r = CMD_OK; break; case CMD_TYPE_DSC: r = dsystem_script(fn); break; case CMD_TYPE_BIN: fd = fs_open(fn, O_RDONLY); if(fd == FILEHND_INVALID) { break; } r = fs_total(fd); buff = (uint8* )memalign(32, r); if(!buff) { fs_close(fd); return CMD_ERROR; } if(fs_read(fd, buff, r) < 0) { fs_close(fd); return CMD_ERROR; } fs_close(fd); arch_exec(buff, r); break; default: break; } return r; } static void FreeCmd(void *cmd) { free(cmd); } void ShutdownCmd() { listDestroy(cmds, (listFreeItemFunc *) FreeCmd); } Cmd_t *AddCmd(const char *cmd, const char *helpmsg, CmdHandler *handler) { Cmd_t *c; Item_t *i; c = (Cmd_t *) calloc(1, sizeof(Cmd_t)); if(c == NULL) return NULL; //ds_printf("Adding cmd %s %s\n", cmd, helpmsg); c->command = cmd; c->desc = helpmsg; c->handler = handler; if((i = listAddItem(cmds, LIST_ITEM_CMD, c->command, c, sizeof(Cmd_t))) == NULL) { FreeCmd(c); return NULL; } return c; } void RemoveCmd(Cmd_t *cmd) { if(cmd == NULL) { return; } listRemoveItem(cmds, listGetItemByName(cmds, cmd->command), (listFreeItemFunc *) FreeCmd); } Item_list_t *GetCmdList() { return cmds; } Cmd_t *GetCmdByName(const char *name) { if(name == NULL) { return NULL; } //SemWait(cmd_mutex); Item_t *i = listGetItemByName(cmds, name); //SemSignal(cmd_mutex); if(i != NULL) { return (Cmd_t *) i->data; } return NULL; } static char *fix_spaces(char *str) { if(!str) return NULL; int i, len = (int) strlen(str); for(i=0; i<len; i++) { if(str[i] == '\\') str[i] = ' '; } return str; } /* Execute a single command input by the user or a script */ int dsystem(const char *buff) { int argc, ret = 0; char *argv[16]; char *str = (char*)buff; /* we don't care if the user just hit enter */ if (buff[0] == '\0') return 0; /* seperate the string into args */ for (argc = 0; argc < 16;) { if ((argv[argc] = fix_spaces(strsep(&str, " \t\n"))) == NULL) break; if (*argv[argc] != '\0') argc++; } /* try to run the command as a builtin */ ret = CallCmd(argc, argv); if(ret == CMD_NOT_EXISTS) { ds_printf("DS_ERROR: '%s' - Command not found\n", buff); } return ret; } int system(const char *buff) { return dsystem(buff); } int dsystemf(const char *fmt, ...) { char buff[256]; va_list args; va_start(args, fmt); vsnprintf(buff, sizeof(buff), fmt, args); va_end(args); return dsystem(buff); } int dsystem_script(const char *fn) { char buff[256]; FILE *f; int r = CMD_OK; f = fopen(fn, "rb"); if (!f) { ds_printf("DS_ERROR: Can't Open DScript: %s\n", fn); return 0; } while (fgets(buff, sizeof(buff), f)) { if (buff[0] == 0 || buff[0] == '#') continue; if (buff[strlen(buff)-1] == '\n') buff[strlen(buff)-1] = 0; if (buff[strlen(buff)-1] == '\r') buff[strlen(buff)-1] = 0; r = dsystem(buff); } fclose(f); return r; } int dsystem_buff(const char *buff) { char *b, *bf; int r = CMD_OK; bf = (char*)buff; while((b = strsep(&bf, "\n")) != NULL) { if (b[0] == 0 || b[0] == '#') continue; r = dsystem(b); } return r; } /* list the contents of the directory */ static int builtin_ls(int argc, char *argv[]) { int lflag = 0; if(argc > 1 && !strncmp(argv[1], "-l", 2)) { lflag = 1; } dirent_t *ent; file_t fd; char dir[NAME_MAX]; int dcnt, fcnt; getcwd(dir, NAME_MAX); fd = fs_open(dir, O_RDONLY | O_DIR); if (fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Couldn't open %s\n", dir); return CMD_ERROR; } dcnt = fcnt = 0; ds_printf("DS_PROCESS: Reading %s\n", dir); while ((ent = fs_readdir(fd)) != NULL) { if (lflag) ds_printf("%12d bytes %s\n", ent->size, ent->name); else ds_printf("%s\n", ent->name); if (ent->size < 0) dcnt++; else fcnt++; } ds_printf("Total: %d files, %d dirs\n", fcnt, dcnt); fs_close(fd); return CMD_OK; } /* change the current directory */ static int builtin_cd(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: cd dir\n"); return CMD_NO_ARG; } if(fs_chdir(argv[1]) < 0) { ds_printf("DS_ERROR: Can't change directory to %s", argv[1]); return CMD_ERROR; } setenv("PWD", fs_getwd(), 1); return CMD_OK; } /* print the current directory */ static int builtin_pwd(int argc, char *argv[]) { ds_printf("%s\n", fs_getwd()); return CMD_OK; } int builtin_env(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s variable [value]\n", argv[0]); return CMD_NO_ARG; } else if(argc > 2) { setenv(argv[1], argv[2], argc > 3 ? atoi(argv[3]) : 1); } else { ds_printf("%s\n", getenv(argv[1])); } return CMD_OK; } /* clear the screen */ static int builtin_clear(int argc, char *argv[]) { ConsoleInformation *console = GetConsole(); Clear_History(console); CON_UpdateConsole(console); return CMD_OK; } /* echo, heh */ static int builtin_echo(int argc, char *argv[]) { int i; char buff[256]; if(argc == 1) { return CMD_NO_ARG; } memset_sh4(buff, 0, sizeof(buff)); strncpy(buff, argv[1], sizeof(buff)); for(i = 2; i < argc; i++) { strcat(buff, " "); strcat(buff, argv[i]); } strcat(buff, "\n"); ds_printf(buff); return CMD_OK; } /* copy files and directories */ static int builtin_cp(int argc, char *argv[]) { if (argc < 3) { ds_printf("Usage: cp src_path dest_path\n"); return CMD_NO_ARG; } int verbose = 0; if(argc > 3) { verbose = atoi(argv[3]); } // struct stat st; // // if (fs_stat(argv[1], &st, 0) < 0) { // ds_printf("DS_ERROR: Can't open %s\n", argv[1]); // return CMD_ERROR; // } // // if(st.st_mode & S_IFDIR) { // // if(CopyDirectory(argv[1], argv[2])) // return CMD_OK; // else // return CMD_ERROR; // // } else if(st.st_mode & S_IFREG) { // // if(CopyFile(argv[1], argv[2])) // return CMD_OK; // else // return CMD_ERROR; // // } else { // ds_printf("DS_ERROR: Allow copy only files and directories\n"); // return CMD_ERROR; // } if(FileExists(argv[1])) { if(CopyFile(argv[1], argv[2], verbose)) return CMD_OK; else return CMD_ERROR; } else if(DirExists(argv[1])) { if(CopyDirectory(argv[1], argv[2], verbose)) return CMD_OK; else return CMD_ERROR; } else { ds_printf("DS_ERROR: Can't open %s\n", argv[1]); return CMD_ERROR; } return CMD_OK; } /* unlink files */ static int builtin_rm(int argc, char *argv[]) { if (argc == 1) { ds_printf("Usage: rm file\n"); return CMD_NO_ARG; } if (fs_unlink(argv[1]) == -1) { ds_printf("DS_ERROR: Error unlinking %s.\n", argv[1]); return CMD_ERROR; } return CMD_OK; } /* create a directory */ static int builtin_mkdir(int argc, char *argv[]) { if (argc == 1) { ds_printf("Usage: %s dirname\n", argv[0]); return CMD_NO_ARG; } if (fs_mkdir(argv[1]) < 0) { ds_printf("DS_ERROR: Error making directory %s (maybe not supported)\n", argv[1]); return CMD_ERROR; } return CMD_OK; } static int builtin_rmdir(int argc, char *argv[]) { if (argc == 1) { ds_printf("Usage: %s dirname\n", argv[0]); return CMD_NO_ARG; } if (fs_rmdir(argv[1]) < 0) { ds_printf("DS_ERROR: Error deleting directory %s (maybe not supported)\n", argv[1]); return CMD_ERROR; } return CMD_OK; } /* create a path */ static int builtin_mkpath(int argc, char *argv[]) { if (argc == 1) { ds_printf("Usage: %s path\n", argv[0]); return CMD_NO_ARG; } if (mkpath(argv[1]) < 0) { ds_printf("DS_ERROR: Error making path %s\n", argv[1]); return CMD_ERROR; } return CMD_OK; } /* cat text files to the screen */ static int builtin_cat(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: cat filename\n"); return CMD_NO_ARG; } FILE *f; char buff[128]; f = fopen(argv[1], "rt"); if (!f) { ds_printf("DS_ERROR: Error opening %s\n", argv[1]); return CMD_ERROR; } while (fgets(buff, 128, f)) { ds_printf(buff); } fclose(f); return CMD_OK; } static int builtin_romdisk(int argc, char *argv[]) { if(argc < 3) { ds_printf("Usage: romdisk -flag args...\n" "Flags: \n" " -m filename dir -Mount Romdisk Image\n" " -u dir -Unmount Romdisk Image\n\n" "Example: romdisk -m /cd/romdisk.dsr /rd2\n" " romdisk -u /rd2\n"); return CMD_NO_ARG; } if (!strncmp(argv[1], "-m", 2)) { void * datar = NULL; ds_printf("DS_PROCESS: Loading the romdisk image...\n"); if (fs_load(argv[2], &datar) <= 0) { ds_printf("DS_ERROR: Error! Invalid romdisk source image '%s'\n", argv[2]); if (datar != NULL) free(datar); return CMD_ERROR; } /* Attempt to mount it */ ds_printf("DS_PROCESS: Mounting on %s...\n", argv[2]); if (fs_romdisk_mount(argv[3], (const uint8 *)datar, 1) < 0) { ds_printf("DS_ERROR: Error! Can't mount romdisk image\n"); free(datar); return CMD_ERROR; } ds_printf("DS_OK: Romdisk Success!\n"); return CMD_ERROR; } if(!strncmp(argv[1], "-u", 2)) { ds_printf("DS_PROCESS: Unmounting %s ...\n", argv[2]); if(fs_romdisk_unmount(argv[2]) < 0) { ds_printf("DS_ERROR: Can't unmounting romdisk %s\n", argv[2]); } ds_printf("DS_OK: Complete.\n"); } return CMD_OK; } static int builtin_exec(int argc, char *argv[]) { if(argc < 3) { ds_printf("Usage: %s option args\n" "Options: \n" " -b, --binary -Binary file type\n" " -e, --elf -Elf file type\n " "Arguments: \n" " -f, --file -File for executing\n" " -a, --addr -Executing address\n\n" "Examples: %s -b -f /cd/prog.bin\n" " %s -b -f /cd/prog.bin -a 0xac010000\n\n", argv[0], argv[0], argv[0]); return CMD_NO_ARG; } CFG_CONTEXT con; int binary = 0, elf = 0, ret = 0; char *file = NULL; uint32 addr = 0;//0xac010000; struct cfg_option options[] = { {"binary", 'b', NULL, CFG_BOOL, (void *) &binary, 0}, {"elf", 'e', NULL, CFG_BOOL, (void *) &elf, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, {"addr", 'a', NULL, CFG_ULONG,(void *) &addr, 0}, {"return", 'r', NULL, CFG_BOOL, (void *) &ret, 0}, CFG_END_OF_LIST }; con = cfg_get_context(options); cfg_set_context_flag(con, CFG_IGNORE_UNKNOWN); if (con == NULL) { ds_printf("DS_ERROR: Not enough memory\n"); return CMD_ERROR; } cfg_set_cmdline_context(con, 1, -1, argv); if (cfg_parse(con) != CFG_OK) { ds_printf("DS_ERROR: Error parsing command line: %s\n", cfg_get_error_str(con)); cfg_free_context(con); return CMD_ERROR; } cfg_free_context(con); if(!file) { ds_printf("DS_ERROR: Not specified file to execute.\n"); return CMD_ERROR; } if(binary) { uint32 len = 0; void *ptr = NULL; file_t f = fs_open(file, O_RDONLY); if (f < 0) { ds_printf("DS_ERROR: Can't open %s\n", file); return CMD_ERROR; } ds_printf("DS_PROCESS: Loading %s in to memory...\n", file); len = fs_total(f); ptr = (uint8*) memalign(32, len); if(ptr == NULL) { ds_printf("DS_ERROR: Not enough memory\n"); return CMD_ERROR; } memset_sh4(ptr, 0, len); fs_read(f, ptr, len); fs_close(f); ds_printf("DS_PROCESS: Executing...\n"); if(!addr) arch_exec(ptr, len); else arch_exec_at(ptr, len, addr); ds_printf("DS_ERROR: Exec failed.\n"); return CMD_OK; } if(elf) { cmd_elf_prog_t *cmd = cmd_elf_load(file); if(cmd == NULL) { ds_printf("DS_ERROR: Can't load %s\n", file); return CMD_ERROR; } int (*cmd_main)(int argc, char *argv[]) = (int (*)(int argc, char *argv[]))cmd->main; int r = cmd_main(argc, argv); cmd_elf_free(cmd); ds_printf("DS_OK: Program return: %d\n", r); return CMD_OK; } return CMD_OK; } static int builtin_periphs(int argc, char *argv[]) { int p, u; maple_device_t *dev; ds_printf("DS: Attached maple peripheral info:\n"); for (p = 0; p < MAPLE_PORT_COUNT; p++) { for (u = 0; u < MAPLE_UNIT_COUNT; u++) { dev = maple_enum_dev(p, u); if (dev) { ds_printf("%c%c: %s (%08lx: %s)\n", 'A' + p, '0' + u, dev->info.product_name, dev->info.functions, maple_pcaps(dev->info.functions)); } } } return CMD_OK; } static int builtin_sleep(int argc, char *argv[]) { if (argc < 2) { ds_printf("Usage: sleep msec\n"); return CMD_NO_ARG; } thd_sleep(atoi(argv[1])); return CMD_OK; } static int builtin_rename(int argc, char *argv[]) { if(argc < 3) { ds_printf("Usage: rename src dst\n"); return CMD_NO_ARG; } if(fs_rename(argv[1], argv[2]) == -1) { ds_printf("DS_ERROR: Renaming Failed.\n"); return CMD_ERROR; } return CMD_OK; } static int builtin_read(int argc, char *argv[]) { void *buff; FILE *f; FILE *fs; int siz = 0; int s_byte = 0; if(argc < 5) { ds_printf("Usage: %s infile outfile size offset\n", argv[0]); ds_printf("Example: %s in.bin out.bin 512 64\n", argv[0]); return CMD_NO_ARG; } //ds_printf("DS_PROCESS: Reading file...\n"); siz = atoi(argv[3]); if(argc > 4) s_byte = atoi(argv[4]); if((buff = malloc(siz)) == NULL) { ds_printf("DS_ERROR: The not enough memory.\n"); return CMD_ERROR; } f = fopen(argv[1], "rb"); if(!f) { ds_printf("DS_ERROR: Can't open %s\n", argv[1]); return CMD_ERROR; } //fseek(f, 0, SEEK_END); if(s_byte) fseek(f, s_byte, SEEK_SET); fread(buff, siz, 1, f); fclose(f); fs = fopen(argv[2], "wb"); if(!fs) { ds_printf("DS_ERROR: Can't open %s\n", argv[2]); return CMD_ERROR; } //ds_printf("DS_PROCESS: Reading complete, writing...\n"); fwrite(buff, siz, 1, fs); fclose(fs); free(buff); //ds_printf("DS_OK: Complete.\n"); return CMD_OK; } static int builtin_mstats(int argc, char *argv[]) { struct mallinfo mi = mallinfo(); //struct mallinfo pmi = pvr_int_mallinfo(); ds_printf( "Memory usage:\n" "Max system bytes = %10lu\n" "System bytes = %10lu\n" "In use bytes = %10lu\n" "Free chunks = %10lu\n" "Fastbin blocks = %10lu\n" "Mmapped regions = %10lu\n" "Total allocated space = %10lu\n" "Total free space = %10lu\n" "PVR Mem avaible = %10lu\n" "Current sbrk = %10lx\n", (uint32)(mi.usmblks), (uint32)(mi.arena + mi.hblkhd), (uint32)(mi.uordblks + mi.hblkhd), (uint32) mi.ordblks, (uint32) mi.smblks, (uint32) mi.hblks, (uint32) mi.uordblks, (uint32) mi.fordblks, (uint32) pvr_mem_available(), (uint32) (sbrk(0)) ); //ds_printf("PVR System bytes = %10lu\n",(uint32)(pmi.arena + pmi.hblkhd)); //ds_printf("PVR In use bytes = %10lu\n",(uint32)(pmi.uordblks + pmi.hblkhd)); return CMD_OK; } static int builtin_statf(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: statf path\n"); return CMD_NO_ARG; } struct stat st; /*time_t t; struct tm tm; const char *days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; const char *months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };*/ if(fs_stat(argv[1], &st, 0) < 0) { ds_printf("DS_ERROR: Couldn't get stat from %s, error: %d\n", argv[1], errno); return CMD_ERROR; } if(st.st_mode & S_IFDIR) { ds_printf("Type: Standard directory, size %d\n", st.st_size); } else if(st.st_mode & S_IFSOCK) { ds_printf("Type: Socket\n"); } else if(st.st_mode & S_IFIFO) { ds_printf("Type: FIFO\n"); } else if(st.st_mode & S_IFBLK) { ds_printf("Type: Block special\n"); } else if(st.st_mode & S_IFCHR) { ds_printf("Type: Character device\n"); } else if(st.st_mode & S_IFREG) { ds_printf("Type: Regular file, size %d\n", st.st_size); } ds_printf("Mode: %08lx\nAccess time: %d\nModified time: %d\nCreated time: %d\n", st.st_mode, st.st_atime, st.st_mtime, st.st_ctime); return CMD_OK; } /* Dreamcast functions */ static int builtin_dc(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: dc -flag arguments(if needed)\n" "Flags:\n" "-menu Kernel \"exit to menu\" call\n" "-exit Generic kernel \"exit\" point\n" "-return Kernel \"return\" point\n" "-abort Kernel \"abort\" point\n" "-reboot Kernel \"reboot\" call\n" "-main Kernel C-level entry point\n"); return CMD_NO_ARG; } else if (!strncmp(argv[1], "-menu", 5)) { arch_menu(); } else if (!strncmp(argv[1], "-exit", 5)) { arch_exit(); } else if (!strncmp(argv[1], "-return", 7)) { arch_return(0); } else if (!strncmp(argv[1], "-abort", 6)) { arch_abort(); } else if (!strncmp(argv[1], "-reboot", 7)) { arch_reboot(); } else if (!strncmp(argv[1], "-main", 5)) { arch_main(); } else { ds_printf("DS_ERROR: flag '%s' is not supported\n", argv[1]); return CMD_ERROR; } return CMD_OK; } static void ctaddr(uint32 ad) { //uint32 *mem = ad; int irqd; irqd = irq_disable(); void (*ctm)() = (void (*)())ad; //void (*ctm)()((uint32*)ctm) = (uint32 *)ad; //{ void (*ctm)(); ((uint32*)ctm) = (uint32 *)ad; ctm(); } ctm(); irq_restore(irqd); } static int builtin_addr(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: addr -flag address args...\n" "Flags: \n" " -c addr -s(if needed) -Call to addr(flag -s for arch_shutdown)\n" " -r addr size filename -Read data from addr and write to file\n" " -w addr filename -Read file to addr\n" " -v addr -Valid addr?\n"); return CMD_NO_ARG; } file_t fd; int irqd, len; uint32 ad = strtoul(argv[2], NULL, 16); if(!strncmp(argv[1], "-c", 2)) { ds_printf("DS_INF: Calling to 0x%x ...\n", ad); if(!strncmp(argv[3], "-s", 2)) { arch_shutdown(); ctaddr(ad); ds_printf("DS_OK: Complete.\n"); return CMD_OK; } ctaddr(ad); ds_printf("DS_OK: Complete.\n"); return CMD_OK; } if(!strncmp(argv[1], "-v", 2)) { if(arch_valid_address(ad)) { ds_printf("DS_INF: 0x%x not valid.\n",ad); return CMD_OK; } ds_printf("DS_INF: 0x%x is valid.\n" ,ad); return CMD_OK; } if(!strncmp(argv[1], "-r", 2)) { len = atoi(argv[3]); fd = fs_open(argv[4], O_CREAT | O_WRONLY); if(fd == -1) { ds_printf("DS_ERROR: Can't open %s\n", argv[4]); return CMD_ERROR; } ds_printf("DS_PROCESS: Reading addr = 0x%x, size = %d\n", len); fs_write(fd, (char*)ad, len); fs_close(fd); ds_printf("DS_OK: Complete.\n"); return CMD_ERROR; } if(!strncmp(argv[1], "-w", 2)) { fd = fs_open(argv[3], O_RDONLY); if(fd == -1) { ds_printf("DS_ERROR: Can't open %s\n", argv[3]); return CMD_ERROR; } len = fs_total(fd); fs_read(fd, (char*)ad, len); fs_close(fd); ds_printf("DS_PROCESS: Loading %s (%i bytes) at 0x%x\n", argv[3], len, (uint32)ad); irqd = irq_disable(); //flush_icache_range((uint32)ad, len); dcache_flush_range((uint32)ad, len); irq_restore(irqd); ds_printf("DS_OK: Complete.\n"); return CMD_ERROR; } return CMD_OK; } static int builtin_lua(int argc, char *argv[]) { if(argc == 1) { ds_printf("%.80s %.80s\n\n", LUA_RELEASE, LUA_COPYRIGHT); ds_printf("Usage: lua file.lua argv...\n"); return CMD_NO_ARG; } lua_State *L = GetLuaState();//NewLuaThread(); if (L == NULL) { ds_printf("DS_ERROR: LUA: Invalid state.. giving up\n"); return CMD_ERROR; } LuaPushArgs(L, argv+1); lua_setglobal(L, "argv"); LuaDo(LUA_DO_FILE, argv[1], L); //lua_close(L); return CMD_OK; } static int builtin_dsc(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: dsc filename.dsc\n"); return CMD_NO_ARG; } dsystem_script(argv[1]); return CMD_OK; } static int builtin_screenshot(int argc, char *argv[]) { if(argc < 3) { ds_printf("Usage: %s filename format(bmp,ppm)\n", argv[0]); return CMD_NO_ARG; } if(argc > 2 && !strncmp(argv[2], "ppm", 3)) { if(vid_screen_shot(argv[1]) < 0) { ds_printf("DS_ERROR: Can't save PPM screenshot to %s\n", argv[1]); return CMD_ERROR; } } else if(argc > 2 && !strncmp(argv[2], "bmp", 3)) { if(SDL_SaveBMP(GetScreen(), argv[1]) < 0) { ds_printf("DS_ERROR: Can't save BMP screenshot to %s\n", argv[1]); return CMD_ERROR; } } else { SDL_Surface *tmp = SDL_PNGFormatAlpha(GetScreen()); if(SDL_SavePNG(tmp, argv[1]) < 0) { SDL_FreeSurface(tmp); ds_printf("DS_ERROR: Can't save PNG screenshot to %s\n", argv[1]); return CMD_ERROR; } SDL_FreeSurface(tmp); } ds_printf("DS_OK: Screenshot saved to %s\n", argv[1]); return CMD_OK; } static int builtin_module(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: module option args...\n\n" "Options: \n" " -o, --open -Open module\n" " -c, --close -Close module\n" " -p, --printlist -Print modules list\n\n" "Arguments: \n" " -n, --name -Module name\n" " -f, --file -Module file\n\n" "Examples: module -o -f /cd/module.klf\n" " module --close --name modulename\n"); return CMD_NO_ARG; } int mopen = 0, mclose = 0, printlist = 0; char *file = NULL, *name = NULL; struct cfg_option options[] = { {"open", 'o', NULL, CFG_BOOL, (void *) &mopen, 0}, {"close", 'c', NULL, CFG_BOOL, (void *) &mclose, 0}, {"printlist", 'p', NULL, CFG_BOOL, (void *) &printlist, 0}, {"name", 'n', NULL, CFG_STR, (void *) &name, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(mopen || mclose) { if(mopen && file == NULL) { ds_printf("DS_ERROR: Too few arguments. (file) \n"); return CMD_NO_ARG; } if(mclose && name == NULL) { ds_printf("DS_ERROR: Too few arguments. (module name) \n"); return CMD_NO_ARG; } } if(printlist) { PrintModuleList(ds_printf); } if(mopen) { klibrary_t *mdl = OpenModule(file); if(mdl != NULL) { ds_printf("DS_OK: Opened module \"%s\"\n", mdl->lib_get_name()); } return CMD_OK; } if(mclose) { if(CloseModule(library_lookup(name))) { ds_printf("DS_OK: Module \"%s\" closed.\n", name); return CMD_OK; } else { ds_printf("DS_ERROR: Can't close module: %s\n", name); return CMD_ERROR; } } if(!printlist) { ds_printf("DS_ERROR: There is no option.\n"); return CMD_NO_ARG; } return CMD_OK; } static int builtin_thread(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: %s option\n\n" "Options: \n" " -l, --list -Print list of threads\n" " -q, --queue -Print list of threads queue\n\n" "Example: %s --list\n", argv[0], argv[0]); return CMD_NO_ARG; } int printlist = 0, printlist_queue = 0; struct cfg_option options[] = { {"list", 'l', NULL, CFG_BOOL, (void *) &printlist, 0}, {"queue", 'q', NULL, CFG_BOOL, (void *) &printlist_queue, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(printlist) { thd_pslist(ds_printf); } else if(printlist_queue) { thd_pslist_queue(ds_printf); } return CMD_OK; } static int builtin_event(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: event option args...\n\n" "Options: \n" " -r, --remove -Remove event\n" " -s, --state -Set event state (0 or 1)\n" " -p, --printlist -Print list of events\n\n" "Arguments: \n" " -m, --name -Event name\n\n" "Examples: event -s 0 -n VKB\n" " event --remove --name VKB\n"); return CMD_NO_ARG; } int remove = 0, printlist = 0, state = -1; char *name = NULL; struct cfg_option options[] = { {"remove", 'd', NULL, CFG_BOOL, (void *) &remove, 0}, {"state", 's', NULL, CFG_INT, (void *) &state, 0}, {"printlist", 'p', NULL, CFG_BOOL, (void *) &printlist, 0}, {"name", 'n', NULL, CFG_STR, (void *) &name, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(remove) { if(name == NULL) { ds_printf("DS_ERROR: Too few arguments. (event name) \n"); return CMD_NO_ARG; } RemoveEvent(GetEventByName(name)); return CMD_OK; } if(printlist) { Item_list_t *events = GetEventList(); Event_t *e; Item_t *i; ds_printf("\n Name State Type\n"); ds_printf("-------------------------\n\n"); SLIST_FOREACH(i, events, list) { e = (Event_t *) i->data; ds_printf(" %s %s %s\n", e->name, e->state ? "Sleep" : "Active", e->type == EVENT_TYPE_INPUT ? "Input" : "Video"); } ds_printf("\n-------------------------\n"); ds_printf(" End of list.\n\n"); } if(state > -1) { if(name == NULL) { ds_printf("DS_ERROR: Too few arguments. (event name) \n"); return CMD_NO_ARG; } SetEventState(GetEventByName(name), state); return CMD_OK; } if(!printlist) ds_printf("DS_ERROR: There is no option.\n"); return CMD_OK; } static int builtin_app(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: app option args...\n\n" "Options: \n" " -a, --add -Add app\n" " -r, --remove -Remove app\n" " -o, --open -Open app\n" " -c, --close -Close app\n" " -s, --sleep -Sleep app\n" " -u, --unload -Unload old apps\n" " -p, --printlist -Print apps list\n\n" "Arguments: \n" " -n, --name -App name\n" " -f, --file -App file\n" " -i, --id -App ID\n" " -g, --args -App args\n" "Examples: app -a -f /cd/apps/test/app.xml\n" " app --remove --id 1\n"); return CMD_OK; } int add = 0, remove = 0, open = 0, close = 0, sleep = 0, printlist = 0, id = 0, unload = 0; char *file = NULL, *name = NULL, *arg = NULL; App_t *a; struct cfg_option options[] = { {"add", 'a', NULL, CFG_BOOL, (void *) &add, 0}, {"remove", 'r', NULL, CFG_BOOL, (void *) &remove, 0}, {"open", 'o', NULL, CFG_BOOL, (void *) &open, 0}, {"close", 'c', NULL, CFG_BOOL, (void *) &close, 0}, {"sleep", 's', NULL, CFG_BOOL, (void *) &sleep, 0}, {"unload", 'u', NULL, CFG_BOOL, (void *) &unload, 0}, {"printlist",'p', NULL, CFG_BOOL, (void *) &printlist, 0}, {"name", 'n', NULL, CFG_STR, (void *) &name, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, {"id", 'i', NULL, CFG_INT, (void *) &id, 0}, {"args", 'g', NULL, CFG_STR+CFG_LEFTOVER_ARGS, (void *) &arg, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(remove || open || close) { if(name == NULL && id == 0) { ds_printf("DS_ERROR: Too few arguments. (app ID/Name) \n"); return CMD_NO_ARG; } } if(printlist) { Item_list_t *apps = GetAppList(); Item_t *i; ds_printf("\n ID Name Version File State\n\n"); SLIST_FOREACH(i, apps, list) { a = (App_t *) i->data; ds_printf(" %d %s %s %s 0x%x\n", a->id, a->name, a->ver, a->fn, a->state); } ds_printf("\n End of list.\n\n"); return CMD_OK; } if(add) { if(file == NULL) { ds_printf("DS_ERROR: Too few arguments. (filename) \n"); return CMD_NO_ARG; } a = AddApp(file); if(a == NULL) { ds_printf("DS_ERROR: Can't add app\n"); return CMD_ERROR; } ds_printf("DS_OK: App '%s' added, id = %d\n", a->name, a->id); return CMD_OK; } if(unload) { UnLoadOldApps(); ds_printf("DS_OK: Old apps unloaded.\n"); return CMD_OK; } if(id) { a = GetAppById(id); } else { a = GetAppByName(name); } if(a == NULL) { ds_printf("DS_ERROR: Can't find app '%s' (%d)\n", id ? "Unknown" : a->name, id); return CMD_ERROR; } if(sleep) { ds_printf("DS_INF: Temporarily it is not supported.\n"); return CMD_OK; } if(remove) { if(!RemoveApp(a)) { ds_printf("DS_ERROR: Can't remove app '%s' with id = %d \n", a->name, a->id); return CMD_ERROR; } ds_printf("DS_OK: App removed.\n", name); return CMD_OK; } if(open) { if(!OpenApp(a, arg)) { ds_printf("DS_ERROR: Can't open app '%s' with id = %d\n", a->name, a->id); return CMD_ERROR; } //ds_printf("DS_OK: App opened.\n"); return CMD_OK; } if(close) { if(!CloseApp(a, 1)) { ds_printf("DS_ERROR: Can't close app '%s' with id = %d\n", a->name, a->id); return CMD_ERROR; } //ds_printf("DS_OK: App closed.\n"); return CMD_OK; } ds_printf("DS_ERROR: There is no option.\n"); return CMD_ERROR; } static int builtin_cmd(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: cmd option args...\n\n" "Options: \n" //" -a, --add -Add new command\n" " -r, --remove -Remove command\n" " -s, --shutdown -Shutdown all commands\n\n" "Arguments: \n" " -n, --name -Command name\n" //" -h, --helpmsg -Help message for - 'help cmd_name'\n" "Examples: cmd --remove --name luacmd\n"); return CMD_NO_ARG; } int remove = 0, shutdown = 0; char *cmd = NULL; struct cfg_option options[] = { //{"add", 'a', NULL, CFG_BOOL, (void *) &add, 0}, {"remove", 'r', NULL, CFG_BOOL, (void *) &remove, 0}, {"shutdown", 's', NULL, CFG_BOOL, (void *) &shutdown, 0}, {"name", 'n', NULL, CFG_STR, (void *) &cmd, 0}, //{"helpmsg", 'h', NULL, CFG_STR+CFG_MULTI+CFG_LEFTOVER_ARGS, (void *) &premsg, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(remove) { if(cmd) RemoveCmd(GetCmdByName(cmd)); else ds_printf("DS_ERROR: Too few arguments.\n"); return CMD_OK; } if(shutdown) { ShutdownCmd(); return CMD_OK; } ds_printf("DS_ERROR: There is no option.\n"); return CMD_NO_ARG; } static int builtin_console(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: console option args...\n" "Options: \n" " -s, --show -Show console\n" " -h, --hide -Hide console\n" " -b, --background -Set background\n" " -p, --position -Set position\n" " -r, --resize -Resize console\n" " -a, --alpha -Console alpha\n" " -u, --update -Update console(redraw)\n"); ds_printf("Arguments: \n" " -w, --width -Console width\n" " -h, --height -Console hight\n" " -x, --xpos -Console/Background x position\n" " -y, --ypos -Console/Background y position\n" " -t, --transparency -Alpha transparency\n" " -f, --file -Background image file\n\n"); ds_printf("Examples: console -r -x 0 -y 0 -w 480 -h 272\n" " console -p -x 0 -y 0\n"); return CMD_NO_ARG; } int show = 0, hide = 0, toggle = 0, back = 0, pos = 0, resize = 0, alpha = 0, update = 0; int w = 0, h = 0, x = 0, y = 0, t = 0; char *file = NULL; char fn[NAME_MAX]; struct cfg_option options[] = { {"show", 's', NULL, CFG_BOOL, (void *) &show, 0}, {"hide", 'h', NULL, CFG_BOOL, (void *) &hide, 0}, {"toggle", 'g', NULL, CFG_BOOL, (void *) &toggle, 0}, {"background", 'b', NULL, CFG_BOOL, (void *) &back, 0}, {"position", 'p', NULL, CFG_BOOL, (void *) &pos, 0}, {"resize", 'r', NULL, CFG_BOOL, (void *) &resize, 0}, {"alpha", 'a', NULL, CFG_BOOL, (void *) &alpha, 0}, {"update", 'u', NULL, CFG_BOOL, (void *) &update, 0}, {"width", 'w', NULL, CFG_INT, (void *) &w, 0}, {"height", 'h', NULL, CFG_INT, (void *) &h, 0}, {"xpos", 'x', NULL, CFG_INT, (void *) &x, 0}, {"ypos", 'y', NULL, CFG_INT, (void *) &y, 0}, {"transparency", 't', NULL, CFG_INT, (void *) &t, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(show) { ShowConsole(); return CMD_OK; } if(hide) { HideConsole(); return CMD_OK; } if(toggle) { ToggleConsole(); return CMD_OK; } if(back) { if(file) { realpath(file, fn); CON_Background(GetConsole(), fn, x, y); } else { ds_printf("DS_ERROR: Too few arguments.\n"); return CMD_NO_ARG; } return CMD_OK; } if(pos) { CON_Position(GetConsole(), x, y); return CMD_OK; } if(resize) { SDL_Rect rect; rect.x = x; rect.y = y; rect.w = w; rect.h = h; CON_Resize(GetConsole(), rect); return CMD_OK; } if(alpha) { CON_Alpha(GetConsole(), t); return CMD_OK; } if(update) { CON_UpdateConsole(GetConsole()); return CMD_OK; } ds_printf("DS_ERROR: There is no option.\n"); return CMD_NO_ARG; } int builtin_gzip(int argc, char *argv[]) { if(argc < 3) { ds_printf("Usage: %s option infile outfile\n" "Options: \n" " -s -Show real file size\n" " -9 -Compress with mode from 0 to 9\n" " -d -Decompress\n\n", argv[0]); ds_printf("Examples: %s -9 /cd/file.dat /ram/file.dat.gz\n" " %s -d /ram/file.dat.gz /ram/file.dat\n", argv[0], argv[0]); return CMD_NO_ARG; } char src[NAME_MAX]; char dst[NAME_MAX]; char buff[512]; int len = 0; realpath(argv[2], src); if(argc < 4) { char tmp[NAME_MAX]; relativeFilePath_wb(tmp, src, strrchr(src, '/')); sprintf(dst, "%s.gz", tmp); } else { realpath(argv[3], dst); } if(!strncmp("-s", argv[1], 2)) { uint32 size = gzip_get_file_size(src); ds_printf("DS_OK: File size is %ld bytes\n", size); return CMD_OK; } else if(!strncmp("-d", argv[1], 2)) { ds_printf("DS_PROCESS: Decompressing '%s' ...\n", src); gzFile s = NULL; file_t d = -1; if((s = gzopen(src, "rb")) == NULL) { ds_printf("DS_ERROR: Can't open file: %s\n", src); return CMD_ERROR; } d = fs_open(dst, O_CREAT | O_WRONLY); if(d < 0) { ds_printf("DS_ERROR: Can't create file: %s\n", dst); gzclose(s); return CMD_ERROR; } while((len = gzread(s, buff, sizeof(buff))) > 0) { fs_write(d, buff, len); } gzclose(s); fs_close(d); ds_printf("DS_OK: File decompressed."); } else if(argv[1][1] >= '0' && argv[1][1] <= '9') { char mode[3]; sprintf(mode, "wb%c", argv[1][1]); ds_printf("DS_PROCESS: Compressing '%s' with mode '%c' ...\n", src, argv[1][1]); gzFile d = NULL; file_t s = -1; if((d = gzopen(dst, mode)) == NULL) { ds_printf("DS_ERROR: Can't create file: %s\n", dst); return CMD_ERROR; } s = fs_open(src, O_RDONLY); if(s < 0) { ds_printf("DS_ERROR: Can't open file: %s\n", src); gzclose(d); return CMD_ERROR; } while((len = fs_read(s, buff, sizeof(buff))) > 0) { if(gzwrite(d, buff, len) <= 0) { ds_printf("DS_ERROR: Error writing to file: %s\n", dst); gzclose(d); fs_close(s); return CMD_ERROR; } } gzclose(d); fs_close(s); ds_printf("DS_OK: File compressed."); } else { return CMD_NO_ARG; } return CMD_OK; } static int builtin_speedtest(int argc, char *argv[]) { uint8 *buff = (uint8*)0x8c400000; size_t buff_size = 0x10000; int rd = 0, size = 0, cnt = 0, rc = 0; int64 time_before = 0, time_after = 0; uint32 t = 0; float speed = 0.0f; file_t fd; if (argc < 2) { ds_printf("Usage: speedtest file [buffsize]\nInfo: if file exists, then testing read," "\n otherwise testing write (need 8 Mb free space!).\n"); return CMD_NO_ARG; } fd = fs_open(argv[1], O_RDONLY); if(fd != FILEHND_INVALID) { rd = 1; } else { fd = fs_open(argv[1], O_CREAT | O_WRONLY); if (fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open %s for write: %d\n", argv[1], errno); return CMD_ERROR; } } if(argc > 2) { buff_size = atoi(argv[2]); } ds_printf("DS_PROCESS: Testing %s speed...\n", (rd ? "read" : "write")); if(rd) { size = fs_total(fd); buff = (uint8 *) memalign(32, buff_size); if(buff == NULL) { fs_close(fd); ds_printf("DS_ERROR: No free memory\n"); return CMD_ERROR; } ShutdownVideoThread(); time_before = timer_ms_gettime64(); while(cnt < size) { rc = fs_read(fd, buff, buff_size); if(rc < 0) { fs_close(fd); InitVideoThread(); ds_printf("DS_ERROR: Can't read file: %d\n", errno); return CMD_ERROR; } cnt += rc; } } else { if(!strncmp(argv[1], "/ram", 4)) { size = 0x400000; } else { size = 0x800000; } /* Pre-allocate clusters */ fs_seek(fd, size, SEEK_SET); fs_seek(fd, 0, SEEK_SET); ShutdownVideoThread(); time_before = timer_ms_gettime64(); while(cnt < size) { if(fs_write(fd, buff, buff_size) != buff_size) { fs_close(fd); InitVideoThread(); ds_printf("DS_ERROR: Can't write to file: %d\n", errno); return CMD_ERROR; } buff += buff_size; cnt += buff_size; } } time_after = timer_ms_gettime64(); InitVideoThread(); t = (uint32)(time_after - time_before); speed = size / ((float)t / 1000); if(rd) { free(buff); } fs_close(fd); ds_printf("DS_OK: Complete!\n" " Test: %s\n Time: %d ms\n" "Speed: %.2f Kbytes/s (%.2f Mbit/s)\n" " Size: %d Kb\n Buff: %d Kb\n", (rd ? "read" : "write"), t, speed / 1024, ((speed / 1024) / 1024) * 8, size / 1024, buff_size / 1024); return CMD_OK; } static int builtin_net(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: %s option args...\n" "Options: \n" " -i, --init -Initialize network\n" " -s, --shutdown -Shutdown network\n", argv[0]); ds_printf("Arguments: \n" " -a, --ip -IP address\n\n"); ds_printf("Example: %s --init\n", argv[0]); return CMD_NO_ARG; } int initnet = 0, shutnet = 0; char *ip_str = NULL; int ipi[4]; union { uint32 ipl; uint8 ipb[4]; } ip; struct cfg_option options[] = { {"init", 'i', NULL, CFG_BOOL, (void *) &initnet, 0}, {"shutdown", 's', NULL, CFG_BOOL, (void *) &shutnet, 0}, {"ip", 'a', NULL, CFG_STR, (void *) &ip_str, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(initnet) { ip.ipl = 0; if(ip_str) { sscanf(ip_str, "%d.%d.%d.%d", &ipi[3], &ipi[2], &ipi[1], &ipi[0]); ip.ipb[0] = (uint8)ipi[0] & 0xff; ip.ipb[1] = (uint8)ipi[1] & 0xff; ip.ipb[2] = (uint8)ipi[2] & 0xff; ip.ipb[3] = (uint8)ipi[3] & 0xff; ds_printf("DS_PROCESS: Initializing network with IP %s\n", ip_str); } else { ds_printf("DS_PROCESS: Initializing network\n"); } if(InitNet(ip.ipl) < 0) { ds_printf("DS_ERROR: Can't initialize network\n"); return CMD_ERROR; } return CMD_OK; } if(shutnet) { ShutdownNet(); return CMD_OK; } return CMD_NO_ARG; } static int builtin_callfunc(int argc, char *argv[]) { if(argc == 1) { ds_printf("Usage: %s function_name arg\n", argv[0]); ds_printf("Example: %s ScreenFadeOut\n"); return CMD_NO_ARG; } int r = 0; uint32 func_addr = GET_EXPORT_ADDR(argv[1]); if(func_addr > 0 && func_addr != 0xffffffff) { EXPT_GUARD_BEGIN; void (*cb_func)(void *) = (void (*)(void *))func_addr; cb_func(argc > 2 ? argv[1] : NULL); r = 1; EXPT_GUARD_CATCH; r = 0; EXPT_GUARD_END; } ds_printf("DS_%s: %s at 0x%08lx\n", (r ? "OK" : "ERROR"), argv[1], func_addr); return r ? CMD_OK : CMD_ERROR; } /* Setup all our builtins */ int InitCmd() { if((cmds = listMake()) != NULL) { /* table of the builtin commands, their help mesg, and their handler funcs */ AddCmd("help", "This message", (CmdHandler *) builtin_help); AddCmd("ls", "List contents of directories(flag -l for print files size)", (CmdHandler *) builtin_ls); AddCmd("cd", "Change directory", (CmdHandler *) builtin_cd); AddCmd("pwd", "Print the current directory(flag -get for store dir, flag -go to change stored dir)", (CmdHandler *) builtin_pwd); AddCmd("env", "Show or set environment variables", (CmdHandler *) builtin_env); AddCmd("clear", "Clear the console screen", (CmdHandler *) builtin_clear); AddCmd("echo", "Echo text to the console", (CmdHandler *) builtin_echo); AddCmd("cat", "Display text files to the console", (CmdHandler *) builtin_cat); AddCmd("cp", "Copy files and directories", (CmdHandler *) builtin_cp); AddCmd("rm", "Remove files", (CmdHandler *) builtin_rm); AddCmd("rename", "Rename Files", (CmdHandler *) builtin_rename); AddCmd("mkdir", "Create a directory", (CmdHandler *) builtin_mkdir); AddCmd("rmdir", "Delete a directory", (CmdHandler *) builtin_rmdir); AddCmd("mkpath", "Create a path", (CmdHandler *) builtin_mkpath); AddCmd("exec", "Load and exec another program", (CmdHandler *) builtin_exec); AddCmd("romdisk", "Mount/unmount a romdisk image", (CmdHandler *) builtin_romdisk); AddCmd("periphs", "Info about attached peripherals", (CmdHandler *) builtin_periphs); AddCmd("mstats", "View Memory usage", (CmdHandler *) builtin_mstats); AddCmd("sleep", "Sleep in milliseconds", (CmdHandler *) builtin_sleep); AddCmd("read", "Reading from file", (CmdHandler *) builtin_read); AddCmd("stat", "Print file(or dir) statistic", (CmdHandler *) builtin_statf); AddCmd("gzip", "Gzip archiver", (CmdHandler *) builtin_gzip); AddCmd("cmd", "Command manager", (CmdHandler *) builtin_cmd); AddCmd("screenshot","Screenshot", (CmdHandler *) builtin_screenshot); AddCmd("dc", "Dreamcast system functions", (CmdHandler *) builtin_dc); AddCmd("addr", "Address manager", (CmdHandler *) builtin_addr); AddCmd("dsc", "CMD script interpreter", (CmdHandler *) builtin_dsc); AddCmd("lua", "Lua script interpreter", (CmdHandler *) builtin_lua); AddCmd("net", "Network", builtin_net); AddCmd("module", "Modules manager", (CmdHandler *) builtin_module); AddCmd("thread", "Threads manager", (CmdHandler *) builtin_thread); AddCmd("event", "Events manager", (CmdHandler *) builtin_event); AddCmd("app", "Apps manager", (CmdHandler *) builtin_app); AddCmd("console", "Console manager", (CmdHandler *) builtin_console); AddCmd("speedtest", "Testing r/w speed of device", (CmdHandler *) builtin_speedtest); AddCmd("callfunc", "Call any exported function", (CmdHandler *) builtin_callfunc); //ds_printf("Command list initialised.\n"); return 1; } return 0; } <file_sep>/modules/opkg/unsqfs.c /* * Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 * <NAME> <<EMAIL>> * * Copyright (c) 2010 LG Electronics * <NAME> <<EMAIL>> * * Copyright (c) 2012 Reality Diluted, LLC * <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * unsqfs.c * * Unsquash a squashfs filesystem with minimal support. This code is * for little endian only, ignores uid/gid, ignores xattr, only works * for squashfs version >4.0, only supports zlib and lzo compression, * is only for Linux, is not multi-threaded and does not support any * regular expressions. You have been warned. * -Steve * * To build as a part of a library or application compile this file * and link with the following CFLAGS and LDFLAGS: * * CFLAGS += -O2 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE * LDFLAGS += -lz -llzo2 */ #include <assert.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <fnmatch.h> #include <sys/types.h> #include <sys/stat.h> //#include <sys/mman.h> #if USE_GZIP #include <zlib/zlib.h> #endif #if USE_LZO #include <minilzo/minilzo.h> #endif #include "unsqfs.h" #if !defined(static_assert) #if __STDC_VERSION__ >= 201112L // glibc prior to 2.16 and uClibc lack this define #define static_assert _Static_assert #else //#warning Compiling without static asserts #define static_assert(e, m) #endif #endif //#define IS_POWER_OF_TWO(x) ((x) != 0 && ((x) & ((x) - 1)) == 0) #define SQUASHFS_MAGIC 0x73717368 #define SQUASHFS_START 0 /* size of metadata (inode and directory) blocks */ #define SQUASHFS_METADATA_SIZE 8192 /* default size of data blocks */ #define SQUASHFS_FILE_SIZE 131072 #define SQUASHFS_FILE_MAX_SIZE 1048576 /* Max length of filename (not 255) */ #define SQUASHFS_NAME_LEN 256 #define SQUASHFS_INVALID_FRAG ((unsigned int) 0xffffffff) /* Max number of types and file types */ #define SQUASHFS_DIR_TYPE 1 #define SQUASHFS_REG_TYPE 2 #define SQUASHFS_LDIR_TYPE 8 #define SQUASHFS_LREG_TYPE 9 /* Flag whether block is compressed or uncompressed, bit is set if block is * uncompressed */ #define SQUASHFS_COMPRESSED_BIT (1 << 15) #define SQUASHFS_COMPRESSED_SIZE(B) (((B) & ~SQUASHFS_COMPRESSED_BIT) ? \ (B) & ~SQUASHFS_COMPRESSED_BIT : SQUASHFS_COMPRESSED_BIT) #define SQUASHFS_COMPRESSED(B) (!((B) & SQUASHFS_COMPRESSED_BIT)) #define SQUASHFS_COMPRESSED_BIT_BLOCK (1 << 24) #define SQUASHFS_COMPRESSED_SIZE_BLOCK(B) ((B) & \ ~SQUASHFS_COMPRESSED_BIT_BLOCK) #define SQUASHFS_COMPRESSED_BLOCK(B) (!((B) & SQUASHFS_COMPRESSED_BIT_BLOCK)) /* * Inode number ops. Inodes consist of a compressed block number, and an * uncompressed offset within that block. */ typedef long long squashfs_inode; static inline unsigned int inode_block(squashfs_inode inode_addr) { return (unsigned int)(inode_addr >> 16); } static inline unsigned short inode_offset(squashfs_inode inode_addr) { return (unsigned short)(inode_addr & 0xffff); } static inline squashfs_inode inode_address( unsigned int block, unsigned short offset) { return ((squashfs_inode)block << 16) | offset; } /* * definitions for structures on disk */ typedef long long squashfs_block; #define ZLIB_COMPRESSION 1 #define LZO_COMPRESSION 3 struct squashfs_super_block { unsigned int s_magic; unsigned int inodes; unsigned int mkfs_time /* time of filesystem creation */; unsigned int block_size; unsigned int fragments; unsigned short compression; unsigned short block_log; unsigned short flags; unsigned short res0; unsigned short s_major; unsigned short s_minor; squashfs_inode root_inode; long long bytes_used; long long res1; long long res2; long long inode_table_start; long long directory_table_start; long long fragment_table_start; long long res3; }; struct squashfs_dir_index { unsigned int index; unsigned int start_block; unsigned int size; unsigned char name[0]; }; struct squashfs_base_inode_header { unsigned short inode_type; unsigned short mode; unsigned short uid; unsigned short guid; unsigned int mtime; unsigned int inode_number; }; struct squashfs_reg_inode_header { unsigned short inode_type; unsigned short mode; unsigned short uid; unsigned short guid; unsigned int mtime; unsigned int inode_number; unsigned int start_block; unsigned int fragment; unsigned int offset; unsigned int file_size; unsigned int block_list[0]; }; struct squashfs_lreg_inode_header { unsigned short inode_type; unsigned short mode; unsigned short uid; unsigned short guid; unsigned int mtime; unsigned int inode_number; squashfs_block start_block; long long file_size; long long sparse; unsigned int nlink; unsigned int fragment; unsigned int offset; unsigned int xattr; unsigned int block_list[0]; }; struct squashfs_dir_inode_header { unsigned short inode_type; unsigned short mode; unsigned short uid; unsigned short guid; unsigned int mtime; unsigned int inode_number; unsigned int start_block; unsigned int nlink; unsigned short file_size; unsigned short offset; unsigned int parent_inode; }; struct squashfs_ldir_inode_header { unsigned short inode_type; unsigned short mode; unsigned short uid; unsigned short guid; unsigned int mtime; unsigned int inode_number; unsigned int nlink; unsigned int file_size; unsigned int start_block; unsigned int parent_inode; unsigned short i_count; unsigned short offset; unsigned int res0; struct squashfs_dir_index index[0]; }; union squashfs_inode_header { struct squashfs_base_inode_header base; struct squashfs_reg_inode_header reg; struct squashfs_lreg_inode_header lreg; struct squashfs_dir_inode_header dir; struct squashfs_ldir_inode_header ldir; }; struct squashfs_dir_entry { unsigned short offset; short inode_number; unsigned short type; unsigned short size; char name[0]; }; struct squashfs_dir_header { unsigned int count; unsigned int start_block; unsigned int inode_number; }; struct squashfs_fragment_entry { long long start_block; unsigned int size; unsigned int unused; }; #ifdef SQUASHFS_TRACE #define TRACE(s, args...) \ do { \ printf("unsquashfs: "s, ## args); \ } while(0) #else #define TRACE(s, args...) #endif #define ERROR(s, args...) \ do { \ printf("unsquashfs: "s, ## args); \ } while(0) #define DIR_ENT_SIZE 16 struct dir_ent { char name[SQUASHFS_NAME_LEN + 1]; squashfs_inode inode_addr; unsigned int type; }; struct dir { int dir_count; int cur_entry; struct dir_ent *dirs; bool is_open; }; struct path_entry { char *name; struct pathname *paths; }; struct pathname { int names; struct path_entry *name; }; struct pathnames { int count; struct pathname *path[0]; }; #define PATHS_ALLOC_SIZE 10 #define HASH_TABLE_SIZE (1 << 16) /* static_assert(IS_POWER_OF_TWO(HASH_TABLE_SIZE), "size must be a power of two so we can do efficient modulo"); */ struct metadata_table { struct hash_table_entry *hash_table[HASH_TABLE_SIZE]; struct PkgData *pdata; }; struct PkgData { struct squashfs_super_block sBlk; struct metadata_table inode_table; struct metadata_table directory_table; long long *fragment_table_index; struct squashfs_fragment_entry **fragment_table_blocks; int fd; struct dir dir; }; // === Low-level I/O === static int read_fs_bytes(const int fd, const long long offset, void *buf, const size_t bytes) { TRACE("read_bytes: reading from position 0x%llx, bytes %lu\n", offset, bytes); if (lseek(fd, (off_t)offset, SEEK_SET) == -1) { int err = -errno; ERROR("Error seeking in input: %s\n", strerror(errno)); return err; } size_t count = 0; while (count < bytes) { const int res = read(fd, buf + count, bytes - count); if (res < 1) { if (res == 0) { ERROR("Error reading input: unexpected EOF\n"); return -EIO; } else if (errno != EINTR) { int err = -errno; ERROR("Error reading input: %s\n", strerror(errno)); return err; } } else { count += res; } } return 0; } static int read_compressed(const struct PkgData *pdata, const long long offset, const size_t csize, void *buf, const size_t buf_size) { if (csize >= buf_size) { // In the case compression doesn't make a block smaller, // mksquashfs will store the block uncompressed. ERROR("Refusing to load too-large compressed block\n"); return -EIO; } // Load compressed data into temporary buffer. char tmp[csize]; int err = read_fs_bytes(pdata->fd, offset, tmp, csize); if (err < 0) { return err; } #if USE_GZIP if (pdata->sBlk.compression == ZLIB_COMPRESSION) { unsigned long bytes_zlib = buf_size; int error = uncompress(buf, &bytes_zlib, (const Bytef *) tmp, csize); if (error == Z_OK) { return (int) bytes_zlib; } ERROR("GZIP uncompress failed with error code %d\n", error); return -EIO; } #endif #if USE_LZO if (pdata->sBlk.compression == LZO_COMPRESSION) { lzo_uint bytes_lzo = buf_size; int error = lzo1x_decompress_safe((const lzo_bytep) tmp, csize, buf, &bytes_lzo, NULL); if (error == LZO_E_OK) { return (int) bytes_lzo; } ERROR("LZO uncompress failed with error code %d\n", error); return -EIO; } #endif ERROR("Unsupported compression algorithm (id: %hu)\n", pdata->sBlk.compression); return -EINVAL; } static int read_uncompressed(const struct PkgData *pdata, const long long offset, const size_t csize, void *buf, const size_t buf_size) { if (csize > buf_size) { ERROR("Refusing to load oversized uncompressed block\n"); return -EIO; } int err = read_fs_bytes(pdata->fd, offset, buf, csize); if (err < 0) { return err; } return (int) csize; } // === High level I/O === static int read_metadata_block(const struct PkgData *pdata, const long long start, long long *next, void *buf, const size_t buf_size) { long long offset = start; unsigned short c_byte; int ret = read_fs_bytes(pdata->fd, offset, &c_byte, 2); if (ret) { goto failed; } offset += 2; int csize = SQUASHFS_COMPRESSED_SIZE(c_byte); TRACE("read_metadata_block: block @0x%llx, %d %s bytes\n", start, csize, SQUASHFS_COMPRESSED(c_byte) ? "compressed" : "uncompressed"); ret = SQUASHFS_COMPRESSED(c_byte) ? read_compressed(pdata, offset, csize, buf, buf_size) : read_uncompressed(pdata, offset, csize, buf, buf_size); if (ret < 0) { goto failed; } offset += csize; if (next) *next = offset; return ret; failed: ERROR("Failed to read metadata block @0x%llx\n", start); return ret; } static int read_data_block(const struct PkgData *pdata, void *buf, const size_t buf_size, const long long offset, const unsigned int c_byte) { const size_t csize = SQUASHFS_COMPRESSED_SIZE_BLOCK(c_byte); return SQUASHFS_COMPRESSED_BLOCK(c_byte) ? read_compressed(pdata, offset, csize, buf, buf_size) : read_uncompressed(pdata, offset, csize, buf, buf_size); } // === Metadata table === struct hash_table_entry { long long cstart, cnext; void *udata; size_t usize; struct hash_table_entry *next; }; static int calculate_hash(long long cstart) { return cstart & (HASH_TABLE_SIZE - 1); } static struct hash_table_entry *load_entry(struct PkgData *pdata, long long cstart) { // Allocate space for decompressed metadata block. void *udata = malloc(SQUASHFS_METADATA_SIZE); if (!udata) { ERROR("Failed to allocate metadata block\n"); return NULL; } long long cnext; int usize = read_metadata_block(pdata, cstart, &cnext, udata, SQUASHFS_METADATA_SIZE); if (usize < 0) { ERROR("Failed to read metadata block\n"); free(udata); return NULL; } struct hash_table_entry *entry = malloc(sizeof(struct hash_table_entry)); if (!entry) { ERROR("Failed to allocate hash table entry\n"); free(udata); return NULL; } entry->cstart = cstart; entry->cnext = cnext; entry->udata = udata; entry->usize = usize; entry->next = NULL; return entry; } static const struct hash_table_entry *fetch_entry(struct metadata_table *table, long long cstart) { struct hash_table_entry **hash_table = table->hash_table; const int hash = calculate_hash(cstart); struct hash_table_entry *entry = hash_table[hash]; while (entry && entry->cstart != cstart) { entry = entry->next; } if (!entry) { entry = load_entry(table->pdata, cstart); hash_table[hash] = entry; } return entry; } static void free_metadata_table(struct metadata_table *table) { struct hash_table_entry **hash_table = table->hash_table; for (unsigned int i = 0; i < HASH_TABLE_SIZE; i++) { struct hash_table_entry *entry = hash_table[i]; while (entry) { struct hash_table_entry *next = entry->next; free(entry->udata); free(entry); entry = next; } } } struct metadata_accessor { struct metadata_table *table; const struct hash_table_entry *entry; unsigned short offset; }; static bool init_metadata_accessor( struct metadata_accessor *accessor, struct metadata_table *table, squashfs_block start_block, unsigned short offset) { const struct hash_table_entry *entry = fetch_entry(table, start_block); if (!entry) { ERROR("Table block %lld not found\n", start_block); return false; } accessor->table = table; accessor->entry = entry; accessor->offset = offset; return true; } static bool read_metadata( struct metadata_accessor *accessor, void *dest, size_t num_bytes) { const struct hash_table_entry *entry = accessor->entry; unsigned int offset = accessor->offset; while (num_bytes != 0) { // Copy bytes from current block. size_t step_bytes = offset + num_bytes <= entry->usize ? num_bytes : entry->usize - offset; memcpy(dest, entry->udata + offset, step_bytes); dest += step_bytes; offset += step_bytes; num_bytes -= step_bytes; if (num_bytes != 0) { // Next block. long long start_block = entry->cnext; entry = fetch_entry(accessor->table, start_block); accessor->entry = entry; if (!entry) { ERROR("Table block %lld not found\n", start_block); return false; } offset = 0; } } accessor->offset = offset; return true; } // === Inodes === struct inode { int num_blocks; struct metadata_accessor accessor; long long file_size; int fragment; int frag_bytes; int offset; // file: offset in fragment block // dir: offset in directory block long long start; // file: compressed block start address // dir: offset of directory block in directory table }; static bool read_inode(struct PkgData *pdata, squashfs_inode inode_addr, struct inode *i) { TRACE("read_inode: reading inode %012llX\n", inode_addr); if (!init_metadata_accessor(&i->accessor, &pdata->inode_table, pdata->sBlk.inode_table_start + inode_block(inode_addr), inode_offset(inode_addr))) { return false; } union squashfs_inode_header header; void *header_ptr = &header.base; if (!read_metadata(&i->accessor, header_ptr, sizeof(header.base))) { return false; } header_ptr += sizeof(header.base); switch(header.base.inode_type) { case SQUASHFS_DIR_TYPE: { struct squashfs_dir_inode_header *inode = &header.dir; if (!read_metadata(&i->accessor, header_ptr, sizeof(*inode) - sizeof(header.base))) { return false; } i->file_size = inode->file_size; i->offset = inode->offset; i->start = inode->start_block; break; } case SQUASHFS_LDIR_TYPE: { struct squashfs_ldir_inode_header *inode = &header.ldir; if (!read_metadata(&i->accessor, header_ptr, sizeof(*inode) - sizeof(header.base))) { return false; } i->file_size = inode->file_size; i->offset = inode->offset; i->start = inode->start_block; break; } case SQUASHFS_REG_TYPE: { struct squashfs_reg_inode_header *inode = &header.reg; if (!read_metadata(&i->accessor, header_ptr, sizeof(*inode) - sizeof(header.base))) { return false; } const bool has_fragment = inode->fragment != SQUASHFS_INVALID_FRAG; i->file_size = inode->file_size; i->frag_bytes = has_fragment ? inode->file_size % pdata->sBlk.block_size : 0; i->fragment = inode->fragment; i->offset = inode->offset; i->num_blocks = (inode->file_size + (has_fragment ? 0 : pdata->sBlk.block_size - 1) ) >> pdata->sBlk.block_log; i->start = inode->start_block; break; } case SQUASHFS_LREG_TYPE: { struct squashfs_lreg_inode_header *inode = &header.lreg; if (!read_metadata(&i->accessor, header_ptr, sizeof(*inode) - sizeof(header.base))) { return false; } const bool has_fragment = inode->fragment != SQUASHFS_INVALID_FRAG; i->file_size = inode->file_size; i->frag_bytes = has_fragment ? inode->file_size % pdata->sBlk.block_size : 0; i->fragment = inode->fragment; i->offset = inode->offset; i->num_blocks = (inode->file_size + (has_fragment ? 0 : pdata->sBlk.block_size - 1) ) >> pdata->sBlk.block_log; i->start = inode->start_block; break; } default: TRACE("read_inode: skipping inode type %d\n", header.base.inode_type); return false; } return true; } // === Directories === static bool squashfs_opendir(struct PkgData *pdata, squashfs_inode inode_addr, struct dir *dir) { TRACE("squashfs_opendir: inode %012llX\n", inode_addr); struct inode i; if (!read_inode(pdata, inode_addr, &i)) { ERROR("Failed to read directory inode %012llX\n", inode_addr); return false; } struct metadata_accessor accessor; if (!init_metadata_accessor(&accessor, &pdata->directory_table, pdata->sBlk.directory_table_start + i.start, i.offset)) { return false; } dir->dir_count = 0; dir->cur_entry = 0; dir->dirs = NULL; char buffer[sizeof(struct squashfs_dir_entry) + SQUASHFS_NAME_LEN + 1] __attribute__((aligned)); struct squashfs_dir_entry *dire = (struct squashfs_dir_entry *) buffer; int remaining = i.file_size - 3; while (remaining > 0) { struct squashfs_dir_header dirh; if (!read_metadata(&accessor, &dirh, sizeof(dirh))) { return false; } remaining -= sizeof(dirh); int dir_count = dirh.count + 1; TRACE("squashfs_opendir: Read directory header, %d directory entries\n", dir_count); while(dir_count--) { if (!read_metadata(&accessor, dire, sizeof(*dire))) { return false; } if (!read_metadata(&accessor, dire->name, dire->size + 1)) { return false; } dire->name[dire->size + 1] = '\0'; remaining -= sizeof(*dire) + dire->size + 1; TRACE("squashfs_opendir: directory entry %s, inode " "%d:%d, type %d\n", dire->name, dirh.start_block, dire->offset, dire->type); if((dir->dir_count % DIR_ENT_SIZE) == 0) { struct dir_ent *new_dir = realloc(dir->dirs, (dir->dir_count + DIR_ENT_SIZE) * sizeof(struct dir_ent)); if (!new_dir) { ERROR("Failed to (re)allocate directory contents\n"); return false; } dir->dirs = new_dir; } strcpy(dir->dirs[dir->dir_count].name, dire->name); dir->dirs[dir->dir_count].inode_addr = inode_address(dirh.start_block, dire->offset); dir->dirs[dir->dir_count].type = dire->type; dir->dir_count ++; } } dir->is_open = true; return true; } static struct dir_ent *squashfs_dir_next(struct dir *dir) { if (dir->cur_entry == dir->dir_count) { return NULL; } else { return &dir->dirs[dir->cur_entry++]; } } static void squashfs_closedir(struct dir *dir) { free(dir->dirs); dir->dirs = NULL; dir->is_open = false; } // === File contents === // Every fragment entry is located in exactly one metadata block. /* static_assert(IS_POWER_OF_TWO(sizeof(struct squashfs_fragment_entry)), "unexpected fragment entry size"); static_assert(IS_POWER_OF_TWO(SQUASHFS_METADATA_SIZE), "unexpected metadata size"); static_assert( sizeof(struct squashfs_fragment_entry) <= SQUASHFS_METADATA_SIZE, "fragment entry larger than metadata block");*/ static const unsigned int entries_per_block = SQUASHFS_METADATA_SIZE / sizeof(struct squashfs_fragment_entry); static unsigned int get_num_fragment_table_blocks(struct PkgData *pdata) { return (pdata->sBlk.fragments + entries_per_block - 1) / entries_per_block; } static long long *read_fragment_table_index(struct PkgData *pdata) { const unsigned int num_table_blocks = get_num_fragment_table_blocks(pdata); TRACE("read_fragment_index: %d fragments, table spans %u metadata blocks, " "index at 0x%llx\n", pdata->sBlk.fragments, num_table_blocks, pdata->sBlk.fragment_table_start); const size_t index_size = num_table_blocks * sizeof(long long); long long *index = malloc(index_size); if (read_fs_bytes(pdata->fd, pdata->sBlk.fragment_table_start, index, index_size) < 0) { ERROR("Failed to read fragment table index\n"); free(index); return NULL; } return index; } static const struct squashfs_fragment_entry *fetch_fragment_entry( struct PkgData *pdata, int fragment) { // Sanity check on fragment number. if ((unsigned int)fragment >= pdata->sBlk.fragments) { ERROR("Fragment out of range: %d of %u\n", fragment, pdata->sBlk.fragments); return NULL; } // Compute location of fragment info in fragment table. const unsigned int block_nr = fragment / entries_per_block; const unsigned int block_idx = fragment % entries_per_block; // Check if relevant fragment table block is cached. struct squashfs_fragment_entry **blocks = pdata->fragment_table_blocks; if (blocks) { // Cache exists. if (blocks[block_nr]) { return &blocks[block_nr][block_idx]; } } else { // Create empty cache. const unsigned int num_table_blocks = get_num_fragment_table_blocks(pdata); if (!(blocks = calloc(num_table_blocks, sizeof(*blocks)))) { ERROR("Failed to allocate fragment table block cache " "of %u blocks\n", num_table_blocks); return NULL; } pdata->fragment_table_blocks = blocks; } // Read fragment table index. long long *index = pdata->fragment_table_index; if (!index) { if (!(index = read_fragment_table_index(pdata))) { return NULL; } pdata->fragment_table_index = index; } // Allocate one fragment table block. const size_t block_size = block_nr < pdata->sBlk.fragments / entries_per_block ? SQUASHFS_METADATA_SIZE : (pdata->sBlk.fragments % entries_per_block) * sizeof(struct squashfs_fragment_entry); struct squashfs_fragment_entry *table_block; if (!(table_block = malloc(block_size))) { ERROR("Failed to allocate fragment table\n"); return NULL; } // Load fragment table block. int length = read_metadata_block(pdata, index[block_nr], NULL, table_block, block_size); TRACE("Read fragment table block %u, from 0x%llx, length %d\n", block_nr, index[block_nr], length); if (length < 0) { ERROR("Failed to read fragment table block %u\n", block_nr); free(table_block); return NULL; } else if ((size_t)length != block_size) { ERROR("Bad length reading fragment table block %u: " "expected %zu, got %d\n", block_nr, block_size, length); free(table_block); return NULL; } // Insert block in cache. blocks[block_nr] = table_block; return &blocks[block_nr][block_idx]; } static int write_buf(struct PkgData *pdata, struct inode *inode, void *buf) { TRACE("write_buf: regular file, %d blocks\n", inode->num_blocks); const int file_end = inode->file_size / pdata->sBlk.block_size; long long start = inode->start; for (int i = 0; i < inode->num_blocks; i++) { int size = i == file_end ? inode->file_size & (pdata->sBlk.block_size - 1) : pdata->sBlk.block_size; unsigned int c_byte; if (!read_metadata(&inode->accessor, &c_byte, sizeof(c_byte))) { return -EIO; } if (c_byte == 0) { // sparse file memset(buf, 0, size); } else { const int usize = read_data_block(pdata, buf, size, start, c_byte); if (usize < 0) { return usize; } else if (usize != size) { ERROR("Error: data block contains %d bytes, expected %d\n", usize, size); return -EIO; } start += SQUASHFS_COMPRESSED_SIZE_BLOCK(c_byte); } buf += size; } if (inode->frag_bytes) { TRACE("read_fragment: reading fragment %d\n", inode->fragment); const struct squashfs_fragment_entry *fragment_entry = fetch_fragment_entry(pdata, inode->fragment); if (!fragment_entry) { ERROR("Failed to get info about fragment %d\n", inode->fragment); return -EIO; } void *data = malloc(pdata->sBlk.block_size); if (!data) { ERROR("Failed to allocate block data buffer\n"); return -ENOMEM; } const int usize = read_data_block(pdata, data, pdata->sBlk.block_size, fragment_entry->start_block, fragment_entry->size); if (usize < 0) { free(data); return usize; } memcpy(buf, data + inode->offset, inode->frag_bytes); free(data); } return 0; } // === Public functions === struct PkgData *opk_sqfs_open(const char *image_name) { struct PkgData *pdata = calloc(1, sizeof(*pdata)); if (!pdata) { ERROR("Unable to create data structure: %s\n", strerror(errno)); goto fail_exit; } pdata->inode_table.pdata = pdata; pdata->directory_table.pdata = pdata; if ((pdata->fd = open(image_name, O_RDONLY)) == -1) { ERROR("Could not open \"%s\": %s\n", image_name, strerror(errno)); goto fail_free; } TRACE("Loading superblock...\n"); if (read_fs_bytes(pdata->fd, SQUASHFS_START, &pdata->sBlk, sizeof(pdata->sBlk)) < 0) { ERROR("Failed to read SQUASHFS superblock on \"%s\"\n", image_name); goto fail_close; } if (pdata->sBlk.s_magic != SQUASHFS_MAGIC) { ERROR("Invalid SQUASHFS superblock on \"%s\"\n", image_name); goto fail_close; } if (pdata->sBlk.s_major != 4 || pdata->sBlk.s_minor != 0) { ERROR("Unsupported SQUASHFS version on \"%s\"\n", image_name); goto fail_close; } TRACE("Done opening image.\n"); return pdata; fail_close: close(pdata->fd); fail_free: free(pdata); fail_exit: return NULL; } void opk_sqfs_close(struct PkgData *pdata) { squashfs_closedir(&pdata->dir); close(pdata->fd); free_metadata_table(&pdata->inode_table); free_metadata_table(&pdata->directory_table); free(pdata->fragment_table_index); if (pdata->fragment_table_blocks) { const unsigned int num_table_blocks = get_num_fragment_table_blocks(pdata); for (unsigned int i = 0; i < num_table_blocks; i++) { free(pdata->fragment_table_blocks[i]); } free(pdata->fragment_table_blocks); } free(pdata); } static int get_inode_from_dir(struct PkgData *pdata, const char *name, squashfs_inode inode_addr, struct inode *i) { struct dir dir; if (!squashfs_opendir(pdata, inode_addr, &dir)) { return -EIO; } int found = 0; const char *dirsep = strchr(name, '/'); if (dirsep) { // Look for subdir. struct dir_ent *ent; while ((ent = squashfs_dir_next(&dir))) { if (ent->type == SQUASHFS_DIR_TYPE || ent->type == SQUASHFS_LDIR_TYPE) { if (!strncmp(ent->name, name, dirsep - name)) { if (!read_inode(pdata, ent->inode_addr, i)) { goto exit_close; } found = get_inode_from_dir( pdata, dirsep + 1, ent->inode_addr, i); goto exit_close; } } } } else { // Look for regular file. struct dir_ent *ent; while ((ent = squashfs_dir_next(&dir))) { if (ent->type == SQUASHFS_REG_TYPE || ent->type == SQUASHFS_LREG_TYPE) { if (!strcmp(ent->name, name)) { found = read_inode(pdata, ent->inode_addr, i); goto exit_close; } } } } exit_close: squashfs_closedir(&dir); return found; } int opk_sqfs_extract_file(struct PkgData *pdata, const char *name, void **out_data, size_t *out_size) { struct inode i; int ret = get_inode_from_dir(pdata, name, pdata->sBlk.root_inode, &i); if (ret < 0) { return ret; } else if (!ret) { ERROR("Unable to find inode for path \"%s\"\n", name); return -ENOENT; } void *buf = malloc(i.file_size); if (!buf) { ERROR("Unable to allocate file extraction buffer\n"); return -ENOMEM; } ret = write_buf(pdata, &i, buf); if (ret < 0) { free(buf); return ret; } *out_data = buf; *out_size = i.file_size; return 0; } int opk_sqfs_get_metadata(struct PkgData *pdata, const char **filename) { if (!pdata->dir.is_open) { if (!squashfs_opendir(pdata, pdata->sBlk.root_inode, &pdata->dir)) return -EIO; } struct dir_ent *ent; while ((ent = squashfs_dir_next(&pdata->dir))) { if (ent->type == SQUASHFS_REG_TYPE || ent->type == SQUASHFS_LREG_TYPE) { char *ptr = strrchr(ent->name, '.'); if (ptr && !strcmp(ptr + 1, "desktop")) { *filename = ent->name; return 1; } } } squashfs_closedir(&pdata->dir); return 0; } <file_sep>/firmware/aica/codec/main.c /* Copyright (C) 2006 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "Board.h" #include "systime.h" #include "serial.h" #include <string.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <malloc.h> #include "keys.h" #include "ir.h" #include "ff.h" #include "diskio.h" #include "fileinfo.h" #include "player.h" #include "profile.h" #include "dac.h" #include "aacdec.h" #include "raw_aac_data.h" FATFS fs; static FIL file; static DIR dir; static FILINFO fileinfo; void write_benchmark(void) { assert(f_open(&file, "testdata.raw", FA_WRITE|FA_CREATE_ALWAYS) == FR_OK); puts("opened"); { WORD BytesWritten; FRESULT res; static const BYTE dummy_ff_block[512] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; PROFILE_START("writing 512 kB"); for(int i=0; i<1000; i++) { res = f_write(&file, dummy_ff_block, sizeof(dummy_ff_block), &BytesWritten); if (res) iprintf("result: %i\n", res); } PROFILE_END(); } assert(f_close(&file) == FR_OK); } void record(void) { int writeable_buffer, readable_buffer; WORD BytesWritten; dac_init(); dac_set_srate(44100); puts("deleting file"); assert(f_unlink("testdata.raw") == FR_OK); puts("opening file"); assert(f_open(&file, "testdata.raw", FA_WRITE|FA_CREATE_ALWAYS) == FR_OK); puts("opened"); *AT91C_SSC_PTCR = AT91C_PDC_RXTEN; for(int i=0; i<500;) { if ( (readable_buffer = dac_get_readable_buffer()) != -1 ) { i++; iprintf("write: %i\n", readable_buffer); assert(f_write(&file, (BYTE *)dac_buffer[readable_buffer], 2*dac_buffer_size[readable_buffer], &BytesWritten) == FR_OK); } if (*AT91C_SSC_RCR == 0) { writeable_buffer = dac_get_writeable_buffer(); if (writeable_buffer == -1) { continue; } *AT91C_SSC_RPR = (unsigned int)dac_buffer[writeable_buffer]; *AT91C_SSC_RCR = DAC_BUFFER_MAX_SIZE; dac_buffer_size[writeable_buffer] = DAC_BUFFER_MAX_SIZE; } if (*AT91C_SSC_RNCR == 0) { writeable_buffer = dac_get_writeable_buffer(); if (writeable_buffer == -1) { continue; } *AT91C_SSC_RNPR = (unsigned int)dac_buffer[writeable_buffer]; *AT91C_SSC_RNCR = DAC_BUFFER_MAX_SIZE; dac_buffer_size[writeable_buffer] = DAC_BUFFER_MAX_SIZE; } } assert(f_close(&file) == FR_OK); puts("finished"); } void codec_bypass(void) { short x[3] = {0, 0, 0}; short y; short h[3] = {32767, 0, 0}; dac_init(); dac_set_srate(8000); *AT91C_SSC_THR = 0; while(1) { //iprintf("endrx: %i, txempty: %i", *AT91C_SSC_PTCR & AT91C_SSC_ENDRX) x[2] = x[1]; x[1] = x[0]; while(!(*AT91C_SSC_SR & AT91C_SSC_ENDRX)); x[0] = *(short *)(AT91C_SSC_RHR); //x[0] = rand(); y = ((x[0]*h[0]) >> 16) + ((x[1]*h[1]) >> 16) + ((x[2]*h[2]) >> 16); while(!(*AT91C_SSC_SR & AT91C_SSC_TXEMPTY)); *AT91C_SSC_THR = *(unsigned short *)(&y); //iprintf("y: %i\n", y); } } void codec_buffered_bypass(void) { int writeable_buffer; dac_init(); dac_set_srate(44100); *AT91C_SSC_PTCR = AT91C_PDC_RXTEN; dac_enable_dma(); while(1) { while(dac_fill_dma() == 0); if (*AT91C_SSC_RCR == 0) { writeable_buffer = dac_get_writeable_buffer(); if (writeable_buffer == -1) { continue; } *AT91C_SSC_RPR = (unsigned int)dac_buffer[writeable_buffer]; *AT91C_SSC_RCR = DAC_BUFFER_MAX_SIZE; dac_buffer_size[writeable_buffer] = DAC_BUFFER_MAX_SIZE; } if (*AT91C_SSC_RNCR == 0) { writeable_buffer = dac_get_writeable_buffer(); if (writeable_buffer == -1) { continue; } *AT91C_SSC_RNPR = (unsigned int)dac_buffer[writeable_buffer]; *AT91C_SSC_RNCR = DAC_BUFFER_MAX_SIZE; dac_buffer_size[writeable_buffer] = DAC_BUFFER_MAX_SIZE; } } } void test_raw_aac(void) { static HAACDecoder hAACDecoder; static AACFrameInfo aacFrameInfo; static unsigned char *readPtr; static short outBuf[2300]; static int bytesLeft; int res; bytesLeft = sizeof(raw_aac_data); readPtr = (unsigned char *)raw_aac_data; assert(hAACDecoder = AACInitDecoder()); puts("decoder initialized"); memset(&aacFrameInfo, 0, sizeof(AACFrameInfo)); aacFrameInfo.nChans = 2; aacFrameInfo.sampRateCore = 44100; aacFrameInfo.profile = AAC_PROFILE_LC; assert(AACSetRawBlockParams(hAACDecoder, 0, &aacFrameInfo) == 0); for(int i=0; i<100; i++) { res = AACDecode(hAACDecoder, &readPtr, &bytesLeft, outBuf); iprintf("AACDecode: %i\nbytesLeft: %i\n", res, bytesLeft); AACGetLastFrameInfo(hAACDecoder, &aacFrameInfo); iprintf("Bitrate: %i\n", aacFrameInfo.bitRate); iprintf("%i samples\n", aacFrameInfo.outputSamps); } while(1); } int main(void) { AT91PS_PMC pPMC = AT91C_BASE_PMC; AT91PS_PIO pPIOA = AT91C_BASE_PIOA; AT91PS_RSTC pRSTC = AT91C_BASE_RSTC; // Enable the clock for PIO and UART0 pPMC->PMC_PCER = ( ( 1 << AT91C_ID_PIOA ) | ( 1 << AT91C_ID_US0 ) ); // n.b. IDs are just bit-numbers // Configure the PIO Lines corresponding to LED1 to LED4 //pPIOA->PIO_PER = LED_MASK; // pins controlled by PIO (GPIO) //pPIOA->PIO_OER = LED_MASK; // pins outputs // Turn off the LEDs. Low Active: set bits to turn off //pPIOA->PIO_SODR = LED_MASK; // enable reset-key on demo-board pRSTC->RSTC_RMR = (0xA5000000 | AT91C_RSTC_URSTEN); systime_init(); key_init(); uart0_init(); ir_init(); memset(&fs, 0, sizeof(FATFS)); FatFs = &fs; iprintf("f_mountdrv: %i\n", f_mountdrv()); memset(&dir, 0, sizeof(DIR)); assert(f_opendir(&dir, "/") == FR_OK); puts("\nDirectory of 'root':"); while ( f_readdir( &dir, &fileinfo ) == FR_OK && fileinfo.fname[0] ) { iprintf( "%s ( %li bytes )\n" , fileinfo.fname, fileinfo.fsize ) ; } { DWORD clust; // Get free clusters assert(f_getfree(&clust) == FR_OK); // Get free bytes iprintf("%lu bytes available on the disk.\n", clust * FatFs->sects_clust * 512); } //codec_bypass(); //record(); player_init(); play(); //test_raw_aac(); while(1); return 0; /* never reached */ } <file_sep>/modules/ogg/liboggvorbis/Makefile # KallistiOS Ogg/Vorbis Decoder Library # # Library Makefile # (c)2001 <NAME> # Based on KOS Makefiles by <NAME> TARGET = liboggvorbisplay.a OBJS = SUBDIRS = liboggvorbis liboggvorbisplay all: subdirs #copylibs # Copy libs from target oggvorbis and oggvorbisplay to root copylibs: cp ./liboggvorbisplay/lib/liboggvorbisplay.a ../../liboggvorbisplay.a include ../../../sdk/Makefile.library <file_sep>/firmware/isoldr/loader/kos/src/lan_adapter.c /* KallistiOS ##version## net/lan_adapter.c (c)2002 <NAME> */ #include <stdio.h> #include <string.h> #include <assert.h> #include <dc/g2bus.h> // #include <dc/asic.h> #include <dc/net/lan_adapter.h> #include <arch/irq.h> #include <arch/timer.h> #include <net/net.h> //CVSID("$Id: lan_adapter.c,v 1.8 2003/02/25 07:39:37 bardtx Exp $"); /* Contains a low-level ethernet driver for the "Lan Adapter" (HIT-0300), which is a Fujitsu ethernet chip attached to the 8-bit interface of the DC's "parallel port". The block diagram looks something like this: The DC Lan Adapter is an 8-bit G2 peripheral with the following block diagram: G2 <---> Altera PLD <---> MB86967 Ethernet <---> TDK "Pulse Transformer" ^ ^ | | v v M5M5278DVP RAM 10BT ethernet Its IO base is located at 0xa060xxxx, like the modem, and the register interface seems very similar (I suspect they actually use the exact same PLD in both, to save money). As for the Fujitsu ethernet chip, the latest updated driver in BSD was for FreeBSD 2.x (!!) and was for PCMCIA, so a bit of interpolation was required. Fortunately the Fujitsu chip is _much_ simpler and easier to work with than the later RTL chip, but unfortunately, that simplicity comes at a cost. Each packet to be send or received must be processed over a PIO interface one byte at a time. This is probably why Sega dumped it for the RTL design later on, because you can imagine the system load to do that while trying to process 3D graphics and such... This driver is really simplistic, but this should form the basis with which a better one can be written if neccessary. It was developed using KOS CVS (1.1.5+). If anyone has a DC Lan Adapter which this doesn't work with, please let me know! Thanks to TheGypsy for test hardware. Historical note: this driver was adapted from the dc-load-ip modifications I made for dc-load-ip-la. */ /* Register names. The first set of register names is always valid; the second depends on which bank you have selected. During normal operation, the last bank will be selected (the one containing the BMPR regs). Source: Fujitsu PDF. */ /* Bank-agnostic registers; the bank for these is specified as -1 so that the register access function will ignore it */ #define DLCR0R 0 #define DLCR0 DLCR0R,-1 /* Transmit Status Register */ #define DLCR0_TMTOK (1<<7) /* Transmit OK */ #define DLCR0_NETBSY (1<<6) /* Net Busy (carrier detected) */ #define DLCR0_TMTREC (1<<5) /* Transmit Packet Receive */ #define DLCR0_SRTPKT (1<<4) /* Short Packet */ #define DLCR0_JABBER (1<<3) /* Jabber */ #define DLCR0_COL (1<<2) /* Collision Error */ #define DLCR0_16COL (1<<1) /* 16 Collision Error */ #define DLCR0_BUSWRERR (1<<0) /* Bus Write Error */ #define DLCR0_CLEARALL 0xff #define DLCR1R 1 #define DLCR1 DLCR1R,-1 /* Receive Status Register */ #define DLCR1_PKTRDY (1<<7) /* Packet ready */ #define DLCR1_BUSRDERR (1<<6) /* Bus Read Error */ #define DLCR1_DMAEOP (1<<5) /* DMA Completed */ #define DLCR1_RMTRST (1<<4) /* Remote Reset */ #define DLCR1_RXSRTPKT (1<<3) /* Short Packet */ #define DLCR1_ALGERR (1<<2) /* Alignment Error */ #define DLCR1_CRCERR (1<<1) /* CRC Error */ #define DLCR1_OVRFLO (1<<0) /* Overflow Error */ #define DLCR1_CLEARALL 0xff #define DLCR2R 2 #define DLCR2 DLCR2R,-1 /* Transmit Interrupt Enable Register */ /* Use DLCR0 Constants */ #define DLCR3R 3 #define DLCR3 DLCR3R,-1 /* Receive Interrupt Enable Register */ /* Use DLCR1 Constants */ #define DLCR4R 4 #define DLCR4 DLCR4R,-1 /* Transmit Mode Register */ #define DLCR4_COLCNT(x) (((x) >> 4) & 0x0f) /* Read collision count (ro) */ #define DLCR4_CNTRL (1<<2) /* DREQ Control */ #define DLCR4_LBC (1<<1) /* Loopback Control */ #define DLCR4_DSC (1<<0) /* Disable Carrier Detect */ #define DLCR5R 5 #define DLCR5 DLCR5R,-1 /* Receive Mode Register */ #define DLCR5_BUFEMP (1<<6) /* Buffer empty? (ro) */ #define DLCR5_ACPTBADPKT (1<<5) /* Accept packets with bad CRC/length */ #define DLCR5_ADDSIZE (1<<4) /* Mac Address Size */ #define DLCR5_ENASRTPKT (1<<3) /* Enable Short Packet Receive */ #define DLCR5_AM_OFF 0 /* Address mode: receive nothing */ #define DLCR5_AM_SELF 1 /* " ": only our packets */ #define DLCR5_AM_OTHER 2 /* " ": only other node packets */ #define DLCR5_AM_PROM 3 /* " ": receive ALL packets */ #define DLCR5_AM_MASK 3 #define DLCR6R 6 #define DLCR6 DLCR6R,-1 /* Control Register 1 */ #define DLCR6_DLCRST (1<<7) /* Reset the DLC and buffers */ #define DLCR6_SCTS (1<<6) /* SRAM cycle time select */ #define DLCR6_SBW (1<<5) /* System Bus Width Select: 16/8 bit */ #define DLCR6_TBS_2K 0 /* TX Buffer Size: 2K, 1-bank */ #define DLCR6_TBS_4K 4 /* TX Buffer Size: 4K, 2-bank */ #define DLCR6_TBS_8K 8 /* TX Buffer Size: 8K, 2-bank */ #define DLCR6_TBS_16K 16 /* TX Buffer Size: 16K, 2-bank */ #define DLCR6_BS (1<<1) /* External Buffer Size: 8K/32K */ #define DLCR7R 7 #define DLCR7 DLCR7R,-1 /* Control Register 2 */ #define DLCR7_IDENT(x) (((x) >> 6) & 3) /* Chip Identification (ro) */ #define DLCR7_ID_MB86960A 0 #define DLCR7_ID_MB86964 1 #define DLCR7_ID_MB86967 2 #define DLCR7_ID_MB86965A 3 #define DLCR7_NSTBY (1<<6) /* Not-standby mode */ #define DLCR7_RBS_D8 0 /* Read Bank Select: DLCR8 - DLCR15 */ #define DLCR7_RBS_M8 4 /* " ": MAR8 - MAR15 */ #define DLCR7_RBS_B8 8 /* " ": BMPR8 - BMPR15 */ #define DLCR7_RBS_MASK 0x0C #define DLCR7_EOP (1<<1) /* DMA End Signal: active LOW / HIGH */ #define DLCR7_BSWAP (1<<0) /* Byte Swap */ #define BMPR16 16,-1 /* EEPROM Control */ #define BMPR16_ESK (1<<6) /* EEPROM Shift Clocks */ #define BMPR16_ECS (1<<5) /* EEPROM Chip Select */ #define BMPR17 17,-1 /* EEPROM Data */ #define BMPR17_EDIO (1<<7) /* EEPROM Data I/O Bit */ /* The rest of these registers must be accessed using the banking mechanism; i.e., their bank must be selected before they can be accessed at all. */ #define DLCR8 8,DLCR7_RBS_D8 /* Node ID (Mac Address) Registers */ #define DLCR14 14,DLCR7_RBS_D8 /* TDR Low */ #define DLCR15 15,DLCR7_RBS_D8 /* TDR High */ #define MAR8 8,DLCR7_RBS_M8 /* Multicast Address Registers */ #define BMPR8 8,DLCR7_RBS_B8 /* Buffer Memory Port */ #define BMPR10 10,DLCR7_RBS_B8 /* Transmit Packet Count */ #define BMPR10_TX (1<<7) /* Start transmit */ #define BMPR10_PKTCNT(x) ((x) & 0x7f) /* Remaining packet count */ #define BMPR11 11,DLCR7_RBS_B8 /* 16 Collision Control */ #define BMPR11_AUTO 6 /* Auto-retransmit */ #define BMPR11_SKIP 7 /* Skip problem packet */ #define BMPR11_MANUAL 2 /* Manually handle 16-collisions */ #define BMPR11_MANUAL_DISCARD 3 /* Discard packet during manual handling */ #define BMPR12 12,DLCR7_RBS_B8 /* DMA Enable Register, or as Fujitsu says, the DAM enable ;-) */ #define BMPR12_NLPR (1<<3) /* Long Packet Receive Disable */ #define BMPR12_RENA (1<<1) /* Receive DMA Enable */ #define BMPR12_TENA (1<<0) /* Transmit DMA Enable */ #define BMPR13 13,DLCR7_RBS_B8 /* DMA Burst/Transceiver Mode Control */ #define BMPR13_LTA (1<<5) /* Link Test Enable */ #define BMPR13_DB_1 0 /* DMA Burst Cycle Count: 1 */ #define BMPR13_DB_4 1 /* " ": 4 */ #define BMPR13_DB_18 2 /* " ": 18 */ #define BMPR13_DB_12 3 /* " ": 12 */ #define BMPR14 14,DLCR7_RBS_B8 /* Receiver Control/Transceiver IRQ Control */ #define BMPR14_LKFE (1<<6) /* Link Failure Interrupt Enable */ #define BMPR14_SDM (1<<5) /* Shutdown mode */ #define BMPR14_SKIPRX (1<<2) /* Skip RX Packet (r/w) */ #define BMPR14_SQE (1<<1) /* Signal Quality Error Int Enable */ #define BMPR14_FS (1<<0) /* Filter Self (in promisc mode) */ #define BMPR15 15,DLCR7_RBS_B8 /* Transceiver Status */ #define BMPR15_LKF (1<<6) /* Link failure */ #define BMPR15_POLREV (1<<5) /* Polarity Reverse */ #define BMPR15_SQE (1<<1) /* Signal Quality Error */ #define BMPR15_CLEARALL (BMPR15_LKF | BMPR15_POLREV | BMPR15_SQE) #define REGLOC(x) (0xa0600400 + (x) * 4) #define G2_8BP_RST 0xa0600480 /* What bank do we have selected now? */ static int la_bank = -1; /* Our network struct */ netif_t la_if; /* What's our current state? */ #define LA_NOT_STARTED 0 #define LA_DETECTED 1 #define LA_RUNNING 2 #define LA_PAUSED 3 static int la_started = LA_NOT_STARTED; /* Mac address (read from EEPROM) */ #define la_mac la_if.mac_addr /* Forward declaration */ //static void la_irq_hnd(uint32 code); /* Set the current bank */ static void la_set_bank(int bank) { int i; if (la_bank == bank) return; i = g2_read_32(REGLOC(DLCR7R)) & 0xff; g2_write_8(REGLOC(DLCR7R), (i & ~DLCR7_RBS_MASK) | bank); la_bank = bank; } /* Read a register */ static int la_read(int reg, int bank) { if (bank != -1) la_set_bank(bank); return g2_read_32(REGLOC(reg)) & 0xff; } /* Write a register */ static void la_write(int reg, int bank, int value) { if (bank != -1) la_set_bank(bank); g2_write_8(REGLOC(reg), value); } /* This is based on the JLI EEPROM reader from FreeBSD. EEPROM in the Sega adapter is a bit simpler than what is described in the Fujitsu manual -- it appears to contain only the MAC address and not a base address like the manual says. EEPROM is read one bit (!) at a time through the EEPROM interface port. */ static void la_strobe_eeprom() { la_write(BMPR16, BMPR16_ECS); la_write(BMPR16, BMPR16_ECS | BMPR16_ESK); la_write(BMPR16, BMPR16_ECS | BMPR16_ESK); la_write(BMPR16, BMPR16_ECS); } static void la_read_eeprom(uint8 *data) { uint8 /*save16, save17, */val; int n, bit; /* Save the current value of the EEPROM registers */ // save16 = la_read(BMPR16); // save17 = la_read(BMPR17); /* Read bytes from EEPROM, two per iteration */ for (n=0; n<3; n++) { /* Reset the EEPROM interface */ la_write(BMPR16, 0); la_write(BMPR17, 0); /* Start EEPROM access */ la_write(BMPR16, BMPR16_ECS); la_write(BMPR17, BMPR17_EDIO); la_strobe_eeprom(); /* Pass the iteration count as well as a READ command */ val = 0x80 | n; for (bit=0x80; bit != 0x00; bit>>=1) { la_write(BMPR17, (val & bit) ? BMPR17_EDIO : 0); la_strobe_eeprom(); } la_write(BMPR17, 0); /* Read a byte */ val = 0; for (bit=0x80; bit != 0x00; bit>>=1) { la_strobe_eeprom(); if (la_read(BMPR17) & BMPR17_EDIO) val |= bit; } *data++ = val; /* Read one more byte */ val = 0; for (bit=0x80; bit != 0x00; bit>>=1) { la_strobe_eeprom(); if (la_read(BMPR17) & BMPR17_EDIO) val |= bit; } *data++ = val; } } /* Reset the lan adapter and verify that it's there and alive */ static int la_detect() { int type; if (la_started != LA_NOT_STARTED) return -1; // assert_msg(la_started == LA_NOT_STARTED, "la_detect called out of sequence"); /* Reset the interface */ g2_write_8(G2_8BP_RST, 0); g2_write_8(G2_8BP_RST, 1); g2_write_8(G2_8BP_RST, 0); /* Give it a few ms to come back */ timer_spin_sleep(100); /* Read the chip type and verify it */ type = DLCR7_IDENT(la_read(DLCR7)); if (type != DLCR7_ID_MB86967) { // dbglog(DBG_KDEBUG, "lan_adapter: no device detected (wrong type = %d)\n", type); return -1; } /* That should do */ la_started = LA_DETECTED; return 0; } /* Reset the lan adapter and set it up for send/receive */ static int la_hw_init() { int i; if (la_started != LA_DETECTED) return -1; // assert_msg(la_started == LA_DETECTED, "la_hw_init called out of sequence"); /* Clear interrupt status */ la_write(DLCR0, DLCR0_CLEARALL); la_write(DLCR1, DLCR0_CLEARALL); /* Power down chip */ timer_spin_sleep(2); la_write(DLCR7, la_read(DLCR7) & ~DLCR7_NSTBY); timer_spin_sleep(2); /* Reset Data Link Control */ timer_spin_sleep(2); la_write(DLCR6, la_read(DLCR6) | DLCR6_DLCRST); timer_spin_sleep(2); /* Power up the chip */ timer_spin_sleep(2); la_write(DLCR7, la_read(DLCR7) | DLCR7_NSTBY); timer_spin_sleep(2); /* Read the EEPROM data */ la_read_eeprom(la_mac); /* Write the MAC address into the Node ID regs */ for (i=0; i<6; i++) la_write(i + DLCR8, la_mac[i]); /* Clear the multicast address */ for (i=0; i<6; i++) la_write(i + MAR8, 0); /* dbglog(DBG_DEBUG, "lan_adapter: MAC address is %02x:%02x:%02x:%02x:%02x:%02x\n", la_mac[0], la_mac[1], la_mac[2], la_mac[3], la_mac[4], la_mac[5]); */ /* Setup the BMPR bank for normal operation */ la_write(BMPR10, 0); la_write(BMPR11, BMPR11_AUTO); la_write(BMPR12, 0); la_write(BMPR13, 0); la_write(BMPR14, 0); la_write(BMPR15, BMPR15_CLEARALL); /* Set non-promiscuous mode (use 0x03 for promiscuous) */ la_write(DLCR5, (la_read(DLCR5) & ~DLCR5_AM_MASK) | DLCR5_AM_OTHER); /* Setup interrupt handler */ // XXX /* asic_evt_set_handler(ASIC_EVT_EXP_8BIT, la_irq_hnd); asic_evt_enable(ASIC_EVT_EXP_8BIT, ASIC_IRQB); */ /* Enable receive interrupt */ la_write(DLCR3, DLCR1_PKTRDY); /* Enable transmitter / receiver */ la_write(DLCR6, (la_read(DLCR6) & ~DLCR6_DLCRST)); la_started = LA_RUNNING; return 0; } /* Start lan adapter (after a stop) */ static void la_start() { // assert_msg(la_started == LA_PAUSED, "la_start called out of sequence"); if (la_started != LA_PAUSED) return; /* Set normal receive mode */ la_write(DLCR5, (la_read(DLCR5) & ~DLCR5_AM_MASK) | DLCR5_AM_OTHER); la_started = LA_RUNNING; } /* Temporarily stop lan adapter */ static void la_stop() { int timeout = 50; // assert_msg(la_started == LA_RUNNING, "la_stop called out of sequence"); if (la_started != LA_RUNNING) return; /* Make sure we aren't transmitting currently */ while (BMPR10_PKTCNT(la_read(BMPR10)) > 0 && (--timeout) > 0) timer_spin_sleep(2); /* Disable all receive */ la_write(DLCR5, (la_read(DLCR5) & ~DLCR5_AM_MASK) | DLCR5_AM_OFF); la_started = LA_PAUSED; } /* Shut it down for good */ static void la_hw_shutdown() { /* Power down chip */ timer_spin_sleep(2); la_write(DLCR7, la_read(DLCR7) & ~DLCR7_NSTBY); timer_spin_sleep(2); la_started = LA_NOT_STARTED; /* Unhook interrupts */ // XXX /* asic_evt_disable(ASIC_EVT_EXP_8BIT, ASIC_IRQB); asic_evt_set_handler(ASIC_EVT_EXP_8BIT, NULL); */ } /* We don't really need these stats right now but we might want 'em later */ static int total_pkts_rx = 0, total_pkts_tx = 0; /* Transmit a packet */ /* Note that it's technically possible to queue up more than one packet at a time for transmission, but this is the simple way. */ static int la_tx(const uint8 * pkt, int len) { int i, timeout; //assert_msg(la_started == LA_RUNNING, "la_tx called out of sequence"); if (la_started != LA_RUNNING) return -1; /* Wait for queue to empty */ timeout = 50; while (BMPR10_PKTCNT(la_read(BMPR10)) > 0 && (--timeout) > 0) timer_spin_sleep(2); if (timeout == 0) { //dbglog(DBG_ERROR, "la_tx timed out waiting for previous tx\n"); return 0; } /* Is the length less than the minimum? */ if (len < 0x60) len = 0x60; /* Poke the length */ la_write(BMPR8, (len & 0x00ff)); la_write(BMPR8, (len & 0xff00) >> 8); /* Write the packet */ for (i=0; i<len; i++) la_write(BMPR8, pkt[i]); /* Start the transmitter */ timer_spin_sleep(2); la_write(BMPR10, 1 | BMPR10_TX); /* 1 Packet, Start */ total_pkts_tx++; return 1; } /* Check for received packets */ static int la_rx() { int i, status, len, count; // assert_msg(la_started == LA_RUNNING, "la_rx called out of sequence"); if (la_started != LA_RUNNING) return -1; for (count = 0; ; count++) { /* Is the buffer empty? */ if (la_read(DLCR5) & DLCR5_BUFEMP) return count; /* Get the receive status byte */ status = la_read(BMPR8); (void)la_read(BMPR8); /* Get the packet length */ len = la_read(BMPR8); len |= la_read(BMPR8) << 8; /* Check for errors */ if ( (status & 0xF0) != 0x20 ) { //dbglog(DBG_ERROR, "la_rx: receive error occured (status %02x)\n", status); return -1; } /* Read the packet */ if (len > 1514) { //dbglog(DBG_ERROR, "la_rx: big packet received (size %d)\n", len); return -2; } for (i=0; i<len; i++) { net_rxbuf[i] = la_read(BMPR8); } /* Submit it for processing */ net_input(&la_if, len); total_pkts_rx++; } } #if 0 static void la_irq_hnd(uint32 code) { int intr_rx, intr_tx, hnd = 0; /* Acknowledge Lan Adapter interrupt(s) */ intr_tx = la_read(DLCR0); la_write(DLCR0, intr_tx); intr_rx = la_read(DLCR1); la_write(DLCR1, intr_rx); /* Handle receive interrupt */ if (intr_rx & DLCR1_PKTRDY) { la_rx(); hnd = 1; } if (!hnd) { //dbglog(DBG_KDEBUG, "la_irq_hnd: spurious interrupt for %02x/%02x\n", intr_tx, intr_rx); } } #endif /****************************************************************************/ /* Netcore interface */ netif_t la_if; static int la_if_detect(netif_t * self) { if (self->flags & NETIF_DETECTED) return 0; if (la_detect() < 0) return -1; self->flags |= NETIF_DETECTED; return 0; } static int la_if_init(netif_t * self) { if (self->flags & NETIF_INITIALIZED) return 0; if (la_hw_init() < 0) return -1; memcpy(self->mac_addr, la_mac, 6); self->flags |= NETIF_INITIALIZED; return 0; } static int la_if_shutdown(netif_t * self) { if (!(self->flags & NETIF_INITIALIZED)) return 0; la_hw_shutdown(); self->flags &= ~(NETIF_DETECTED | NETIF_INITIALIZED | NETIF_RUNNING); return 0; } static int la_if_start(netif_t * self) { if (!(self->flags & NETIF_INITIALIZED)) return -1; self->flags |= NETIF_RUNNING; if (la_started == LA_PAUSED) la_start(); return 0; } static int la_if_stop(netif_t * self) { if (!(self->flags & NETIF_RUNNING)) return -1; self->flags &= ~NETIF_RUNNING; if (la_started == LA_RUNNING) la_stop(); return 0; } static int la_if_tx(netif_t * self, const uint8 * data, int len) { if (!(self->flags & NETIF_RUNNING)) return -1; if (la_tx(data, len) != 1) return -1; return 0; } static int la_if_rx_poll(netif_t * self) { (void)self; return la_rx(); } /* Don't need to hook anything here yet */ static int la_if_set_flags(netif_t * self, uint32 flags_and, uint32 flags_or) { self->flags = (self->flags & flags_and) | flags_or; return 0; } /* Initialize */ int la_init() { /* Initialize our state */ la_started = LA_NOT_STARTED; /* Setup the netcore structure */ la_if.descr = "Lan Adapter (HIT-0300)"; la_if.flags = NETIF_NO_FLAGS; memset(la_if.ip_addr, 0, sizeof(la_if.ip_addr)); la_if.if_detect = la_if_detect; la_if.if_init = la_if_init; la_if.if_shutdown = la_if_shutdown; la_if.if_start = la_if_start; la_if.if_stop = la_if_stop; la_if.if_tx = la_if_tx; la_if.if_rx_poll = la_if_rx_poll; la_if.if_set_flags = la_if_set_flags; return 0; } /* Shutdown */ int la_shutdown() { la_if_shutdown(&la_if); return 0; } <file_sep>/sdk/bin/src/ciso/Makefile CFLAGS ?= -O2 # can be overriden by environment variable DEBUGFLAGS = -g -Wall -Wextra -Wconversion -Wcast-qual -Wcast-align -Wdeclaration-after-statement -Werror LDLIBS = -lz -llzo2 INSTALL = install DESTDIR = ../.. .PHONY: release release : CPPFLAGS += -DNDEBUG release : ciso .PHONY: all all : ciso .PHONY: debug debug: ciso-debug .PHONY: ciso-debug ciso-debug: CFLAGS = $(DEBUGFLAGS) ciso-debug: ciso .PHONY: install install : ciso $(INSTALL) -m 755 ciso $(DESTDIR)/ciso .PHONY: clean clean: $(RM) *.o $(RM) ciso <file_sep>/modules/ogg/liboggvorbis/liboggvorbisplay/misc.h /* KallistiOS Ogg/Vorbis Decoder Library * for KOS ##version## * * sndvorbisfile.h * (c)2001/2002 <NAME> * * Basic Ogg/Vorbis stream information and decoding routines used by * libsndoggvorbis. May also be used directly for playback without * threading. */ /* Typedefinition for File Information Following the Ogg-Vorbis Spec * * TITLE :Track name * VERSION :The version field may be used to differentiate multiple version of the * same track title in a single collection. (e.g. remix info) * ALBUM :The collection name to which this track belongs * TRACKNUMBER :The track number of this piece if part of a specific larger collection * or album * ARTIST :Track performer * ORGANIZATION :Name of the organization producing the track (i.e. the 'record label') * DESCRIPTION :A short text description of the contents * GENRE :A short text indication of music genre * DATE :Date the track was recorded * LOCATION :Location where track was recorded * COPYRIGHT :Copyright information * ISRC :ISRC number for the track; see {the ISRC intro page} for more information on * ISRC numbers. * * (Based on v-comment.html found in original OggVorbis packages) */ typedef struct { char *artist; char *title; char *version; char *album; char *tracknumber; char *organization; char *description; char *genre; char *date; char *location; char *copyright; char *isrc; const char *filename; long nominalbitrate; long actualbitrate; long actualposition; } VorbisFile_info_t; <file_sep>/lib/SDL_gui/Widget.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include "SDL_gui.h" GUI_Widget::GUI_Widget(const char *aname, int x, int y, int w, int h) : GUI_Drawable(aname, x, y, w, h) { parent = 0; //wtype = WIDGET_TYPE_OTHER; } GUI_Widget::~GUI_Widget(void) { } void GUI_Widget::SetAlign(int mask) { ClearFlags(WIDGET_ALIGN_MASK); WriteFlags(WIDGET_ALIGN_MASK, mask); } void GUI_Widget::SetTransparent(int flag) { if (flag) SetFlags(WIDGET_TRANSPARENT); else ClearFlags(WIDGET_TRANSPARENT); } /* set/clear the disabled flag for a widget */ void GUI_Widget::SetEnabled(int flag) { if (flag) ClearFlags(WIDGET_DISABLED); else SetFlags(WIDGET_DISABLED); } /* set the state of a widget (mainly for ToggleButton) */ void GUI_Widget::SetState(int state) { if (state) SetFlags(WIDGET_TURNED_ON); else ClearFlags(WIDGET_TURNED_ON); } /* get the state of a widget (mainly for ToggleButton) */ int GUI_Widget::GetState() { return (flags & WIDGET_TURNED_ON) != 0; } void GUI_Widget::SetParent(GUI_Drawable *aparent) { parent = aparent; } GUI_Drawable *GUI_Widget::GetParent(void) { return parent; } void GUI_Widget::Update(int force) { if (parent==0) return; if (force) { if (flags & WIDGET_TRANSPARENT) parent->Erase(&area); SDL_Rect r = area; r.x = r.y = 0; DrawWidget(&r); } } void GUI_Widget::Draw(GUI_Surface *image, const SDL_Rect *sr, const SDL_Rect *dr) { if (parent) { SDL_Rect dest = Adjust(dr); parent->Draw(image, sr, &dest); } } void GUI_Widget::Fill(const SDL_Rect *dr, SDL_Color c) { if (parent) { SDL_Rect dest = Adjust(dr); parent->Fill(&dest, c); } } void GUI_Widget::Erase(const SDL_Rect *dr) { if (parent) { SDL_Rect dest = Adjust(dr); if (flags & WIDGET_TRANSPARENT) parent->Erase(&dest); DrawWidget(&dest); } } void GUI_Widget::DrawWidget(const SDL_Rect *clip) { } extern "C" { void GUI_WidgetUpdate(GUI_Widget *widget, int force) { widget->DoUpdate(force); } void GUI_WidgetDraw(GUI_Widget *widget, GUI_Surface *image, const SDL_Rect *sr, const SDL_Rect *dr) { widget->Draw(image, sr, dr); } void GUI_WidgetErase(GUI_Widget *widget, const SDL_Rect *dr) { widget->Erase(dr); } void GUI_WidgetFill(GUI_Widget *widget, const SDL_Rect *dr, SDL_Color c) { widget->Fill(dr, c); } int GUI_WidgetEvent(GUI_Widget *widget, const SDL_Event *event, int xoffset, int yoffset) { return widget->Event(event, xoffset, yoffset); } void GUI_WidgetClicked(GUI_Widget *widget, int x, int y) { widget->Clicked(x, y); } void GUI_WidgetContextClicked(GUI_Widget *widget, int x, int y) { widget->ContextClicked(x, y); } void GUI_WidgetHighlighted(GUI_Widget *widget, int x, int y) { widget->Highlighted(x, y); } void GUI_WidgetSetAlign(GUI_Widget *widget, int align) { widget->SetAlign(align); } void GUI_WidgetMarkChanged(GUI_Widget *widget) { widget->MarkChanged(); } void GUI_WidgetSetTransparent(GUI_Widget *widget, int trans) { widget->SetTransparent(trans); } void GUI_WidgetSetEnabled(GUI_Widget *widget, int flag) { widget->SetEnabled(flag); } void GUI_WidgetTileImage(GUI_Widget *widget, GUI_Surface *surface, const SDL_Rect *area, int x_offset, int y_offset) { widget->TileImage(surface, area, x_offset, y_offset); } void GUI_WidgetSetFlags(GUI_Widget *widget, int mask) { widget->SetFlags(mask); } void GUI_WidgetClearFlags(GUI_Widget *widget, int mask) { widget->ClearFlags(mask); } void GUI_WidgetSetState(GUI_Widget *widget, int state) { widget->SetState(state); } int GUI_WidgetGetState(GUI_Widget *widget) { return widget->GetState(); } SDL_Rect GUI_WidgetGetArea(GUI_Widget *widget) { return widget->GetArea(); } void GUI_WidgetSetPosition(GUI_Widget *widget, int x, int y) { widget->SetPosition(x, y); } void GUI_WidgetSetSize(GUI_Widget *widget, int w, int h) { widget->SetSize(w, h); } int GUI_WidgetGetType(GUI_Widget *widget) { return ((GUI_Drawable*)widget)->GetWType(); } int GUI_WidgetGetFlags(GUI_Widget *widget) { return ((GUI_Drawable*)widget)->GetFlags(); } GUI_Widget *GUI_WidgetGetParent(GUI_Widget *widget) { return (GUI_Widget *)((GUI_Drawable*)widget)->GetParent(); } } <file_sep>/modules/ogg/liboggvorbis/liboggvorbis/libogg/Makefile # KallistiOS Ogg/Vorbis Decoder Library # # Library Makefile # (c)2001 <NAME> # Based on KOS Makefiles by <NAME> SUBDIRS= src all: subdirs clean: -rm -rf build/*.o build/*.a src/*.o src/*.a include $(KOS_BASE)/Makefile.rules <file_sep>/firmware/bios/bootstrap/makeprog.py #!/usr/bin/env python fd = open("prog.bin", "r").read() for i in range(0, len(fd), 8): sub = map(lambda x:ord(x), fd[i:i+8]) print "\t.byte\t0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x" % \ (sub[0], sub[1], sub[2], sub[3], sub[4], sub[5], sub[6], sub[7]) <file_sep>/firmware/isoldr/loader/kos/dc/net/broadband_adapter.h /* KallistiOS ##version## * * dc/net/broadband_adapter.h * * Copyright (C)2001-2002,2004 <NAME> * * $Id: broadband_adapter.h,v 1.1 2003/07/31 00:54:04 bardtx Exp $ */ #ifndef __DC_NET_BROADBAND_ADAPTER_H #define __DC_NET_BROADBAND_ADAPTER_H #include <sys/cdefs.h> __BEGIN_DECLS #include <arch/types.h> #include <kos/net.h> /* RTL8139C register definitions */ #define RT_IDR0 0x00 /* Mac address */ #define RT_MAR0 0x08 /* Multicast filter */ #define RT_TXSTATUS0 0x10 /* Transmit status (4 32bit regs) */ #define RT_TXADDR0 0x20 /* Tx descriptors (also 4 32bit) */ #define RT_RXBUF 0x30 /* Receive buffer start address */ #define RT_RXEARLYCNT 0x34 /* Early Rx byte count */ #define RT_RXEARLYSTATUS 0x36 /* Early Rx status */ #define RT_CHIPCMD 0x37 /* Command register */ #define RT_RXBUFTAIL 0x38 /* Current address of packet read (queue tail) */ #define RT_RXBUFHEAD 0x3A /* Current buffer address (queue head) */ #define RT_INTRMASK 0x3C /* Interrupt mask */ #define RT_INTRSTATUS 0x3E /* Interrupt status */ #define RT_TXCONFIG 0x40 /* Tx config */ #define RT_RXCONFIG 0x44 /* Rx config */ #define RT_TIMER 0x48 /* A general purpose counter */ #define RT_RXMISSED 0x4C /* 24 bits valid, write clears */ #define RT_CFG9346 0x50 /* 93C46 command register */ #define RT_CONFIG0 0x51 /* Configuration reg 0 */ #define RT_CONFIG1 0x52 /* Configuration reg 1 */ #define RT_TIMERINT 0x54 /* Timer interrupt register (32 bits) */ #define RT_MEDIASTATUS 0x58 /* Media status register */ #define RT_CONFIG3 0x59 /* Config register 3 */ #define RT_CONFIG4 0x5A /* Config register 4 */ #define RT_MULTIINTR 0x5C /* Multiple interrupt select */ #define RT_MII_TSAD 0x60 /* Transmit status of all descriptors (16 bits) */ #define RT_MII_BMCR 0x62 /* Basic Mode Control Register (16 bits) */ #define RT_MII_BMSR 0x64 /* Basic Mode Status Register (16 bits) */ #define RT_AS_ADVERT 0x66 /* Auto-negotiation advertisement reg (16 bits) */ #define RT_AS_LPAR 0x68 /* Auto-negotiation link partner reg (16 bits) */ #define RT_AS_EXPANSION 0x6A /* Auto-negotiation expansion reg (16 bits) */ /* RTL8193C MII (media independent interface) control bits */ #define RT_MII_AN_START 0x0200 /* Start auto-negotiation */ #define RT_MII_AN_ENABLE 0x1000 /* Enable auto-negotiation */ #define RT_MII_RESET 0x8000 /* Reset the MII chip */ /* RTL8193C MII (media independent interface) status bits */ #define RT_MII_LINK 0x0004 /* Link is present */ #define RT_MII_AN_CAPABLE 0x0008 /* Can do auto negotiation */ #define RT_MII_AN_COMPLETE 0x0020 /* Auto-negotiation complete */ #define RT_MII_10_HALF 0x0800 /* Can do 10Mbit half duplex */ #define RT_MII_10_FULL 0x1000 /* Can do 10Mbit full */ #define RT_MII_100_HALF 0x2000 /* Can do 100Mbit half */ #define RT_MII_100_FULL 0x4000 /* Can do 100Mbit full */ /* RTL8193C command bits; or these together and write teh resulting value into CHIPCMD to execute it. */ #define RT_CMD_RESET 0x10 #define RT_CMD_RX_ENABLE 0x08 #define RT_CMD_TX_ENABLE 0x04 #define RT_CMD_RX_BUF_EMPTY 0x01 /* RTL8139C interrupt status bits */ #define RT_INT_PCIERR 0x8000 /* PCI Bus error */ #define RT_INT_TIMEOUT 0x4000 /* Set when TCTR reaches TimerInt value */ #define RT_INT_RXFIFO_OVERFLOW 0x0040 /* Rx FIFO overflow */ #define RT_INT_RXFIFO_UNDERRUN 0x0020 /* Packet underrun / link change */ #define RT_INT_LINK_CHANGE 0x0020 /* Packet underrun / link change */ #define RT_INT_RXBUF_OVERFLOW 0x0010 /* Rx BUFFER overflow */ #define RT_INT_TX_ERR 0x0008 #define RT_INT_TX_OK 0x0004 #define RT_INT_RX_ERR 0x0002 #define RT_INT_RX_OK 0x0001 /* Composite RX bits we check for while doing an RX interrupt */ #define RT_INT_RX_ACK (RT_INT_RXFIFO_OVERFLOW | RT_INT_RXBUF_OVERFLOW | RT_INT_RX_OK) /* RTL8139C transmit status bits */ #define RT_TX_CARRIER_LOST 0x80000000 /* Carrier sense lost */ #define RT_TX_ABORTED 0x40000000 /* Transmission aborted */ #define RT_TX_OUT_OF_WINDOW 0x20000000 /* Out of window collision */ #define RT_TX_STATUS_OK 0x00008000 /* Status ok: a good packet was transmitted */ #define RT_TX_UNDERRUN 0x00004000 /* Transmit FIFO underrun */ #define RT_TX_HOST_OWNS 0x00002000 /* Set to 1 when DMA operation is completed */ #define RT_TX_SIZE_MASK 0x00001fff /* Descriptor size mask */ /* RTL8139C receive status bits */ #define RT_RX_MULTICAST 0x00008000 /* Multicast packet */ #define RT_RX_PAM 0x00004000 /* Physical address matched */ #define RT_RX_BROADCAST 0x00002000 /* Broadcast address matched */ #define RT_RX_BAD_SYMBOL 0x00000020 /* Invalid symbol in 100TX packet */ #define RT_RX_RUNT 0x00000010 /* Packet size is <64 bytes */ #define RT_RX_TOO_LONG 0x00000008 /* Packet size is >4K bytes */ #define RT_RX_CRC_ERR 0x00000004 /* CRC error */ #define RT_RX_FRAME_ALIGN 0x00000002 /* Frame alignment error */ #define RT_RX_STATUS_OK 0x00000001 /* Status ok: a good packet was received */ /* Initialize */ int bba_init(); /* Shutdown */ int bba_shutdown(); extern netif_t bba_if; __END_DECLS #endif /* __DC_NET_BROADBAND_ADAPTER_H */ <file_sep>/firmware/aica/codec/play_aac.c /* Copyright (C) 2006 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <assert.h> #include <stdio.h> #include <string.h> #include "AT91SAM7S64.h" #include "play_aac.h" #include "aacdec.h" #include "ff.h" #include "dac.h" #include "profile.h" #define debug_printf #define PROFILE_START(x) #define PROFILE_END() static HAACDecoder hAACDecoder; static AACFrameInfo aacFrameInfo; static unsigned char *readPtr; static int bytesLeft=0, bytesLeftBeforeDecoding=0, err, offset; static int nFrames = 0; static unsigned char *aacbuf; static unsigned int aacbuf_size; static unsigned char allocated = 0; void aac_init(unsigned char *buffer, unsigned int buffer_size) { aacbuf = buffer; aacbuf_size = buffer_size; aac_reset(); } void aac_reset() { readPtr = NULL; bytesLeftBeforeDecoding = bytesLeft = 0; nFrames = 0; } void aac_alloc() { if (!allocated) assert(hAACDecoder = AACInitDecoder()); allocated = 1; } void aac_free() { if (allocated) AACFreeDecoder(hAACDecoder); allocated = 0; } void aac_setup_raw() { memset(&aacFrameInfo, 0, sizeof(AACFrameInfo)); aacFrameInfo.nChans = 2; aacFrameInfo.sampRateCore = 44100; aacFrameInfo.profile = AAC_PROFILE_LC; assert(AACSetRawBlockParams(hAACDecoder, 0, &aacFrameInfo) == 0); } int aac_process(FIL *aacfile, int raw) { int writeable_buffer; WORD bytes_read; if (readPtr == NULL) { assert(f_read(aacfile, (BYTE *)aacbuf, aacbuf_size, &bytes_read) == FR_OK); if (bytes_read == aacbuf_size) { readPtr = aacbuf; offset = 0; bytesLeft = aacbuf_size; } else { puts("can't read more data"); return -1; } } if (!raw) { offset = AACFindSyncWord(readPtr, bytesLeft); if (offset < 0) { puts("Error: AACFindSyncWord returned <0"); // read more data assert(f_read(aacfile, (BYTE *)aacbuf, aacbuf_size, &bytes_read) == FR_OK); if (bytes_read == aacbuf_size) { readPtr = aacbuf; offset = 0; bytesLeft = aacbuf_size; return 0; } else { puts("can't read more data"); return -1; } } readPtr += offset; bytesLeft -= offset; } bytesLeftBeforeDecoding = bytesLeft; // check if this is really a valid frame // (the decoder does not seem to calculate CRC, so make some plausibility checks) /* if (AACGetNextFrameInfo(hAACDecoder, &aacFrameInfo, readPtr) == 0 && aacFrameInfo.sampRateOut == 44100 && aacFrameInfo.nChans == 2) { debug_printf("Found a frame at offset %x\n", offset + readPtr - aacbuf + aacfile->FilePtr); } else { iprintf("this is no valid frame\n"); // advance data pointer // TODO: what if bytesLeft == 0? assert(bytesLeft > 0); bytesLeft -= 1; readPtr += 1; return 0; } */ if (bytesLeft < 1024) { PROFILE_START("file_read"); // after fseeking backwards the FAT has to be read from the beginning -> S L O W //assert(f_lseek(aacfile, aacfile->fptr - bytesLeftBeforeDecoding) == FR_OK); // better: move unused rest of buffer to the start // no overlap as long as (1024 <= aacbuf_size/2), so no need to use memove memcpy(aacbuf, readPtr, bytesLeft); assert(f_read(aacfile, (BYTE *)aacbuf + bytesLeft, aacbuf_size - bytesLeft, &bytes_read) == FR_OK); if (bytes_read == aacbuf_size - bytesLeft) { readPtr = aacbuf; offset = 0; bytesLeft = aacbuf_size; PROFILE_END(); return 0; } else { puts("can't read more data"); return -1; } } debug_printf("bytesLeftBeforeDecoding: %i\n", bytesLeftBeforeDecoding); while (dac_fill_dma() == 0); writeable_buffer = dac_get_writeable_buffer(); if (writeable_buffer == -1) { return 0; } debug_printf("wb %i\n", writeable_buffer); PROFILE_START("AACDecode"); err = AACDecode(hAACDecoder, &readPtr, &bytesLeft, dac_buffer[writeable_buffer]); PROFILE_END(); nFrames++; if (err) { switch (err) { case ERR_AAC_INDATA_UNDERFLOW: puts("ERR_AAC_INDATA_UNDERFLOW"); //outOfData = 1; // try to read more data // seek backwards to reread partial frame at end of current buffer // TODO: find out why it doesn't work if the following line is uncommented //aacfile->FilePtr -= bytesLeftBefore; f_read(aacfile, (BYTE *)aacbuf, aacbuf_size, &bytes_read); if (bytes_read == aacbuf_size) { // TODO: reuse writable_buffer readPtr = aacbuf; offset = 0; bytesLeft = aacbuf_size; puts("indata underflow, reading more data"); } else { puts("can't read more data"); return -1; } break; default: iprintf("unknown error: %i\n", err); // skip this frame if (bytesLeft > 0) { bytesLeft --; readPtr ++; } else { // TODO assert(0); } break; } dac_buffer_size[writeable_buffer] = 0; } else { /* no error */ AACGetLastFrameInfo(hAACDecoder, &aacFrameInfo); debug_printf("Bitrate: %i\r\n", aacFrameInfo.bitRate); debug_printf("%i samples\n", aacFrameInfo.outputSamps); debug_printf("Words remaining in first DMA buffer: %i\n", *AT91C_SSC_TCR); debug_printf("Words remaining in next DMA buffer: %i\n", *AT91C_SSC_TNCR); dac_buffer_size[writeable_buffer] = aacFrameInfo.outputSamps; debug_printf("%lu Hz, %i kbps\n", aacFrameInfo.sampRateOut, aacFrameInfo.bitRate/1000); if (dac_set_srate(aacFrameInfo.sampRateOut) != 0) { iprintf("unsupported sample rate: %lu\n", aacFrameInfo.sampRateOut); return -1; } } while (dac_fill_dma() == 0); return 0; } <file_sep>/firmware/isoldr/loader/kos/net/icmp.c /* KallistiOS ##version## net/icmp.c Copyright (C)2002,2004 <NAME> */ #include <stdio.h> #include <string.h> #include <kos/net.h> #include <net/net.h> int net_icmp_input(netif_t *src, uint8 *pkt, int pktsize) { eth_hdr_t *eth; ip_hdr_t *ip; icmp_hdr_t *icmp; int i; uint8 tmp[6]; (void)pktsize; /* Get pointers */ eth = (eth_hdr_t*)(pkt + 0); ip = (ip_hdr_t*)(pkt + sizeof(eth_hdr_t)); icmp = (icmp_hdr_t*)(pkt + sizeof(eth_hdr_t) + 4*(ip->version_ihl & 0x0f)); /* Check icmp checksum */ memset(net_txbuf, 0, ntohs(ip->length) + (ntohs(ip->length) % 2) - 4*(ip->version_ihl & 0x0f)); i = icmp->checksum; icmp->checksum = 0; memcpy(net_txbuf, icmp, ntohs(ip->length) - 4*(ip->version_ihl & 0x0f)); icmp->checksum = net_checksum((uint16*)net_txbuf, (ntohs(ip->length) + 1) / 2 - 2*(ip->version_ihl & 0x0f)); if (i != icmp->checksum) { printf("net_icmp: icmp with invalid checksum\n"); return 0; } if (icmp->type == 8) { /* echo request */ icmp->type = 0; /* echo reply */ /* Swap source and dest addresses */ memcpy(tmp, eth->dest, 6); memcpy(eth->dest, eth->src, 6); memcpy(eth->src, tmp, 6); /* Swap source and dest ip addresses */ memcpy(&i, &ip->src, 4); memcpy(&ip->src, &ip->dest, 4); memcpy(&ip->dest, &i, 4); /* Recompute the IP header checksum */ ip->checksum = 0; ip->checksum = net_checksum((uint16*)ip, 2*(ip->version_ihl & 0x0f)); /* Recompute the ICMP header checksum */ icmp->checksum = 0; icmp->checksum = net_checksum((uint16*)icmp, ntohs(ip->length)/2 - 2*(ip->version_ihl & 0x0f)); /* Send it */ src->if_tx(src, pkt, sizeof(eth_hdr_t) + ntohs(ip->length)); } return 0; } <file_sep>/modules/aicaos/arm/interrupt.h #ifndef _INIT_H #define _INIT_H #include <stdint.h> void reset(void); uint32_t int_enable(void); uint32_t int_disable(void); void int_restore(uint32_t context); int int_enabled(void); void int_acknowledge(void); #endif <file_sep>/modules/mp3/libmp3/xingmp3/dec8.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** dec8.c *************************************************** ANSI C MPEG audio decoder Layer II only mpeg1 and mpeg2 output sample type and sample rate conversion decode mpeg to 8000Ks mono output 16 bit linear, 8 bit linear, or u-law mod 6/29/95 bugfix in u-law table mod 11/15/95 for Layer I mod 1/7/97 minor mods for warnings ******************************************************************/ /***************************************************************** MPEG audio software decoder portable ANSI c. Decodes all Layer II to 8000Ks mono pcm. Output selectable: 16 bit linear, 8 bit linear, u-law. ------------------------------------- int audio_decode8_init(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit) initilize decoder: return 0 = fail, not 0 = success MPEG_HEAD *h input, mpeg header info (returned by call to head_info) framebytes input, mpeg frame size (returned by call to head_info) reduction_code input, ignored transform_code input, ignored convert_code input, set convert_code = 4*bit_code + chan_code bit_code: 1 = 16 bit linear pcm 2 = 8 bit (unsigned) linear pcm 3 = u-law (8 bits unsigned) chan_code: 0 = convert two chan to mono 1 = convert two chan to mono 2 = convert two chan to left chan 3 = convert two chan to right chan freq_limit input, ignored --------------------------------- void audio_decode8_info( DEC_INFO *info) information return: Call after audio_decode8_init. See mhead.h for information returned in DEC_INFO structure. --------------------------------- IN_OUT audio_decode8(unsigned char *bs, void *pcmbuf) decode one mpeg audio frame: bs input, mpeg bitstream, must start with sync word. Caution: may read up to 3 bytes beyond end of frame. pcmbuf output, pcm samples. IN_OUT structure returns: Number bytes conceptually removed from mpeg bitstream. Returns 0 if sync loss. Number bytes of pcm output. This may vary from frame to frame. *****************************************************************/ #include <float.h> #include <math.h> #include <string.h> #include "L3.h" #include "mhead.h" /* mpeg header structure */ /*------------------------------------------*/ static int output_code; static int convert(void *mv, unsigned char *pcm); static int convert_8bit(void *mv, unsigned char *pcm); static int convert_u(void *mv, unsigned char *pcm); static CVT_FUNCTION_8 cvt_table[3] = { convert, convert_8bit, convert_u, }; void mpeg8_init(MPEG8 *m) { memset(&m->dec, 0, sizeof(m->dec)); m->dec.ncnt = 8 * 288; m->dec.ncnt1 = 8 * 287; m->dec.nlast = 287; m->dec.ndeci = 11; m->dec.kdeci = 8 * 288; m->dec.first_pass = 1; } /*====================================================================*/ IN_OUT audio_decode8(MPEG8 *m, unsigned char *bs, signed short *pcmbuf) { IN_OUT x; x = audio_decode(&m->cupper, bs, m->dec.pcm); if (x.in_bytes <= 0) return x; x.out_bytes = m->dec.convert_routine(m, (void *) pcmbuf); return x; } /*--------------8Ks 16 bit pcm --------------------------------*/ static int convert(void *mv, unsigned char y0[]) { MPEG8 *m = mv; int i, k; long alpha; short *y; y = (short *) y0; k = 0; if (m->dec.kdeci < m->dec.ncnt) { alpha = m->dec.kdeci & 7; y[k++] = (short) (m->dec.xsave + ((alpha * (m->dec.pcm[0] - m->dec.xsave)) >> 3)); m->dec.kdeci += m->dec.ndeci; } m->dec.kdeci -= m->dec.ncnt; for (; m->dec.kdeci < m->dec.ncnt1; m->dec.kdeci += m->dec.ndeci) { i = m->dec.kdeci >> 3; alpha = m->dec.kdeci & 7; y[k++] = (short) (m->dec.pcm[i] + ((alpha * (m->dec.pcm[i + 1] - m->dec.pcm[i])) >> 3)); } m->dec.xsave = m->dec.pcm[m->dec.nlast]; /* printf("\n k out = %4d", k); */ return sizeof(short) * k; } /*----------------8Ks 8 bit unsigned pcm ---------------------------*/ static int convert_8bit(void *mv, unsigned char y[]) { MPEG8 *m = mv; int i, k; long alpha; k = 0; if (m->dec.kdeci < m->dec.ncnt) { alpha = m->dec.kdeci & 7; y[k++] = (unsigned char) (((m->dec.xsave + ((alpha * (m->dec.pcm[0] - m->dec.xsave)) >> 3)) >> 8) + 128); m->dec.kdeci += m->dec.ndeci; } m->dec.kdeci -= m->dec.ncnt; for (; m->dec.kdeci < m->dec.ncnt1; m->dec.kdeci += m->dec.ndeci) { i = m->dec.kdeci >> 3; alpha = m->dec.kdeci & 7; y[k++] = (unsigned char) (((m->dec.pcm[i] + ((alpha * (m->dec.pcm[i + 1] - m->dec.pcm[i])) >> 3)) >> 8) + 128); } m->dec.xsave = m->dec.pcm[m->dec.nlast]; /* printf("\n k out = %4d", k); */ return k; } /*--------------8Ks u-law --------------------------------*/ static int convert_u(void *mv, unsigned char y[]) { MPEG8 *m = mv; int i, k; long alpha; unsigned char *look; look = m->dec.look_u + 4096; k = 0; if (m->dec.kdeci < m->dec.ncnt) { alpha = m->dec.kdeci & 7; y[k++] = look[(m->dec.xsave + ((alpha * (m->dec.pcm[0] - m->dec.xsave)) >> 3)) >> 3]; m->dec.kdeci += m->dec.ndeci; } m->dec.kdeci -= m->dec.ncnt; for (; m->dec.kdeci < m->dec.ncnt1; m->dec.kdeci += m->dec.ndeci) { i = m->dec.kdeci >> 3; alpha = m->dec.kdeci & 7; y[k++] = look[(m->dec.pcm[i] + ((alpha * (m->dec.pcm[i + 1] - m->dec.pcm[i])) >> 3)) >> 3]; } m->dec.xsave = m->dec.pcm[m->dec.nlast]; /* printf("\n k out = %4d", k); */ return k; } /*--------------------------------------------------------------------*/ static int ucomp3(int x) /* re analog devices CCITT G.711 */ { int s, p, y, t, u, u0, sign; sign = 0; if (x < 0) { x = -x; sign = 0x0080; } if (x > 8031) x = 8031; x += 33; t = x; for (s = 0; s < 15; s++) { if (t & 0x4000) break; t <<= 1; } y = x << s; p = (y >> 10) & 0x0f; /* position */ s = 9 - s; /* segment */ u0 = (((s << 4) | p) & 0x7f) | sign; u = u0 ^ 0xff; return u; } /*------------------------------------------------------------------*/ static void table_init(MPEG8 *m) { int i; for (i = -4096; i < 4096; i++) m->dec.look_u[4096 + i] = (unsigned char) (ucomp3(2 * i)); } /*-------------------------------------------------------------------*/ int audio_decode8_init(MPEG8 *m, MPEG_HEAD * h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit) { int istat; int outvals; static int sr_table[2][4] = {{22, 24, 16, 0}, {44, 48, 32, 0}}; if (m->dec.first_pass) { table_init(m); m->dec.first_pass = 0; } if ((h->sync & 1) == 0) return 0; // fail mpeg 2.5 output_code = convert_code >> 2; if (output_code < 1) output_code = 1; /* 1= 16bit 2 = 8bit 3 = u */ if (output_code > 3) output_code = 3; /* 1= 16bit 2 = 8bit 3 = u */ convert_code = convert_code & 3; if (convert_code <= 0) convert_code = 1; /* always cvt to mono */ reduction_code = 1; if (h->id) reduction_code = 2; /* select convert routine */ m->dec.convert_routine = cvt_table[output_code - 1]; /* init decimation/convert routine */ /*-- MPEG-2 layer III --*/ if ((h->option == 1) && h->id == 0) outvals = 576 >> reduction_code; else if (h->option == 3) outvals = 384 >> reduction_code; /*-- layer I --*/ else outvals = 1152 >> reduction_code; m->dec.ncnt = 8 * outvals; m->dec.ncnt1 = 8 * (outvals - 1); m->dec.nlast = outvals - 1; m->dec.ndeci = sr_table[h->id][h->sr_index] >> reduction_code; m->dec.kdeci = 8 * outvals; /* printf("\n outvals %d", outvals); */ freq_limit = 3200; istat = audio_decode_init(&m->cupper, h, framebytes_arg, reduction_code, transform_code, convert_code, freq_limit); return istat; } /*-----------------------------------------------------------------*/ void audio_decode8_info(MPEG8 *m, DEC_INFO * info) { audio_decode_info(&m->cupper, info); info->samprate = 8000; if (output_code != 1) info->bits = 8; if (output_code == 3) info->type = 10; } <file_sep>/modules/isofs/cdi.c /** * Copyright (c) 2013-2014 by SWAT <<EMAIL>> www.dc-swat.ru * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <kos.h> #include "console.h" #include "isofs/cdi.h" #include "internal.h" //#define DEBUG 1 static const uint8 TRACK_START_MARKER[20] = { 0x00,0x00,0x01,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF, 0x00,0x00,0x01,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF }; // static const uint8 EXT_MARKER[9] = {0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}; struct CDI_track_data { uint32 pregap_length; uint32 length; char unknown2[6]; uint32 mode; char unknown3[0x0c]; uint32 start_lba; uint32 total_length; char unknown4[0x10]; uint32 sector_size; char unknown5[0x1D]; } __attribute__((packed)); static int check_cdi_image(file_t fd, CDI_trailer_t *trail) { uint32 len; fs_seek(fd, -8, SEEK_END); len = fs_tell(fd) + 8; fs_read(fd, trail, sizeof(CDI_trailer_t)); if(trail->header_offset >= len || trail->header_offset == 0) { #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Invalid CDI image: %ld >= %ld, version: %08lx\n", __func__, trail->header_offset, len, trail->version); #endif return -1; } if(trail->version != CDI_V2_ID && trail->version != CDI_V3_ID && trail->version != CDI_V35_ID) { #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Invalid CDI image version: %08lx\n", __func__, trail->version); #endif return -1; } #ifdef DEBUG dbglog(DBG_DEBUG, "%s: CDI image version %08lx\n", __func__, trail->version); #endif return 0; } CDI_header_t *cdi_open(file_t fd) { CDI_trailer_t trail; if(check_cdi_image(fd, &trail) < 0) { return NULL; } int i, j; uint16 total_tracks = 0; uint32 posn = 0; uint32 sector_size = 0, offset = 0; uint8 marker[20]; CDI_header_t *hdr; hdr = (CDI_header_t*)malloc(sizeof(CDI_header_t)); memset_sh4(hdr, 0, sizeof(CDI_header_t)); memcpy_sh4(&hdr->trail, &trail, sizeof(CDI_trailer_t)); #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Seek to header at %ld\n", __func__, (hdr->trail.version == CDI_V35_ID ? fs_total(fd) - hdr->trail.header_offset : hdr->trail.header_offset) ); #endif if(hdr->trail.version == CDI_V35_ID) { fs_seek(fd, -(off_t)hdr->trail.header_offset, SEEK_END); } else { fs_seek(fd, (off_t)hdr->trail.header_offset, SEEK_SET); } fs_read(fd, &hdr->session_count, sizeof(hdr->session_count)); if(!hdr->session_count || hdr->session_count > CDI_MAX_SESSIONS) { free(hdr); ds_printf("DS_ERROR: Bad sessions count in CDI image: %d\n", hdr->session_count); return NULL; } #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Sessions count: %d\n", __func__, hdr->session_count); #endif for(i = 0; i < hdr->session_count; i++) { hdr->sessions[i] = (CDI_session_t *)malloc(sizeof(CDI_session_t)); if(hdr->sessions[i] == NULL) { goto error; } fs_read(fd, &hdr->sessions[i]->track_count, sizeof(hdr->sessions[i]->track_count)); #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Session: %d, tracks count: %d\n", __func__, i + 1, hdr->sessions[i]->track_count); #endif if((i != hdr->session_count-1 && hdr->sessions[i]->track_count < 1) || hdr->sessions[i]->track_count > 99 ) { ds_printf("DS_ERROR: Invalid number of tracks (%d), bad cdi image\n", hdr->sessions[i]->track_count); goto error; } if(hdr->sessions[i]->track_count + total_tracks > 99) { ds_printf("DS_ERROR: Invalid number of tracks in disc, bad cdi image\n"); goto error; } for(j = 0; j < hdr->sessions[i]->track_count; j++) { hdr->sessions[i]->tracks[j] = (CDI_track_t *)malloc(sizeof(CDI_track_t)); if(hdr->sessions[i]->tracks[j] == NULL) { goto error; } uint32 new_fmt = 0; uint8 fnamelen = 0; fs_read(fd, &new_fmt, sizeof(new_fmt)); if(new_fmt != 0) { /* Additional data 3.00.780+ ?? */ fs_seek(fd, 8, SEEK_CUR); /* Skip */ } fs_read(fd, marker, 20); if(memcmp(marker, TRACK_START_MARKER, 20) != 0) { ds_printf("DS_ERROR: Track start marker not found, error reading cdi image\n"); goto error; } fs_seek(fd, 4, SEEK_CUR); fs_read(fd, &fnamelen, 1); fs_seek(fd, (off_t)fnamelen, SEEK_CUR); /* skip over the filename */ fs_seek(fd, 19, SEEK_CUR); fs_read(fd, &new_fmt, sizeof(new_fmt)); if(new_fmt == 0x80000000) { fs_seek(fd, 10, SEEK_CUR); } else { fs_seek(fd, 2, SEEK_CUR); } struct CDI_track_data trk; memset(&trk, 0, sizeof(trk)); fs_read(fd, &trk, sizeof(trk)); hdr->sessions[i]->tracks[j]->length = trk.length; hdr->sessions[i]->tracks[j]->mode = trk.mode; hdr->sessions[i]->tracks[j]->pregap_length = trk.pregap_length; hdr->sessions[i]->tracks[j]->sector_size = trk.sector_size; hdr->sessions[i]->tracks[j]->start_lba = trk.start_lba; hdr->sessions[i]->tracks[j]->total_length = trk.total_length; if(hdr->trail.version != CDI_V2_ID) { uint32 extmarker = 0; fs_seek(fd, 5, SEEK_CUR); fs_read(fd, &extmarker, sizeof(extmarker)); if(extmarker == 0xFFFFFFFF) { fs_seek(fd, 78, SEEK_CUR); } } sector_size = cdi_track_sector_size(hdr->sessions[i]->tracks[j]); offset = posn + hdr->sessions[i]->tracks[j]->pregap_length * sector_size; #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Session: %d, track: %d, lba: %ld, length: %ld, mode: %ld, secsize: %ld, offset: %ld\n", __func__, i + 1, j + 1, hdr->sessions[i]->tracks[j]->start_lba, hdr->sessions[i]->tracks[j]->length, hdr->sessions[i]->tracks[j]->mode, hdr->sessions[i]->tracks[j]->sector_size, offset); #endif hdr->sessions[i]->tracks[j]->offset = offset; posn += hdr->sessions[i]->tracks[j]->total_length * sector_size; total_tracks++; } fs_seek(fd, 12, SEEK_CUR); if(hdr->trail.version != CDI_V2_ID) { fs_seek(fd, 1, SEEK_CUR); } } return hdr; error: cdi_close(hdr); return NULL; } int cdi_close(CDI_header_t *hdr) { if(!hdr) { return -1; } int i, j; for(i = 0; i < hdr->session_count; i++) { if(hdr->sessions[i] != NULL && hdr->sessions[i]->track_count > 0 && hdr->sessions[i]->track_count < CDI_MAX_TRACKS) { for(j = 0; j < hdr->sessions[i]->track_count; j++) { if(hdr->sessions[i]->tracks[j] != NULL) { free(hdr->sessions[i]->tracks[j]); } } free(hdr->sessions[i]); } } free(hdr); return 0; } uint16 cdi_track_sector_size(CDI_track_t *track) { switch(track->mode) { case 0: return (track->sector_size == 2 ? 2352 : 0); case 1: return (track->sector_size == 0 ? 2048 : 0); case 2: switch(track->sector_size) { case 0: return 2048; case 1: return 2336; case 2: default: return 0; } default: break; } return 0; } int cdi_get_toc(CDI_header_t *hdr, CDROM_TOC *toc) { int i, j = 0; uint16 total_tracks = 0; uint8 ctrl = 0, adr = 1; for(i = 0; i < hdr->session_count; i++) { for(j = 0; j < hdr->sessions[i]->track_count; j++) { ctrl = (hdr->sessions[i]->tracks[j]->mode == 0 ? 0 : 4); toc->entry[total_tracks] = ctrl << 28 | adr << 24 | (hdr->sessions[i]->tracks[j]->start_lba + 150); #ifdef DEBUG dbglog(DBG_DEBUG, "%s: Track%d %08lx\n", __func__, (int)total_tracks, toc->entry[total_tracks]); #endif total_tracks++; } } CDI_session_t *last_session = hdr->sessions[ hdr->session_count - 1 ]; CDI_track_t *last_track = last_session->tracks[ last_session->track_count - 1 ]; ctrl = (last_track->mode == 0 ? 0 : 4); toc->first = ctrl << 28 | adr << 24 | 1 << 16; toc->last = ctrl << 28 | adr << 24 | total_tracks << 16; toc->leadout_sector = ctrl << 28 | adr << 24 | (last_track->start_lba + last_track->length + 150); for(i = total_tracks; i < 99; i++) { toc->entry[i] = -1; } #ifdef DEBUG dbglog(DBG_DEBUG, "%s:\n First track %08lx\n Last track %08lx\n Leadout %08lx\n", __func__, toc->first, toc->last, toc->leadout_sector); #endif return 0; } CDI_track_t *cdi_get_track(CDI_header_t *hdr, uint32 lba) { int i, j; for(i = hdr->session_count - 1; i > -1; i--) { for(j = hdr->sessions[i]->track_count - 1; j > -1; j--) { if(hdr->sessions[i]->tracks[j]->start_lba <= lba) { return hdr->sessions[i]->tracks[j]; } } } return NULL; } uint32 cdi_get_offset(CDI_header_t *hdr, uint32 lba, uint16 *sector_size) { CDI_track_t *track = cdi_get_track(hdr, lba); if(track == NULL) { return -1; } uint32 offset = lba - track->start_lba; *sector_size = cdi_track_sector_size(track); if(!offset) { offset = track->offset; } else { offset *= *sector_size; offset += track->offset; } return offset; } int cdi_read_sectors(CDI_header_t *hdr, file_t fd, uint8 *buff, uint32 start, uint32 count) { uint16 sector_size; uint32 offset = cdi_get_offset(hdr, start, &sector_size); if(offset == (uint32)-1) { return -1; } #ifdef DEBUG dbglog(DBG_DEBUG, "%s: %ld %ld at %ld mode %d\n", __func__, start, count, offset, sector_size); #endif fs_seek(fd, offset, SEEK_SET); return read_sectors_data(fd, count, sector_size, buff); } <file_sep>/commands/ciso/main.c /* This file is part of Ciso. Ciso is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Ciso is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Copyright 2005 BOOSTER Copyright 2011-2015 SWAT */ #include <ds.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <zlib/zlib.h> #include <zlib/zconf.h> #include <minilzo/minilzo.h> #include <isofs/ciso.h> static const char *fname_in,*fname_out; static FILE *fin,*fout; static z_stream z; static unsigned int *index_buf = NULL; static unsigned int *crc_buf = NULL; static unsigned char *block_buf1 = NULL; static unsigned char *block_buf2 = NULL; /**************************************************************************** compress ISO to CSO ****************************************************************************/ static CISO_header_t ciso; static int ciso_total_block; static int is_ziso = 0; unsigned long long check_file_size(FILE *fp) { unsigned long long pos; if( fseek(fp,0,SEEK_END) < 0) return -1; pos = ftell(fp); if(pos==-1) return pos; /* init ciso header */ memset(&ciso,0,sizeof(ciso)); if(is_ziso) { ciso.magic[0] = 'Z'; } else { ciso.magic[0] = 'C'; } ciso.magic[1] = 'I'; ciso.magic[2] = 'S'; ciso.magic[3] = 'O'; ciso.ver = 0x01; ciso.block_size = 0x800; /* ISO9660 one of sector */ ciso.total_bytes = pos; #if 0 /* align >0 has bug */ for(ciso.align = 0 ; (ciso.total_bytes >> ciso.align) >0x80000000LL ; ciso.align++); #endif ciso_total_block = pos / ciso.block_size ; fseek(fp,0,SEEK_SET); return pos; } /**************************************************************************** decompress CSO to ISO ****************************************************************************/ int decomp_ciso(void) { unsigned int index , index2; unsigned long long read_pos , read_size; int index_size; int block; int cmp_size; int status; int percent_period; int percent_cnt; int plain; unsigned long lzolen; /* read header */ if( fread(&ciso, 1, sizeof(ciso), fin) != sizeof(ciso) ) { ds_printf("file read error\n"); return 1; } /* check header */ if( (ciso.magic[0] != 'Z' && ciso.magic[0] != 'C') || ciso.magic[1] != 'I' || ciso.magic[2] != 'S' || ciso.magic[3] != 'O' || ciso.block_size ==0 || ciso.total_bytes == 0 ) { ds_printf("ciso file format error\n"); return 1; } ciso_total_block = ciso.total_bytes / ciso.block_size; /* allocate index block */ index_size = (ciso_total_block + 1 ) * sizeof(unsigned long); index_buf = malloc(index_size); block_buf1 = malloc(ciso.block_size*2); block_buf2 = malloc(ciso.block_size*2); if( !index_buf || !block_buf1 || !block_buf2 ) { ds_printf("Can't allocate memory %d and %d x2\n", index_size, ciso.block_size*2); return 1; } memset(index_buf,0,index_size); /* read index block */ if( fread(index_buf, 1, index_size, fin) != index_size ) { ds_printf("file read error\n"); return 1; } /* show info */ ds_printf("Decompress '%s' to '%s'\n",fname_in,fname_out); ds_printf("Total File Size %ld bytes\n",ciso.total_bytes); ds_printf("block size %d bytes\n",ciso.block_size); ds_printf("total blocks %d blocks\n",ciso_total_block); ds_printf("index align %d\n",1<<ciso.align); ds_printf("type %s\n", ciso.magic[0] == 'Z' ? "ZISO" : "CISO"); if(ciso.magic[0] == 'Z') { if(lzo_init() != LZO_E_OK) { ds_printf("lzo_init() failed\n"); return 1; } } else { /* init zlib */ z.zalloc = Z_NULL; z.zfree = Z_NULL; z.opaque = Z_NULL; } /* decompress data */ percent_period = ciso_total_block/100; percent_cnt = 0; for(block = 0;block < ciso_total_block ; block++) { if(--percent_cnt<=0) { percent_cnt = percent_period; ds_printf("decompress %d%%\r",block / percent_period); } if(ciso.magic[0] == 'C') { if (inflateInit2(&z,-15) != Z_OK) { ds_printf("deflateInit : %s\n", (z.msg) ? z.msg : "???"); return 1; } } /* check index */ index = index_buf[block]; plain = index & 0x80000000; index &= 0x7fffffff; read_pos = index << (ciso.align); if(plain) { read_size = ciso.block_size; } else { index2 = index_buf[block+1] & 0x7fffffff; read_size = (index2-index) << (ciso.align); } fseek(fin,read_pos,SEEK_SET); z.avail_in = fread(block_buf2, 1, read_size , fin); if(z.avail_in != read_size) { ds_printf("block=%d : read error\n",block); return 1; } if(plain) { memcpy(block_buf1,block_buf2,read_size); cmp_size = read_size; } else { if(ciso.magic[0] == 'Z') { z.avail_out = ciso.block_size; status = lzo1x_decompress(block_buf2, z.avail_in, block_buf1, &lzolen, NULL); cmp_size = lzolen; if(status != LZO_E_OK) { ds_printf("block %d:lzo1x_decompress: %d\n", status); return 1; } } else { z.next_out = block_buf1; z.avail_out = ciso.block_size; z.next_in = block_buf2; status = inflate(&z, Z_FULL_FLUSH); if (status != Z_STREAM_END) /*if (status != Z_OK)*/ { ds_printf("block %d:inflate : %s[%d]\n", block,(z.msg) ? z.msg : "error",status); return 1; } cmp_size = ciso.block_size - z.avail_out; } if(cmp_size != ciso.block_size) { ds_printf("block %d : block size error %d != %d\n",block,cmp_size , ciso.block_size); return 1; } } /* write decompressed block */ if(fwrite(block_buf1, 1,cmp_size , fout) != cmp_size) { ds_printf("block %d : Write error\n",block); return 1; } if(ciso.magic[0] == 'C') { /* term zlib */ if (inflateEnd(&z) != Z_OK) { ds_printf("inflateEnd : %s\n", (z.msg) ? z.msg : "error"); return 1; } } } ds_printf("ciso decompress completed\n"); return 0; } /**************************************************************************** compress ISO ****************************************************************************/ int comp_ciso(int level, int no_comp_diff) { unsigned long long file_size; unsigned long long write_pos; int index_size; int block; unsigned char buf4[64]; int cmp_size; int status; int percent_period; int percent_cnt; int align,align_b,align_m; lzo_voidp wrkmem = NULL; unsigned long lzolen; file_size = check_file_size(fin); if(file_size<0) { ds_printf("Can't get file size\n"); return 1; } /* allocate index block */ index_size = (ciso_total_block + 1 ) * sizeof(unsigned long); index_buf = malloc(index_size); crc_buf = malloc(index_size); block_buf1 = malloc(ciso.block_size*2); block_buf2 = malloc(ciso.block_size*2); if( !index_buf || !crc_buf || !block_buf1 || !block_buf2 ) { ds_printf("Can't allocate memory\n"); return 1; } memset(index_buf,0,index_size); memset(crc_buf,0,index_size); memset(buf4,0,sizeof(buf4)); if(is_ziso) { if(lzo_init() != LZO_E_OK) { ds_printf("lzo_init() failed\n"); return 1; } wrkmem = (lzo_voidp) malloc(LZO1X_1_MEM_COMPRESS); // wrkmem = (lzo_voidp) malloc(LZO1X_999_MEM_COMPRESS); } else { /* init zlib */ z.zalloc = Z_NULL; z.zfree = Z_NULL; z.opaque = Z_NULL; } /* show info */ ds_printf("Compress '%s' to '%s'\n",fname_in,fname_out); ds_printf("Total File Size %ld bytes\n",ciso.total_bytes); ds_printf("block size %d bytes\n",ciso.block_size); ds_printf("index align %d\n",1<<ciso.align); ds_printf("compress level %d\n",level); ds_printf("type %s\n", is_ziso ? "ZISO" : "CISO"); /* write header block */ fwrite(&ciso,1,sizeof(ciso),fout); /* dummy write index block */ fwrite(index_buf,1,index_size,fout); write_pos = sizeof(ciso) + index_size; /* compress data */ percent_period = ciso_total_block/100; percent_cnt = ciso_total_block/100; align_b = 1<<(ciso.align); align_m = align_b -1; for(block = 0;block < ciso_total_block ; block++) { if(--percent_cnt<=0) { percent_cnt = percent_period; ds_printf("compress %3d%% avarage rate %3d%%\r" ,block / percent_period ,block==0 ? 0 : 100*write_pos/(block*0x800)); } if(!is_ziso) { if (deflateInit2(&z, level , Z_DEFLATED, -15,8,Z_DEFAULT_STRATEGY) != Z_OK) { ds_printf("deflateInit : %s\n", (z.msg) ? z.msg : "???"); return 1; } } /* write align */ align = (int)write_pos & align_m; if(align) { align = align_b - align; if(fwrite(buf4,1,align, fout) != align) { ds_printf("block %d : Write error\n",block); return 1; } write_pos += align; } /* mark offset index */ index_buf[block] = write_pos>>(ciso.align); /* read buffer */ z.next_out = block_buf2; z.avail_out = ciso.block_size*2; z.next_in = block_buf1; z.avail_in = fread(block_buf1, 1, ciso.block_size , fin); if(z.avail_in != ciso.block_size) { ds_printf("block=%d : read error\n",block); return 1; } if(is_ziso) { status = lzo1x_1_compress(block_buf1, z.avail_in, block_buf2, &lzolen, wrkmem); //status = lzo1x_999_compress(block_buf1, z.avail_in, block_buf2, &lzolen, wrkmem); //ds_printf("in: %d out: %d\n", z.avail_in, lzolen); if (status != LZO_E_OK) { /* this should NEVER happen */ ds_printf("compression failed: lzo1x_1_compress: %d\n", status); return 1; } cmp_size = lzolen; } else { /* compress block status = deflate(&z, Z_FULL_FLUSH);*/ status = deflate(&z, Z_FINISH); if (status != Z_STREAM_END) /* if (status != Z_OK) */ { ds_printf("block %d:deflate : %s[%d]\n", block,(z.msg) ? z.msg : "error",status); return 1; } cmp_size = ciso.block_size*2 - z.avail_out; } /* choise plain / compress */ if(cmp_size >= (ciso.block_size - no_comp_diff)) { cmp_size = ciso.block_size; memcpy(block_buf2,block_buf1,cmp_size); /* plain block mark */ index_buf[block] |= 0x80000000; } /* write compressed block */ if(fwrite(block_buf2, 1,cmp_size , fout) != cmp_size) { ds_printf("block %d : Write error\n",block); return 1; } /* mark next index */ write_pos += cmp_size; if(!is_ziso) { /* term zlib */ if (deflateEnd(&z) != Z_OK) { ds_printf("deflateEnd : %s\n", (z.msg) ? z.msg : "error"); return 1; } } } /* last position (total size)*/ index_buf[block] = write_pos>>(ciso.align); /* write header & index block */ fseek(fout,sizeof(ciso),SEEK_SET); fwrite(index_buf,1,index_size,fout); ds_printf("ciso compress completed, total size = %8d bytes, rate %d%%\n", (int)write_pos, (int)(write_pos * 100 / ciso.total_bytes)); return 0; } /**************************************************************************** main ****************************************************************************/ int main(int argc, char *argv[]) { int level; int result; int no_comp_diff = 48; ds_printf("ISO9660 comp/dec to/from CISO/ZISO v%d.%d build %d by SWAT\n", VER_MAJOR, VER_MINOR, VER_BUILD); if (argc < 5) { ds_printf("Usage: %s library level infile outfile [no_comp_diff_bytes]\n", argv[0]); ds_printf(" level: 1-9 for compress (1=fast/large - 9=small/slow), 0 for decompress\n"); ds_printf(" library: zlib or lzo\n\n"); return CMD_NO_ARG; } level = argv[2][0] - '0'; if(level < 0 || level > 9) { ds_printf("Unknown mode: %c\n", argv[2][0]); return CMD_ERROR; } fname_in = argv[3]; fname_out = argv[4]; if(argc > 5) { no_comp_diff = atoi(argv[5]); } if(!strcmp("lzo", argv[1])) { is_ziso = 1; } if ((fin = fopen(fname_in, "rb")) == NULL) { ds_printf("Can't open %s\n", fname_in); return CMD_ERROR; } if ((fout = fopen(fname_out, "wb")) == NULL) { ds_printf("Can't create %s\n", fname_out); return CMD_ERROR; } if(level==0) result = decomp_ciso(); else result = comp_ciso(level, no_comp_diff); /* free memory */ if(index_buf) free(index_buf); if(crc_buf) free(crc_buf); if(block_buf1) free(block_buf1); if(block_buf2) free(block_buf2); /* close files */ fclose(fin); fclose(fout); return (result ? CMD_ERROR : CMD_OK); } <file_sep>/lib/SDL_Console/include/DT_drawtext.h /* SDL_console: An easy to use drop-down console based on the SDL library Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WHITOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library Generla Public License along with this library; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA <NAME> <EMAIL> */ #ifndef Drawtext_h #define Drawtext_h #define TRANS_FONT 1 #ifdef __cplusplus extern "C" { #endif typedef struct BitFont_td { SDL_Surface *FontSurface; int CharWidth; int CharHeight; int FontNumber; struct BitFont_td *NextFont; } BitFont; void DT_DrawText(const char *string, SDL_Surface *surface, int FontType, int x, int y ); int DT_LoadFont(const char *BitmapName, int flags ); int DT_FontHeight( int FontNumber ); int DT_FontWidth( int FontNumber ); BitFont* DT_FontPointer(int FontNumber ); void DT_DestroyDrawText(); #ifdef __cplusplus }; #endif #endif <file_sep>/modules/dreameye/module.c /* DreamShell ##version## module.c - dreameye module Copyright (C)2009-2016 SWAT */ #include "ds.h" #include "drivers/dreameye.h" DEFAULT_MODULE_EXPORTS_CMD(dreameye, "Dreameye camera"); static int save_image(const char *fn, uint8 *buf, int size) { file_t fd; fd = fs_open(fn, O_CREAT | O_WRONLY); if(fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open file for write: %s\n", fn); return -1; } fs_write(fd, buf, size); fs_close(fd); return 0; } int builtin_dreameye_cmd(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s options args...\n" "Options: \n" " -g, --grab -Grab images from dreameye and save to file\n" " -e, --erase -Erase images from dreameye\n" " -c, --count -Get images count\n" " -p, --param -Get param\n\n" "Arguments: \n" " -f, --file -File for save image\n" " -d, --dir -Directory for save all images\n" " -n, --num -Image number for grab or erase (doesn't set it for all)\n\n" "Example: %s -g -n 2 -f /sd/photo.jpg\n" " %s -g -d /sd", argv[0], argv[0], argv[0]); return CMD_NO_ARG; } /* Arguments */ int grab = 0, count = 0, erase = 0, param = 0; char *file = NULL, *dir = NULL; int num = -1; /* Buffers */ char fn[NAME_MAX]; uint8 *buf; int size, err, i; /* Device state */ maple_device_t *dreameye; dreameye_state_t *state; struct cfg_option options[] = { {"grab", 'g', NULL, CFG_BOOL, (void *) &grab, 0}, {"count", 'c', NULL, CFG_BOOL, (void *) &count, 0}, {"erase", 'e', NULL, CFG_BOOL, (void *) &erase, 0}, {"param", 'p', NULL, CFG_BOOL, (void *) &param, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, {"num", 'n', NULL, CFG_INT, (void *) &num, 0}, {"dir", 'd', NULL, CFG_STR, (void *) &dir, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); dreameye = maple_enum_type(0, MAPLE_FUNC_CAMERA); if(!dreameye) { ds_printf("DS_ERROR: Couldn't find any attached devices, bailing out.\n"); return CMD_ERROR; } state = (dreameye_state_t *)maple_dev_status(dreameye); if(param) { uint16 val; while(++num < 0x20) { dreameye_get_param(dreameye, DREAMEYE_COND_REG_JANGGU, num & 0xff, &val); ds_printf("0x%02x = 0x%02x\n", num & 0xff, val & 0xff); } return CMD_OK; } /* Get count option */ if(count) { ds_printf("DS_PROCESS: Attempting to grab the number of saved images...\n"); dreameye_get_image_count(dreameye, 1); if(state->image_count_valid && state->image_count > 0) { ds_printf("DS_INFO: Count of images: %d\n", state->image_count); } else { ds_printf("DS_INFO: No images avaible.\n"); } } /* Grap data option */ if(grab) { ds_printf("DS_PROCESS: Attempting to grab the %s...\n", (num > -1 ? "image" : "all images")); if(num < 0) { dreameye_get_image_count(dreameye, 1); if(!state->image_count_valid || !state->image_count) { ds_printf("DS_ERROR: No images avaible.\n"); return CMD_ERROR; } for(i = 2; i < state->image_count + 2; i++) { err = dreameye_get_image(dreameye, i, &buf, &size); if(err != MAPLE_EOK) { ds_printf("DS_ERROR: No image data at index: %d\n", i); break; } sprintf(fn, "%s/photo_%d.jpg", dir, i); ds_printf("DS_OK: Image received successfully. Writing %d bytes to %s\n", size, fn); if(save_image(fn, buf, size) < 0) { ds_printf("DS_ERROR: Couldn't save image to %s\n", fn); } free(buf); } } else { if(num < 2) { err = dreameye_get_video_frame(dreameye, num, &buf, &size); } else { err = dreameye_get_image(dreameye, num, &buf, &size); } if(err != MAPLE_EOK) { ds_printf("DS_ERROR: No image data at index: %d\n", num); return CMD_ERROR; } ds_printf("DS_OK: Image received successfully. Writing %d bytes to %s\n", size, file); if(save_image(file, buf, size) < 0) { ds_printf("DS_ERROR: Couldn't save image to %s\n", file); free(buf); return CMD_ERROR; } free(buf); } ds_printf("DS_OK: Complete.\n"); return CMD_OK; } /* Erase option */ if(erase) { if(num < 2 || num > 33) { ds_printf("DS_ERROR: Wrong image index: %d\n", num); return CMD_ERROR; } ds_printf("DS_PROCESS: Erasing %s...\n", (num > 1 ? "image" : "all images")); err = dreameye_erase_image(dreameye, (num > 1 ? num : 0xFF), 1); if(err != MAPLE_EOK) { if(num > -1) { ds_printf("DS_ERROR: Couldn't erase image at index: %d\n", num); } else { ds_printf("DS_ERROR: Couldn't erase all images\n"); } return CMD_ERROR; } ds_printf("DS_OK: Complete.\n"); return CMD_OK; } return (!count ? CMD_NO_ARG : CMD_OK); } <file_sep>/include/console.h /** * \file console.h * \brief DreamShell console * \date 2004-2014 * \author SWAT www.dc-swat.ru */ #ifndef _DS_CONSOLE_H #define _DS_CONSOLE_H #ifndef _NO_VIDEO_H #include "video.h" #else #include "list.h" #endif typedef enum { CMD_OK = 0, CMD_NO_ARG, CMD_ERROR, CMD_NOT_EXISTS } CMD_RESULT; typedef enum { CMD_TYPE_INTERNAL = 0, CMD_TYPE_ELF, CMD_TYPE_LUA, CMD_TYPE_DSC, CMD_TYPE_BIN, CMD_TYPE_UKNOWN } CMD_TYPES; typedef int CmdHandler(int, char *[]); typedef struct Cmd { const char *command; const char *desc; CmdHandler *handler; } Cmd_t; #define CMD_DEFAULT_ARGS_PARSER(options) \ do { \ CFG_CONTEXT con = cfg_get_context(options); \ cfg_set_context_flag(con, CFG_IGNORE_UNKNOWN); \ \ if (con == NULL) { \ ds_printf("DS_ERROR: Not enough memory\n"); \ return CMD_ERROR; \ } \ \ cfg_set_cmdline_context(con, 1, -1, argv); \ \ if (cfg_parse(con) != CFG_OK) { \ ds_printf("DS_ERROR: Parsing command line: %s\n", \ cfg_get_error_str(con)); \ return CMD_ERROR; \ } \ \ cfg_free_context(con); \ } while(0) int CallCmd(int argc, char *argv[]); int CallExtCmd(int argc, char *argv[]); int CallCmdFile(const char *fn, int argc, char *argv[]); int CheckExtCmdType(const char *fn); Cmd_t *AddCmd(const char *cmd, const char *helpmsg, CmdHandler *handler); void RemoveCmd(Cmd_t *cmd); Item_list_t *GetCmdList(); Cmd_t *GetCmdByName(const char *name); int InitCmd(); void ShutdownCmd(); void SetConsoleDebug(int mode); int ds_printf(const char *fmt, ...); int ds_uprintf(const char *fmt, ...); int dbg_printf(const char *fmt, ...); int dsystem(const char *buff); int dsystemf(const char *fmt, ...); int dsystem_script(const char *fn); int dsystem_buff(const char *buff); int InitConsole(const char *font, const char *background, int lines, int x, int y, int w, int h, int alpha); void ShutdownConsole(); void DrawConsole(); int ToggleConsole(); void ShowConsole(); void HideConsole(); int ConsoleIsVisible(); #ifndef _NO_VIDEO_H ConsoleInformation *GetConsole(); #endif extern dbgio_handler_t dbgio_ds; extern dbgio_handler_t dbgio_sd; #endif <file_sep>/firmware/aica/codec/serial.h #ifndef serial_h_ #define serial_h_ void uart0_init (void); int uart0_putc(int ch); int uart0_putchar (int ch); /* replaces \n with \r\n */ int uart0_puts ( char *s ); /* uses putc */ int uart0_prints ( char* s ); /* uses putchar */ int uart0_kbhit( void ); int uart0_getc ( void ); #endif <file_sep>/modules/s3m/libs3mplay/libs3mplay.c /* KallistiOS ##version## libs3mplay.c (C) 2011 <NAME> Based on: 2ndmix.c (c)2000-2002 <NAME> */ #include <kos.h> #include <stdlib.h> #include <assert.h> /**********************************************************/ #include "libs3mplay.h" #include "s3mplay.h" volatile unsigned long *snd_dbg = (unsigned long*)0xa080ffc0; static int s3m_size=0; /* Load and start an S3M file from disk or memory */ int s3m_play(char *fn) { int idx, r; FILE * fd; unsigned char buffer[2048]; spu_disable(); printf("LibS3MPlay: Loading %s\r\n", fn); fd = fopen( fn, "rb" ); if (fd == 0) return S3M_ERROR_IO; fseek( fd, 0, SEEK_END ); s3m_size = ftell( fd ); fseek( fd, 0, SEEK_SET ); if( s3m_size > 1024*512*3 ) return S3M_ERROR_MEM; idx = 0x10000; /* Load 2048 bytes at a time */ while ( (r=fread(buffer, 1, 2048, fd)) > 0) { spu_memload(idx, buffer, r); idx += r; } fclose(fd); printf("LibS3MPlay: Loading ARM program\r\n"); spu_memload(0, s3mplay, sizeof(s3mplay)); spu_enable(); while (*snd_dbg != 3) ; while (*snd_dbg == 3) ; printf("S3M File Now Plays on the AICA processor\r\n"); return S3M_SUCCESS; } /* Stop the AICA SPU and reset the memory */ void s3m_stop() { printf("LibS3MPlay: Stopping\n"); spu_disable(); spu_memset(0x10000, 0, s3m_size ); spu_memset(0, 0, sizeof(s3mplay) ); } <file_sep>/applications/speedtest/modules/module.c /* DreamShell ##version## module.c - Speedtest app module Copyright (C)2014 megavolt85 Copyright (C)2014-2020 SWAT http://www.dc-swat.ru */ #include "ds.h" DEFAULT_MODULE_EXPORTS(app_speedtest); static struct { App_t *app; GUI_Widget *cd_c; GUI_Widget *sd_c; GUI_Widget *hdd_c; GUI_Widget *pc_c; GUI_Widget *speedwr; GUI_Widget *speedrd; GUI_Widget *status; } self; static uint8 rd_buff[0x10000] __attribute__((aligned(32))); static void show_status_ok(char *msg) { GUI_LabelSetTextColor(self.status, 28, 227, 70); GUI_LabelSetText(self.status, msg); ScreenWaitUpdate(); } static void show_status_error(char *msg) { GUI_LabelSetTextColor(self.status, 255, 0, 0); GUI_LabelSetText(self.status, msg); } void Speedtest_Run(GUI_Widget *widget) { uint8 *buff = (uint8*)0x8c400000; size_t buff_size = 0x10000; int size = 0x800000, cnt = 0, rs; int64 time_before, time_after; uint32 t; double speed; file_t fd; int read_only = 0; char name[64]; char result[128]; const char *wname = GUI_ObjectGetName((GUI_Object *)widget); if(!strncasecmp(wname, "/cd", 3)) { read_only = 1; snprintf(name, sizeof(name), "%s/1DS_CORE.BIN", wname); if(FileExists(name)) { goto readtest; } else { snprintf(name, sizeof(name), "%s/1ST_READ.BIN", wname); goto readtest; } } show_status_ok("Testing WRITE speed..."); GUI_LabelSetText(self.speedwr, "..."); GUI_LabelSetText(self.speedrd, " "); snprintf(name, sizeof(name), "%s/%s.tst", wname, lib_get_name()); if(FileExists(name)) { fs_unlink(name); } /* WRITE TEST */ fd = fs_open(name, O_CREAT | O_WRONLY); if (fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open %s for write: %d\n", name, errno); show_status_error("Can't open file for write"); return; } ShutdownVideoThread(); time_before = timer_ms_gettime64(); while(cnt < size) { rs = fs_write(fd, buff, buff_size); if(rs <= 0) { fs_close(fd); InitVideoThread(); ds_printf("DS_ERROR: Can't write to file: %d\n", errno); show_status_error("Can't write to file"); return; } buff += rs; cnt += rs; } time_after = timer_ms_gettime64(); InitVideoThread(); t = (uint32)(time_after - time_before); speed = size / ((float)t / 1000); fs_close(fd); snprintf(result, sizeof(result), "Write speed %.2f Kbytes/s (%.2f Mbit/s) Time: %ld ms", speed / 1024, ((speed / 1024) / 1024) * 8, t); GUI_LabelSetText(self.speedwr, result); show_status_ok("Complete!"); ds_printf("DS_OK: Complete!\n" " Test: write\n Time: %ld ms\n" " Speed: %.2f Kbytes/s (%.2f Mbit/s)\n" " Size: %d Kb\n Buff: %d Kb\n", t, speed / 1024, ((speed / 1024) / 1024) * 8, size / 1024, buff_size / 1024); readtest: show_status_ok("Testing READ speed..."); GUI_LabelSetText(self.speedrd, "..."); /* READ TEST */ fd = fs_open(name, O_RDONLY); if (fd == FILEHND_INVALID) { ds_printf("DS_ERROR: Can't open %s for read: %d\n", name, errno); show_status_error("Can't open file for read"); return; } if(read_only) { GUI_LabelSetText(self.speedwr, "Write test passed"); /* Reset ISO9660 filesystem cache */ fs_ioctl(fd, 0, NULL); fs_close(fd); fd = fs_open(name, O_RDONLY); } time_before = time_after = t = cnt = 0; speed = 0.0f; size = fs_total(fd); buff = rd_buff; ShutdownVideoThread(); time_before = timer_ms_gettime64(); while(cnt < size) { rs = fs_read(fd, buff, buff_size); if(rs <= 0) { fs_close(fd); InitVideoThread(); ds_printf("DS_ERROR: Can't read file: %d\n", errno); show_status_error("Can't read file"); return; } cnt += rs; } time_after = timer_ms_gettime64(); t = (uint32)(time_after - time_before); speed = size / ((float)t / 1000); fs_close(fd); if(!read_only) { fs_unlink(name); } else { cdrom_spin_down(); } snprintf(result, sizeof(result), "Read speed %.2f Kbytes/s (%.2f Mbit/s) Time: %ld ms", speed / 1024, ((speed / 1024) / 1024) * 8, t); InitVideoThread(); ds_printf("DS_OK: Complete!\n" " Test: read\n Time: %ld ms\n" " Speed: %.2f Kbytes/s (%.2f Mbit/s)\n" " Size: %d Kb\n Buff: %d Kb\n", t, speed / 1024, ((speed / 1024) / 1024) * 8, size / 1024, buff_size / 1024); GUI_LabelSetText(self.speedrd, result); show_status_ok("Complete!"); } void Speedtest_Init(App_t *app) { memset(&self, 0, sizeof(self)); if(app != NULL) { self.app = app; self.speedrd = APP_GET_WIDGET("speedr_text"); self.speedwr = APP_GET_WIDGET("speedw_text"); self.status = APP_GET_WIDGET("status_text"); self.cd_c = APP_GET_WIDGET("/cd"); self.sd_c = APP_GET_WIDGET("/sd"); self.hdd_c = APP_GET_WIDGET("/ide"); self.pc_c = APP_GET_WIDGET("/pc"); if(!DirExists("/pc")) GUI_WidgetSetEnabled(self.pc_c, 0); if(!DirExists("/sd")) GUI_WidgetSetEnabled(self.sd_c, 0); if(is_custom_bios()/*!DirExists("/cd")*/) { GUI_WidgetSetEnabled(self.cd_c, 0); } if(!DirExists("/ide")) GUI_WidgetSetEnabled(self.hdd_c, 0); } else { ds_printf("DS_ERROR: %s: Attempting to call %s is not by the app initiate.\n", lib_get_name(), __func__); } } <file_sep>/lib/SDL_gui/SDL_gui.cc #include <string.h> #include <stdlib.h> #include "SDL_gui.h" //#include <SDL/SDL_thread.h> static GUI_Screen *screen = NULL; /* static int gui_running = 0; static SDL_mutex *gui_mutex=0; static Uint32 gui_thread=0; */ GUI_Screen *GUI_GetScreen() { return screen; } void GUI_SetScreen(GUI_Screen *new_screen) { // FIXME incref/decref? screen = new_screen; } #if 0 int GUI_GetRunning() { return gui_running; } void GUI_SetRunning(int value) { gui_running = value; } int GUI_Lock() { return SDL_LockMutex(gui_mutex); } int GUI_Unlock() { return SDL_UnlockMutex(gui_mutex); } int GUI_MustLock() { return (SDL_ThreadID() != gui_thread); } int GUI_Init(void) { SDL_EnableUNICODE(1); gui_mutex = SDL_CreateMutex(); return 0; } void GUI_SetThread(Uint32 id) { gui_thread = id; } void GUI_Run() { SDL_Event event; GUI_SetThread(SDL_ThreadID()); GUI_SetRunning(1); /* update the screen */ screen->DoUpdate(1); /* process events */ while (GUI_GetRunning()) { SDL_WaitEvent(&event); do { GUI_Lock(); screen->Event(&event, 0, 0); GUI_Unlock(); } while (SDL_PollEvent(&event)); GUI_Lock(); screen->DrawMouse(); screen->DoUpdate(0); GUI_Unlock(); } } void GUI_Quit() { SDL_DestroyMutex(gui_mutex); } #endif int GUI_ClipRect(SDL_Rect *sr, SDL_Rect *dr, const SDL_Rect *clip) { int dx = dr->x; int dy = dr->y; int dw = dr->w; int dh = dr->h; int cx = clip->x; int cy = clip->y; int cw = clip->w; int ch = clip->h; #ifdef DEBUG_CLIP printf(">>> "); if (sr != NULL) printf("sr: %3d %3d %3d %3d ", sr->x, sr->y, sr->w, sr->h); printf("dr: %3d %3d %3d %3d ", dr->x, dr->y, dr->w, dr->h); printf("clip: %3d %3d %3d %3d\n", clip->x, clip->y, clip->w, clip->h); #endif int adj = cx - dx; if (adj > 0) { if (adj > dw) return 0; dx += adj; dw -= adj; if (sr != NULL) { sr->x += adj; sr->w -= adj; } #ifdef DEBUG_CLIP printf("X ADJ %d\n", adj); #endif } adj = cy - dy; if (adj > 0) { if (adj > dh) return 0; dy += adj; dh -= adj; if (sr != NULL) { sr->y += adj; sr->h -= adj; } #ifdef DEBUG_CLIP printf("Y ADJ %d\n", adj); #endif } adj = (dx + dw) - (cx + cw); if (adj > 0) { #ifdef DEBUG_CLIP printf("W ADJ %d\n", adj); #endif if (adj > dw) return 0; dw -= adj; if (sr != NULL) sr->w -= adj; } adj = (dy + dh) - (cy + ch); if (adj > 0) { #ifdef DEBUG_CLIP printf("H ADJ %d\n", adj); #endif if (adj > dh) return 0; dh -= adj; if (sr != NULL) sr->h -= adj; } #ifdef DEBUG_CLIP printf("<<< "); if (sr != NULL) printf("sr: %3d %3d %3d %3d ", sr->x, sr->y, sr->w, sr->h); printf("dr: %3d %3d %3d %3d ", dr->x, dr->y, dr->w, dr->h); printf("clip: %3d %3d %3d %3d\n", clip->x, clip->y, clip->w, clip->h); #endif dr->x = dx; dr->y = dy; dr->w = dw; dr->h = dh; return 1; } void GUI_TriggerUpdate() { SDL_Event e; e.type = SDL_USEREVENT; e.user.code = 0; SDL_PushEvent(&e); } #if defined(WIN32) && defined(BUILDING_SDLGUI_DLL) #define WIN32_LEAN_AND_MEAN #include <windows.h> #undef WIN32_LEAN_AND_MEAN extern "C" int WINAPI _cygwin_dll_entry(HANDLE h, DWORD reason, void *ptr) { switch (reason) { case DLL_PROCESS_ATTACH: break; case DLL_PROCESS_DETACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; } return 1; } #endif <file_sep>/include/app.h /** * \file app.h * \brief DreamShell applications * \date 2007-2014 * \author SWAT www.dc-swat.ru */ #ifndef _DS_APP_H #define _DS_APP_H #include <kos.h> #include "list.h" #include "gui.h" #include "mxml.h" #include "console.h" #include "lua.h" /** * App state flags */ #define APP_STATE_OPENED 0x00000001 #define APP_STATE_LOADED 0x00000002 #define APP_STATE_READY 0x00000004 #define APP_STATE_PROCESS 0x00000008 #define APP_STATE_SLEEP 0x00000020 #define APP_STATE_WAIT_UNLOAD 0x00000040 /** * App info structure */ typedef struct App { const char fn[NAME_MAX]; const char icon[NAME_MAX]; const char name[64]; const char ver[32]; const char ext[64]; const char *args; uint32 id; uint32 state; Item_list_t *resources; Item_list_t *elements; mxml_node_t *xml; kthread_t *thd; lua_State *lua; GUI_Widget *body; } App_t; /** * Initialize and shutdown application system */ int InitApps(); void ShutdownApps(); /** * Apps list utils */ Item_list_t *GetAppList(); App_t *GetAppById(int id); App_t *GetAppByFileName(const char *fn); App_t *GetAppByName(const char *name); App_t *GetAppByExtension(const char *ext); App_t *GetAppsByExtension(const char *ext, App_t **app_list, size_t count); /** * Get current opened application */ App_t *GetCurApp(); /** * Parse app XML file and add to list * * return NULL on error */ App_t *AddApp(const char *fn); /** * Remove app from list */ int RemoveApp(App_t *app); /** * Open app with arguments (if needed) * Application can be loaded and builded automatically * * return 0 on error and 1 on success */ int OpenApp(App_t *app, const char *args); /** * Close app and unload (if unload > 0) * * return 0 on error and 1 on success */ int CloseApp(App_t *app, int unload); /** * Loading and unloading app resources * * return 0 on error and 1 on success */ int LoadApp(App_t *app, int build); int UnLoadApp(App_t *app); /** * Building app body from XML tree * * return 0 on error and 1 on success */ int BuildAppBody(App_t *app); /** * Add and remove GUI widget to/from app body Panel widget * * return 0 on error and 1 on success */ int AddToAppBody(App_t *app, GUI_Widget *widget); int RemoveFromAppBody(App_t *app, GUI_Widget *widget); /** * Calling app exported function * * return 0 on error and 1 on success */ int CallAppExportFunc(App_t *app, const char *fstr); /** * Calling app onload, onunload, onopen and onclose events * * return 0 on error and 1 on success */ int CallAppBodyEvent(App_t *app, char *event); /** * Waiting for clear flag APP_STATE_PROCESS */ void WaitApp(App_t *app); /** * Setup APP_STATE_SLEEP flag manualy * * return 0 on error and 1 on success */ int SetAppSleep(App_t *app, int sleep); /** * Check extension supported * * return 0 is NOT and 1 on success */ int IsFileSupportedByApp(App_t *app, const char *filename); /* Utils */ char *FindXmlAttr(char *name, mxml_node_t *node, char *defValue); void UnLoadOldApps(); void UnloadAppResources(Item_list_t *lst); /* Resource helpers */ void *getAppElement(App_t *app, const char *name, ListItemType type); #define APP_GET_WIDGET(name) ((GUI_Widget *) getAppElement(self.app, name, LIST_ITEM_GUI_WIDGET)) #define APP_GET_SURFACE(name) ((GUI_Surface *) getAppElement(self.app, name, LIST_ITEM_GUI_SURFACE)) #define APP_GET_FONT(name) ((GUI_Font *) getAppElement(self.app, name, LIST_ITEM_GUI_FONT)) #endif <file_sep>/modules/aicaos/arm/interrupt.c #include <stdint.h> #include "interrupt.h" #include "../aica_registers.h" /* When F bit (resp. I bit) is set, FIQ (resp. IRQ) is disabled. */ #define F_BIT 0x40 #define I_BIT 0x80 void int_restore(uint32_t context) { __asm__ volatile("msr CPSR_c,%0" : : "r"(context)); } uint32_t int_disable(void) { register uint32_t cpsr; __asm__ volatile("mrs %0,CPSR" : "=r"(cpsr) :); int_restore(cpsr | I_BIT | F_BIT); return cpsr; } uint32_t int_enable(void) { register uint32_t cpsr; __asm__ volatile("mrs %0,CPSR" : "=r"(cpsr) :); int_restore(cpsr & ~(I_BIT | F_BIT)); return cpsr; } int int_enabled(void) { register uint32_t cpsr; __asm__ volatile("mrs %0,CPSR" : "=r"(cpsr) :); return !(cpsr & (I_BIT | F_BIT)); } void int_acknowledge(void) { *(unsigned int *) REG_ARM_INT_RESET = MAGIC_CODE; *(unsigned int *) REG_ARM_FIQ_ACK = 1; } /* Called from crt0.S */ void __attribute__((interrupt ("FIQ"))) bus_fiq_hdl(void) { while(0x100 & *(volatile unsigned int *) REG_BUS_REQUEST); } /* Called from crt0.S */ void __attribute__((interrupt ("FIQ"))) timer_fiq_hdl(void) { } <file_sep>/firmware/isoldr/loader/include/main.h /** * DreamShell ISO Loader * (c)2009-2023 SWAT <http://www.dc-swat.ru> */ #ifndef _ISO_LOADER_H #define _ISO_LOADER_H #if defined(LOG) && (defined(DEV_TYPE_IDE) || defined(DEV_TYPE_GD)) #include <dc/scif.h> #endif #include <dc/video.h> #include <dc/biosfont.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <isoldr.h> #include "fs.h" #include "syscalls.h" #include "reader.h" #include "cdda.h" #include "malloc.h" #define APP_ADDR 0x8c010000 #define IPBIN_ADDR 0x8c008000 #define GDC_SYS_ADDR 0x8c001000 #define RAM_START_ADDR 0x8c000000 #define RAM_END_ADDR 0x8d000000 #define PHYS_ADDR(addr) ((addr) & 0x0fffffff) #define CACHED_ADDR(addr) (PHYS_ADDR(addr) | 0x80000000) #define NONCACHED_ADDR(addr) (PHYS_ADDR(addr) | 0xa0000000) #define ALIGN32_ADDR(addr) (((addr) + 0x1f) & ~0x1f) #define SYD_DDS_FLAG_ADDR NONCACHED_ADDR(IPBIN_ADDR + 0xfc)) #define SYD_DDS_FLAG_CLEAR 0x20 #define is_custom_bios() (*(uint16 *)0x00100018 != 0x4e46) #define is_no_syscalls() (*(uint16 *)(RAM_START_ADDR + 0x100) != 0x2f06) extern isoldr_info_t *IsoInfo; extern uint32 loader_size; extern uint32 loader_addr; extern uint32 loader_end; extern void boot_stub(void *, uint32) __attribute__((noreturn)); void setup_machine(void); void shutdown_machine(void); #define launch(addr) \ void (*fboot)(uint32) __attribute__((noreturn)); \ fboot = (void *)(NONCACHED_ADDR((uint32)&boot_stub)); \ fboot(addr) void video_init(); void video_screenshot(); void draw_gdtex(uint8 *src); void set_file_number(char *filename, int num); char *relative_filename(char *filename); void descramble(uint8 *source, uint8 *dest, uint32 size); void *search_memory(const uint8 *key, uint32 key_size); int patch_memory(const uint32 key, const uint32 val); void apply_patch_list(); #ifndef printf int printf(const char *fmt, ...); #endif uint Load_BootBin(); uint Load_IPBin(); int Load_DS(); void Load_Syscalls(); #ifdef LOG int OpenLog(); int WriteLog(const char *fmt, ...); int WriteLogFunc(const char *func, const char *fmt, ...); void CloseLog(); # define LOGF(...) WriteLog(__VA_ARGS__) # define LOGFF(...) WriteLogFunc(__func__, __VA_ARGS__) # ifdef DEBUG # define LOG_DEBUG = 1 # define DBGF(...) WriteLog(__VA_ARGS__) # define DBGFF(...) WriteLogFunc(__func__, __VA_ARGS__) # else # define DBGF(...) # define DBGFF(...) # endif #else # define OpenLog() # define CloseLog() # define LOGF(...) # define LOGFF(...) # define DBGF(...) # define DBGFF(...) #endif #endif /* _ISO_LOADER */ <file_sep>/lib/SDL_image/IMG_pvr.c /* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2012 <NAME> <<EMAIL>> Copyright (C) 2013-2014 SWAT <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <stdlib.h> #include <string.h> #include <strings.h> #include <stdbool.h> #include <stdio.h> #include <math.h> #include "SDL_endian.h" #include "SDL_image.h" #include "SegaPVRImage.h" #if defined(__DREAMCAST__) #include <malloc.h> #endif #if defined(HAVE_STDIO_H) && !defined(__DREAMCAST__) int fileno(FILE *f); #endif #ifdef LOAD_PVR unsigned long int GetUntwiddledTexelPosition(unsigned long int x, unsigned long int y); int MipMapsCountFromWidth(unsigned long int width); // RGBA Utils void TexelToRGBA( unsigned short int srcTexel, enum TextureFormatMasks srcFormat, unsigned char *r, unsigned char *g, unsigned char *b, unsigned char *a); unsigned int ToUint16(unsigned char* value) { return (value[0] | (value[1] << 8)); } // Twiddle static const unsigned int kTwiddleTableSize = 1024; unsigned long int gTwiddledTable[1024]; static bool bTwiddleTable = false; /* See if an image is contained in a data source */ int IMG_isPVR(SDL_RWops *src) { int start; int is_PVR = 0; char magic[4]; if ( !src ) return 0; start = SDL_RWtell(src); if ( SDL_RWread(src, magic, 1, sizeof(magic)) == sizeof(magic) ) { if (!strncasecmp(magic, "GBIX", 4) || !strncasecmp(magic, "PVRT", 4)) { is_PVR = 1; } } SDL_RWseek(src, start, RW_SEEK_SET); #ifdef DEBUG_IMGLIB fprintf(stderr, "IMG_isPVR: %d (%c%c%c%c)\n", is_PVR, magic[0], magic[1], magic[2], magic[3]); #endif return(is_PVR); } /* Load a PVR type image from an SDL datasource */ SDL_Surface *IMG_LoadPVR_RW(SDL_RWops *src) { int start = 0, len = 0; Uint32 Rmask; Uint32 Gmask; Uint32 Bmask; Uint32 Amask; SDL_Surface *surface = NULL; char *error = NULL; uint8 *data; if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); SDL_RWseek(src, 0, RW_SEEK_END); len = SDL_RWtell(src); SDL_RWseek(src, 0, RW_SEEK_SET); #ifdef DEBUG_IMGLIB fprintf(stderr, "IMG_LoadPVR_RW: %d bytes\n", len); #endif data = (uint8*) memalign(32, len); if(data == NULL) { error = "no free memory"; goto done; } #if defined(HAVE_STDIO_H) && !defined(__DREAMCAST__) int fd = fileno(src->hidden.stdio.fp); if(fd > -1) { if(read(fd, data, len) < 0) { error = "file truncated"; goto done; } } else { if (!SDL_RWread(src, data, len, 1)) { error = "file truncated"; goto done; } } #else if (!SDL_RWread(src, data, len, 1)) { error = "file truncated"; goto done; } #endif struct PVRTHeader pvrtHeader; unsigned int offset = ReadPVRHeader(data, &pvrtHeader); if (offset == 0) { error = "bad PVR header"; goto done; } enum TextureFormatMasks srcFormat = (enum TextureFormatMasks)(pvrtHeader.textureAttributes & 0xFF); if(srcFormat != TFM_ARGB1555 && srcFormat != TFM_RGB565 && srcFormat != TFM_ARGB4444) { error = "unsupported format"; goto done; } /* Create the surface of the appropriate type */ Rmask = Gmask = Bmask = Amask = 0; if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { Rmask = 0x000000FF; Gmask = 0x0000FF00; Bmask = 0x00FF0000; if(srcFormat != TFM_RGB565) Amask = 0xFF000000; } else { int so = srcFormat != TFM_RGB565 ? 0 : 8; Rmask = 0xFF000000 >> so; Gmask = 0x00FF0000 >> so; Bmask = 0x0000FF00 >> so; Amask = 0x000000FF >> so; } surface = SDL_AllocSurface(SDL_SWSURFACE, pvrtHeader.width, pvrtHeader.height, 32, Rmask, Gmask, Bmask, Amask); if ( surface == NULL ) { error = "can't allocate surface"; goto done; } if(bTwiddleTable == false) { BuildTwiddleTable(); bTwiddleTable = true; } memset_sh4(surface->pixels, 0, pvrtHeader.width * pvrtHeader.height * 4); if(!DecodePVR(data + offset, &pvrtHeader, surface->pixels)) { error = "can't decode image"; goto done; } done: if ( error ) { SDL_RWseek(src, start, RW_SEEK_SET); if ( surface ) { SDL_FreeSurface(surface); surface = NULL; } IMG_SetError(error); } if(data) { free(data); } return(surface); } unsigned int ReadPVRHeader(unsigned char* srcData, struct PVRTHeader* pvrtHeader) { unsigned int offset = 0; struct GBIXHeader gbixHeader = {0}; if (strncmp((char*)srcData, "GBIX", 4) == 0) { memcpy(&gbixHeader, srcData, 8); offset += 8; memcpy(&gbixHeader.globalIndex, srcData + offset, gbixHeader.nextTagOffset); offset += gbixHeader.nextTagOffset; } memcpy(pvrtHeader, srcData + offset, sizeof(struct PVRTHeader)); offset += sizeof(struct PVRTHeader); return offset; } int DecodePVR(unsigned char* srcData, const struct PVRTHeader* pvrtHeader, unsigned char* dstData) { const unsigned int kSrcStride = sizeof(unsigned short int); const unsigned int kDstStride = sizeof(unsigned int); // RGBA8888 enum TextureFormatMasks srcFormat = (enum TextureFormatMasks)(pvrtHeader->textureAttributes & 0xFF); // Unpack data bool isTwiddled = false; bool isMipMaps = false; bool isVQCompressed = false; unsigned int codeBookSize = 0; switch((pvrtHeader->textureAttributes >> 8) & 0xFF) { case TTM_TwiddledMipMaps: isMipMaps = true; case TTM_Twiddled: case TTM_TwiddledNonSquare: isTwiddled = true; break; case TTM_VectorQuantizedMipMaps: isMipMaps = true; case TTM_VectorQuantized: isVQCompressed = true; codeBookSize = 256; break; case TTM_VectorQuantizedCustomCodeBookMipMaps: isMipMaps = true; case TTM_VectorQuantizedCustomCodeBook: isVQCompressed = true; codeBookSize = pvrtHeader->width; if(codeBookSize < 16) { codeBookSize = 16; } else if(codeBookSize == 64) { codeBookSize = 128; } else { codeBookSize = 256; } break; case TTM_Raw: case TTM_RawNonSquare: break; default: return 0; break; } const unsigned int numCodedComponents = 4; unsigned char* srcVQ = 0; if (isVQCompressed) { srcVQ = srcData; srcData += numCodedComponents * kSrcStride * codeBookSize; } unsigned int mipWidth = 0; unsigned int mipHeight = 0; unsigned int mipSize = 0; // skip mipmaps int mipMapCount = (isMipMaps) ? MipMapsCountFromWidth(pvrtHeader->width) : 1; while (mipMapCount) { mipWidth = (pvrtHeader->width >> (mipMapCount - 1)); mipHeight = (pvrtHeader->height >> (mipMapCount - 1)); mipSize = mipWidth * mipHeight; if (--mipMapCount > 0) { if (isVQCompressed) { srcData += mipSize / 4; } else { srcData += kSrcStride * mipSize; } } else if (isMipMaps) { srcData += (isVQCompressed) ? 1 : kSrcStride; // skip 1x1 mip } } // Compressed textures processes only half-size if (isVQCompressed) { mipWidth /= 2; mipHeight /= 2; mipSize = mipWidth * mipHeight; } //extract image data unsigned long int x = 0; unsigned long int y = 0; int proccessed = 0; while(proccessed < mipSize) { unsigned long int srcPos = 0; unsigned long int dstPos = 0; unsigned short int srcTexel = 0; if (isVQCompressed) { unsigned long int vqIndex = srcData[GetUntwiddledTexelPosition(x, y)] * numCodedComponents; // Index of codebook * numbers of 2x2 block components // Bypass elements in 2x2 block for (unsigned int yoffset = 0; yoffset < 2; ++yoffset) { for (unsigned int xoffset = 0; xoffset < 2; ++xoffset) { srcPos = (vqIndex + (xoffset * 2 + yoffset)) * kSrcStride; srcTexel = ToUint16(&srcVQ[srcPos]); dstPos = ((y * 2 + yoffset) * 2 * mipWidth + (x * 2 + xoffset)) * kDstStride; TexelToRGBA(srcTexel, srcFormat, &dstData[dstPos], &dstData[dstPos + 1], &dstData[dstPos + 2], &dstData[dstPos + 3]); } } if (++x >= mipWidth) { x = 0; ++y; } } else { x = proccessed % mipWidth; y = proccessed / mipWidth; srcPos = ((isTwiddled) ? GetUntwiddledTexelPosition(x, y) : proccessed) * kSrcStride; srcTexel = ToUint16(&srcData[srcPos]); dstPos = proccessed * kDstStride; TexelToRGBA(srcTexel, srcFormat, &dstData[dstPos], &dstData[dstPos + 1], &dstData[dstPos + 2], &dstData[dstPos + 3]); } ++proccessed; } return 1; } int MipMapsCountFromWidth(unsigned long int width) { unsigned int mipMapsCount = 0; while( width ) { ++mipMapsCount; width /= 2; } return mipMapsCount; } // Twiddle unsigned long int UntwiddleValue(unsigned long int value) { unsigned long int untwiddled = 0; for (size_t i = 0; i < 10; i++) { unsigned long int shift = pow(2, i); if (value & shift) untwiddled |= (shift << i); } return untwiddled; } void BuildTwiddleTable() { for( unsigned long int i = 0; i < kTwiddleTableSize; i++ ) { gTwiddledTable[i] = UntwiddleValue( i ); } } unsigned long int GetUntwiddledTexelPosition(unsigned long int x, unsigned long int y) { unsigned long int pos = 0; if(x >= kTwiddleTableSize || y >= kTwiddleTableSize) { pos = UntwiddleValue(y) | UntwiddleValue(x) << 1; } else { pos = gTwiddledTable[y] | gTwiddledTable[x] << 1; } return pos; } void TexelToRGBA(unsigned short int srcTexel, enum TextureFormatMasks srcFormat, unsigned char *r, unsigned char *g, unsigned char *b, unsigned char *a) { switch( srcFormat ) { case TFM_RGB565: *a = 0xFF; *r = (srcTexel & 0xF800) >> 8; *g = (srcTexel & 0x07E0) >> 3; *b = (srcTexel & 0x001F) << 3; break; case TFM_ARGB1555: *a = (srcTexel & 0x8000) ? 0xFF : 0x00; *r = (srcTexel & 0x7C00) >> 7; *g = (srcTexel & 0x03E0) >> 2; *b = (srcTexel & 0x001F) << 3; break; case TFM_ARGB4444: *a = (srcTexel & 0xF000) >> 8; *r = (srcTexel & 0x0F00) >> 4; *g = (srcTexel & 0x00F0); *b = (srcTexel & 0x000F) << 4; break; case TFM_YUV422: // wip *a = 0xFF; *r = 0xFF; *g = 0xFF; *b = 0xFF; break; } } #else /* See if an image is contained in a data source */ int IMG_isPVR(SDL_RWops *src) { return(0); } /* Load a PCX type image from an SDL datasource */ SDL_Surface *IMG_LoadPVR_RW(SDL_RWops *src) { return(NULL); } #endif /* LOAD_PVR */ <file_sep>/firmware/bios/Makefile # # Bios ROM for DreamShell # Copyright (C) 2009-2014 SWAT # http://www.dc-swat.ru # SUBDIRS = bootstrap include ../../sdk/Makefile.cfg FW_NAME = bios FW_BOOTSTRAP = ./bootstrap/boot.bin FW_DIR = $(DS_BUILD)/firmware/$(FW_NAME)/ds RD_DIR = $(FW_DIR)/romdisks FW_FILES = ds_core.bios ds_core_rd.bios \ boot_loader.bios boot_loader_rd_ext.bios DEPS = $(FW_BOOTSTRAP) $(DS_BUILD)/DS_CORE.BIN \ $(DS_BASE)/firmware/bootloader/loader.bin \ initrd.img initrd_ext.img initrd_core.img all: fw install $(FW_BOOTSTRAP): cd bootstrap && make fw: $(FW_FILES) $(FW_FILES): $(DEPS) -rm -f $(FW_FILES) cat $(FW_BOOTSTRAP) $(DS_BUILD)/DS_CORE.BIN > ds_core.bios cat $(FW_BOOTSTRAP) $(DS_BUILD)/DS_CORE.BIN initrd.img > ds_core_rd.bios cat $(FW_BOOTSTRAP) ../bootloader/loader.bin > boot_loader.bios cat $(FW_BOOTSTRAP) ../bootloader/loader.bin initrd_ext.img > boot_loader_rd_ext.bios cat $(FW_BOOTSTRAP) ../bootloader/loader.bin initrd_core.img > boot_loader_rd_core.bios initrd: initrd.img initrd_ext.img initrd_core.img initrd.img: ./initrd/* ./initrd_ext/* $(KOS_GENROMFS) -f initrd.img -d initrd -V DreamShell -v -x .svn $(KOS_GENROMFS) -f initrd_ext.img -d initrd_ext -V DreamShell -v -x .svn cp $(DS_BUILD)/DS_CORE.BIN ./initrd/DS_CORE.BIN gzip -9 ./initrd/DS_CORE.BIN mv ./initrd/DS_CORE.BIN.gz ./initrd/ZDS_CORE.BIN $(KOS_GENROMFS) -f initrd_core.img -d initrd -V DreamShell -v -x .svn rm -f ./initrd/ZDS_CORE.BIN install: fw rm-old cp ds_core.bios $(FW_DIR)/ds_core.bios cp ds_core_rd.bios $(FW_DIR)/ds_core_rd.bios cp boot_loader.bios $(FW_DIR)/boot_loader.bios cp boot_loader_rd_ext.bios $(FW_DIR)/boot_loader_rd_ext.bios cp boot_loader_rd_core.bios $(FW_DIR)/boot_loader_rd_core.bios cp initrd.img $(RD_DIR)/initrd.img cp initrd_ext.img $(RD_DIR)/initrd_ext.img cp initrd_core.img $(RD_DIR)/initrd_core.img rm-old: @-mkdir -p $(FW_DIR) -rm -f $(FW_DIR)/ds_core.bios -rm -f $(FW_DIR)/ds_core_rd.bios -rm -f $(FW_DIR)/boot_loader.bios -rm -f $(FW_DIR)/boot_loader_rd_ext.bios -rm -f $(FW_DIR)/boot_loader_rd_core.bios -rm -f $(RD_DIR)/initrd.img -rm -f $(RD_DIR)/initrd_ext.img -rm -f $(RD_DIR)/initrd_core.img clean: -rm -f $(FW_FILES) -rm -f initrd.img initrd_ext.img initrd_core.img <file_sep>/modules/gumbo/gumbo/setup.py #!/usr/bin/env python from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup(name='gumbo', version='0.9.0', description='Python bindings for Gumbo HTML parser', long_description=readme(), url='http://github.com/google/gumbo-parser', keywords='gumbo html html5 parser google html5lib beautifulsoup', author='<NAME>', author_email='<EMAIL>', license='Apache 2.0', packages=['gumbo'], package_dir={'': 'python'}, zip_safe=True) <file_sep>/firmware/isoldr/loader/kos/src/timer.c /* KallistiOS ##version## timer.c Copyright (C)2000, 2001, 2002,2004 <NAME> Copyright (C)2014-2023 SWAT Copyright (C)2023 <NAME> */ //#include <stdio.h> #include <arch/timer.h> #include <arch/irq.h> /* Quick access macros */ #define TIMER8(o) ( *((volatile uint8*)(0xffd80000 + (o))) ) #define TIMER16(o) ( *((volatile uint16*)(0xffd80000 + (o))) ) #define TIMER32(o) ( *((volatile uint32*)(0xffd80000 + (o))) ) #define TOCR 0x00 #define TSTR 0x04 #define TCOR0 0x08 #define TCNT0 0x0c #define TCR0 0x10 #define TCOR1 0x14 #define TCNT1 0x18 #define TCR1 0x1c #define TCOR2 0x20 #define TCNT2 0x24 #define TCR2 0x28 #define TCPR2 0x2c static int tcors[] = { TCOR0, TCOR1, TCOR2 }; static int tcnts[] = { TCNT0, TCNT1, TCNT2 }; static int tcrs[] = { TCR0, TCR1, TCR2 }; /* Pre-initialize a timer; set values but don't start it */ int timer_prime(int which, uint32 speed, int interrupts) { /* P0/64 scalar, maybe interrupts */ if (interrupts) { TIMER16(tcrs[which]) = 32 | 2; } else { TIMER16(tcrs[which]) = 2; } /* Initialize counters; formula is P0/(tps*64) */ TIMER32(tcnts[which]) = 50000000 / (speed*64); TIMER32(tcors[which]) = 50000000 / (speed*64); if(interrupts) { timer_enable_ints(which); } return 0; } /* Pre-initialize a timer for CDDA; set values but don't start it */ int timer_prime_cdda(int which, uint32 count, int interrupts) { /* Stop timer */ TIMER8(TSTR) &= ~(1 << which); /* External clock, maybe interrupts */ if (interrupts) { TIMER16(tcrs[which]) = 32 | 3; } else { TIMER16(tcrs[which]) = 3; } /* Initialize counters */ TIMER32(tcnts[which]) = count; TIMER32(tcors[which]) = count; /* Clears the timer underflow bit */ TIMER16(tcrs[which]) &= ~0x100; if(interrupts) { timer_enable_ints(which); } return 0; } /* Pre-initialize a timer as do it the BIOS; set values but don't start it */ int timer_prime_bios(int which) { /* Stop timer */ TIMER8(TSTR) &= ~(1 << which); TIMER16(tcrs[which]) = 2; TIMER32(tcnts[which]) = 0xFFFFFFFF; TIMER32(tcors[which]) = 0xFFFFFFFF; /* Clears the timer underflow bit */ TIMER16(tcrs[which]) &= ~0x100; return 0; } /* Start a timer -- starts it running (and interrupts if applicable) */ int timer_start(int which) { TIMER8(TSTR) |= 1 << which; return 0; } /* Stop a timer -- and disables its interrupt */ int timer_stop(int which) { /* Stop timer */ TIMER8(TSTR) &= ~(1 << which); return 0; } /* Clears the timer underflow bit and returns what its value was */ int timer_clear(int which) { uint16 value = TIMER16(tcrs[which]); TIMER16(tcrs[which]) &= ~0x100; return (value & 0x100) ? 1 : 0; } /* Returns the count value of a timer */ uint32 timer_count(int which) { return TIMER32(tcnts[which]); } /* Spin-loop kernel sleep func: uses the secondary timer in the SH-4 to very accurately delay even when interrupts are disabled */ void timer_spin_sleep(int ms) { timer_stop(TMU1); timer_prime(TMU1, 1000, 0); timer_clear(TMU1); timer_start(TMU1); while (ms > 0) { while (!(TIMER16(tcrs[TMU1]) & 0x100)) ; timer_clear(TMU1); ms--; } timer_stop(TMU1); } void timer_spin_sleep_bios(int ms) { uint32 before, cur, cnt = 782 * ms; before = timer_count(TMU0); do { cur = before - timer_count(TMU0); } while(cur < cnt); } /* Enable timer interrupts (high priority); needs to move to irq.c sometime. */ void timer_enable_ints(int which) { volatile uint16 *ipra = (uint16*)0xffd00004; *ipra |= (0x000f << (12 - 4 * which)); } /* Disable timer interrupts; needs to move to irq.c sometime. */ void timer_disable_ints(int which) { volatile uint16 *ipra = (uint16*)0xffd00004; *ipra &= ~(0x000f << (12 - 4 * which)); } /* Check whether ints are enabled */ int timer_ints_enabled(int which) { volatile uint16 *ipra = (uint16*)0xffd00004; return (*ipra & (0x000f << (12 - 4 * which))) != 0; } /* Init */ int timer_init() { /* Disable all timers */ TIMER8(TSTR) = 0; /* Set to internal clock source */ TIMER8(TOCR) = 0; return 0; } /* Shutdown */ void timer_shutdown() { /* Disable all timers */ TIMER8(TSTR) = 0; timer_disable_ints(TMU0); timer_disable_ints(TMU1); timer_disable_ints(TMU2); } /* Quick access macros */ #define PMCR_CTRL(o) ( *((volatile uint16*)(0xff000084) + (o << 1)) ) #define PMCTR_HIGH(o) ( *((volatile uint32*)(0xff100004) + (o << 1)) ) #define PMCTR_LOW(o) ( *((volatile uint32*)(0xff100008) + (o << 1)) ) #define PMCR_CLR 0x2000 #define PMCR_PMST 0x4000 #define PMCR_PMENABLE 0x8000 #define PMCR_RUN 0xc000 #define PMCR_PMM_MASK 0x003f #define PMCR_CLOCK_TYPE_SHIFT 8 /* 5ns per count in 1 cycle = 1 count mode(PMCR_COUNT_CPU_CYCLES) */ #define NS_PER_CYCLE 5 /* Get a counter's current configuration */ uint16 perf_cntr_get_config(int which) { return PMCR_CTRL(which); } /* Start a performance counter */ int perf_cntr_start(int which, int mode, int count_type) { perf_cntr_clear(which); PMCR_CTRL(which) = PMCR_RUN | mode | (count_type << PMCR_CLOCK_TYPE_SHIFT); return 0; } /* Stop a performance counter */ int perf_cntr_stop(int which) { PMCR_CTRL(which) &= ~(PMCR_PMM_MASK | PMCR_PMENABLE); return 0; } /* Clears a performance counter. Has to stop it first. */ int perf_cntr_clear(int which) { perf_cntr_stop(which); PMCR_CTRL(which) |= PMCR_CLR; return 0; } /* Returns the count value of a counter */ inline uint64 perf_cntr_count(int which) { return (uint64)(PMCTR_HIGH(which) & 0xffff) << 32 | PMCTR_LOW(which); } void timer_ns_enable() { perf_cntr_start(PRFC0, PMCR_ELAPSED_TIME_MODE, PMCR_COUNT_CPU_CYCLES); } void timer_ns_disable() { uint16 config = PMCR_CTRL(PRFC0); /* If timer is running, disable it */ if((config & PMCR_ELAPSED_TIME_MODE)) { perf_cntr_clear(PRFC0); } } inline uint64 timer_ns_gettime64() { uint64 cycles = perf_cntr_count(PRFC0); return cycles * NS_PER_CYCLE; } <file_sep>/lib/SDL_gui/Exception.cc #include <assert.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include "SDL_gui.h" extern "C" { int ds_printf(const char *fmt, ...); } GUI_Exception::GUI_Exception(const char *fmt, ...) { va_list marker; char temp[4096]; va_start(marker, fmt); vsprintf(temp, fmt, marker); va_end(marker); message = strdup(temp); ds_printf("DS_ERROR: %s\n", message); } GUI_Exception::GUI_Exception(const GUI_Exception &err) { message = strdup(err.message); } GUI_Exception::~GUI_Exception(void) { free(message); } const char *GUI_Exception::GetMessage(void) { return message; } <file_sep>/firmware/isoldr/syscalls/include/string.h /* KallistiOS ##version## string.h (c)2000 <NAME> $Id: string.h,v 1.3 2002/07/27 00:52:08 bardtx Exp $ */ #ifndef __STRING_H #define __STRING_H #include <sys/cdefs.h> __BEGIN_DECLS #include <arch/types.h> void bcopy(const void * src, void * dest, size_t count); void bzero(void *s, size_t n); char * index(const char *p, int ch); void * memchr(const void *s, uint8 c, size_t n); int memcmp(const void * cs,const void * ct,size_t count); void * memcpy(void *p1, const void *p2, size_t count); void * memmove(void *p1, const void *p2, size_t count); void * memset(void *p1, uint32 val, size_t count); void * memscan(void * addr, int c, size_t size); char * rindex(const char *p, int ch); char * strcat(char * dest, const char * src); char * strchr(const char * s, int c); int strcmp(const char * cs,const char * ct); int strcoll(const char *s1, const char *s2); char * strcpy(char * dest,const char *src); size_t strcspn(const char *s1, const char *s2); char * strdup(const char * src); char * strerror(int errnum); int stricmp(const char *cs, const char *ct); size_t strlen(const char * s); size_t strnlen(const char *s, size_t maxlen); char * strncat(char *dest, const char *src, size_t count); char * strncpy(char * dest,const char *src, size_t count); int strnicmp(const char *cs, const char *ct, int cnt); int strncmp(const char * cs,const char * ct,size_t count); size_t strnlen(const char * s, size_t count); char * strpbrk(const char * cs,const char * ct); char * strrchr(const char * s, int c); char * strsep(char **stringp, const char *delim); size_t strspn(const char *s, const char *accept); char * strstr(const char * s1,const char * s2); char * strtok(char * s,const char * ct); size_t strxfrm(char *s1, const char *s2, size_t n); long strtol(const char * nptr, char ** endptr, int base); char * _strupr(char * string); void memcpy4(uint32 *p1, const uint32 *p2, uint32 count); void memset4(uint32 *p1, uint32 val, uint32 count); void memcpy2(uint16 *p1, const uint16 *p2, uint32 count); void memset2(uint16 *p1, uint32 val, uint32 count); int strncasecmp(const char *s1, const char *s2, int n); int strcasecmp(const char *s1, const char *s2); int check_digit (char c); int hex_to_int(char c); __END_DECLS #endif /* __STRING_H */ <file_sep>/firmware/isoldr/loader/fs/dcl/fs.c /* * DreamShell ISO Loader * dcload file system * (c)2009-2022 SWAT <http://www.dc-swat.ru> */ #include <main.h> #include <arch/irq.h> #include "dcload.h" #ifdef HAVE_IRQ #define dclsc(...) ({ \ int rv, old; \ if (!exception_inside_int()) { \ old = irq_disable(); \ } \ do {} while ((*(vuint32 *)0xa05f688c) & 0x20); \ rv = dcloadsyscall(__VA_ARGS__); \ if (!exception_inside_int()) \ irq_restore(old); \ rv; \ }) #else #define dclsc(...) ({ \ int rv, old; \ old = irq_disable(); \ do {} while ((*(vuint32 *)0xa05f688c) & 0x20); \ rv = dcloadsyscall(__VA_ARGS__); \ irq_restore(old); \ rv; \ }) #endif static int dma_mode = 0; int fs_init() { return dcload_init(); } void fs_enable_dma(int state) { dma_mode = state; } int fs_dma_enabled() { return dma_mode; } int open(const char *path, int mode) { uint32 dcload_mode = 0; int fd = -1; if((mode & O_MODE_MASK) == O_RDONLY) dcload_mode = 0; if((mode & O_MODE_MASK) == O_RDWR) dcload_mode = 2 | 0x0200; if((mode & O_MODE_MASK) == O_WRONLY) dcload_mode = 1 | 0x0200; if((mode & O_MODE_MASK) == O_APPEND) dcload_mode = 2 | 8 | 0x0200; if(mode & O_TRUNC) dcload_mode |= 0x0400; fd = dclsc(DCLOAD_OPEN, path, dcload_mode, 0644); if(fd < 0) { return FS_ERR_NOFILE; } return fd; } int close(int fd) { if(dclsc(fd > 100 ? DCLOAD_CLOSEDIR : DCLOAD_CLOSE, fd) < 0) { return FS_ERR_PARAM; } return 0; } int read(int fd, void *ptr, size_t size) { return dclsc(DCLOAD_READ, fd, ptr, size); } int pre_read(int fd, unsigned int size) { (void)fd; (void)size; return 0; } #if !_FS_READONLY int write(int fd, void *ptr, size_t size) { return dclsc(DCLOAD_WRITE, fd, ptr, size); } #endif long int lseek(int fd, long int offset, int whence) { return dclsc(DCLOAD_LSEEK, fd, (int)offset, whence); } long int tell(int fd) { return dclsc(DCLOAD_LSEEK, fd, 0, SEEK_CUR); } unsigned long total(int fd) { long cur = dclsc(DCLOAD_LSEEK, fd, 0, SEEK_CUR); long ret = dclsc(DCLOAD_LSEEK, fd, 0, SEEK_END); dclsc(DCLOAD_LSEEK, fd, cur, SEEK_SET); return (unsigned long)ret; } int ioctl(int fd, int cmd, void *data) { (void)fd; switch(cmd) { case FS_IOCTL_GET_LBA: { unsigned long sec = 0; memcpy(data, &sec, sizeof(sec)); return 0; } default: return FS_ERR_PARAM; } } <file_sep>/include/profiler.h /* DreamShell ##version## profiler.h Copyright (C) 2020 <NAME> Copyright (C) 2023 <NAME> */ /** \file src/profiler.h \brief gprof compatible sampling profiler. The Dreamcast doesn't have any kind of profiling support from GCC so this is a cumbersome sampling profiler that runs in a background thread. Once profiling has begun, the background thread will regularly gather the PC and PR registers stored by the other threads. The way thread scheduling works is that when other threads are blocked their current program counter is stored in a context. If the profiler thread is doing work then all the other threads aren't and so the stored program counters will be up-to-date. The profiling thread gathers PC/PR pairs and how often that pairing appears. */ #pragma once #ifdef __cplusplus extern "C" { #endif void profiler_init(const char* output); void profiler_start(); void profiler_stop(); void profiler_clean_up(); #ifdef __cplusplus } #endif <file_sep>/firmware/bootloader/src/descramble.c /** * DreamShell boot loader * Descramble binary * (c)2011-2016 SWAT <http://www.dc-swat.ru> */ #include "main.h" #define MAXCHUNK 0x200000 static uint seed; static inline void my_srand(uint n) { seed = n & 0xffff; } static inline uint my_rand(void) { seed = (seed * 2109 + 9273) & 0x7fff; return (seed + 0xc000) & 0xffff; } static void load(uint8 *dest, uint32 size) { static uint8 *source; if (!size) { source = dest; return; } memcpy(dest, source, size); source += size; } static inline void handle_chunk(uint8 *ptr, int sz) { int idx[MAXCHUNK / 32]; int i; /* Convert chunk size to number of slices */ sz /= 32; /* Initialize index table with unity, so that each slice gets loaded exactly once */ for(i = 0; i < sz; i++) idx[i] = i; for(i = sz-1; i >= 0; --i) { /* Select a replacement index */ int x = (my_rand() * i) >> 16; /* Swap */ int tmp = idx[i]; idx[i] = idx[x]; idx[x] = tmp; /* Load resulting slice */ load(ptr + 32 * idx[i], 32); } } void descramble(uint8 *source, uint8 *dest, uint32 size) { load(source, 0); my_srand(size); /* Descramble 2 meg blocks for as long as possible, then gradually reduce the window down to 32 bytes (1 slice) */ for(uint32 chunksz = MAXCHUNK; chunksz >= 32; chunksz >>= 1) { while(size >= chunksz) { handle_chunk(dest, chunksz); size -= chunksz; dest += chunksz; } } /* !!! Load final incomplete slice */ if(size) load(dest, size); } <file_sep>/modules/mp3/libmp3/xingmp3/upsf.c /*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ____________________________________________________________________________*/ /**** upsf.c *************************************************** Layer III unpack scale factors ******************************************************************/ #include <float.h> #include <math.h> #include "L3.h" #include "mhead.h" unsigned int bitget(MPEG *m, int n); /*------------------------------------------------------------*/ static const int slen_table[16][2] = { {0, 0}, {0, 1}, {0, 2}, {0, 3}, {3, 0}, {1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}, {4, 2}, {4, 3}, }; /* nr_table[size+3*is_right][block type 0,1,3 2, 2+mixed][4] */ /* for bt=2 nr is count for group of 3 */ static const int nr_table[6][3][4] = { {{6, 5, 5, 5}, {3, 3, 3, 3}, {6, 3, 3, 3}}, {{6, 5, 7, 3}, {3, 3, 4, 2}, {6, 3, 4, 2}}, {{11, 10, 0, 0}, {6, 6, 0, 0}, {6, 3, 6, 0}}, /* adjusted *//* 15, 18, 0, 0, */ /*-intensity stereo right chan--*/ {{7, 7, 7, 0}, {4, 4, 4, 0}, {6, 5, 4, 0}}, {{6, 6, 6, 3}, {4, 3, 3, 2}, {6, 4, 3, 2}}, {{8, 8, 5, 0}, {5, 4, 3, 0}, {6, 6, 3, 0}}, }; /*=============================================================*/ void unpack_sf_sub_MPEG1(MPEG *m, SCALEFACT sf[], GR * grdat, int scfsi, /* bit flag */ int gr) { int sfb; int slen0, slen1; int block_type, mixed_block_flag, scalefac_compress; block_type = grdat->block_type; mixed_block_flag = grdat->mixed_block_flag; scalefac_compress = grdat->scalefac_compress; slen0 = slen_table[scalefac_compress][0]; slen1 = slen_table[scalefac_compress][1]; if (block_type == 2) { if (mixed_block_flag) { /* mixed */ for (sfb = 0; sfb < 8; sfb++) sf[0].l[sfb] = bitget(m, slen0); for (sfb = 3; sfb < 6; sfb++) { sf[0].s[0][sfb] = bitget(m, slen0); sf[0].s[1][sfb] = bitget(m, slen0); sf[0].s[2][sfb] = bitget(m, slen0); } for (sfb = 6; sfb < 12; sfb++) { sf[0].s[0][sfb] = bitget(m, slen1); sf[0].s[1][sfb] = bitget(m, slen1); sf[0].s[2][sfb] = bitget(m, slen1); } return; } for (sfb = 0; sfb < 6; sfb++) { sf[0].s[0][sfb] = bitget(m, slen0); sf[0].s[1][sfb] = bitget(m, slen0); sf[0].s[2][sfb] = bitget(m, slen0); } for (; sfb < 12; sfb++) { sf[0].s[0][sfb] = bitget(m, slen1); sf[0].s[1][sfb] = bitget(m, slen1); sf[0].s[2][sfb] = bitget(m, slen1); } return; } /* long blocks types 0 1 3, first granule */ if (gr == 0) { for (sfb = 0; sfb < 11; sfb++) sf[0].l[sfb] = bitget(m, slen0); for (; sfb < 21; sfb++) sf[0].l[sfb] = bitget(m, slen1); return; } /* long blocks 0, 1, 3, second granule */ sfb = 0; if (scfsi & 8) for (; sfb < 6; sfb++) sf[0].l[sfb] = sf[-2].l[sfb]; else for (; sfb < 6; sfb++) sf[0].l[sfb] = bitget(m, slen0); if (scfsi & 4) for (; sfb < 11; sfb++) sf[0].l[sfb] = sf[-2].l[sfb]; else for (; sfb < 11; sfb++) sf[0].l[sfb] = bitget(m, slen0); if (scfsi & 2) for (; sfb < 16; sfb++) sf[0].l[sfb] = sf[-2].l[sfb]; else for (; sfb < 16; sfb++) sf[0].l[sfb] = bitget(m, slen1); if (scfsi & 1) for (; sfb < 21; sfb++) sf[0].l[sfb] = sf[-2].l[sfb]; else for (; sfb < 21; sfb++) sf[0].l[sfb] = bitget(m, slen1); return; } /*=============================================================*/ void unpack_sf_sub_MPEG2(MPEG *m, SCALEFACT sf[], GR * grdat, int is_and_ch, IS_SF_INFO * sf_info) { int sfb; int slen1, slen2, slen3, slen4; int nr1, nr2, nr3, nr4; int i, k; int preflag, intensity_scale; int block_type, mixed_block_flag, scalefac_compress; block_type = grdat->block_type; mixed_block_flag = grdat->mixed_block_flag; scalefac_compress = grdat->scalefac_compress; preflag = 0; intensity_scale = 0; /* to avoid compiler warning */ if (is_and_ch == 0) { if (scalefac_compress < 400) { slen2 = scalefac_compress >> 4; slen1 = slen2 / 5; slen2 = slen2 % 5; slen4 = scalefac_compress & 15; slen3 = slen4 >> 2; slen4 = slen4 & 3; k = 0; } else if (scalefac_compress < 500) { scalefac_compress -= 400; slen2 = scalefac_compress >> 2; slen1 = slen2 / 5; slen2 = slen2 % 5; slen3 = scalefac_compress & 3; slen4 = 0; k = 1; } else { scalefac_compress -= 500; slen1 = scalefac_compress / 3; slen2 = scalefac_compress % 3; slen3 = slen4 = 0; if (mixed_block_flag) { slen3 = slen2; /* adjust for long/short mix logic */ slen2 = slen1; } preflag = 1; k = 2; } } else { /* intensity stereo ch = 1 (right) */ intensity_scale = scalefac_compress & 1; scalefac_compress >>= 1; if (scalefac_compress < 180) { slen1 = scalefac_compress / 36; slen2 = scalefac_compress % 36; slen3 = slen2 % 6; slen2 = slen2 / 6; slen4 = 0; k = 3 + 0; } else if (scalefac_compress < 244) { scalefac_compress -= 180; slen3 = scalefac_compress & 3; scalefac_compress >>= 2; slen2 = scalefac_compress & 3; slen1 = scalefac_compress >> 2; slen4 = 0; k = 3 + 1; } else { scalefac_compress -= 244; slen1 = scalefac_compress / 3; slen2 = scalefac_compress % 3; slen3 = slen4 = 0; k = 3 + 2; } } i = 0; if (block_type == 2) i = (mixed_block_flag & 1) + 1; nr1 = nr_table[k][i][0]; nr2 = nr_table[k][i][1]; nr3 = nr_table[k][i][2]; nr4 = nr_table[k][i][3]; /* return is scale factor info (for right chan is mode) */ if (is_and_ch) { sf_info->nr[0] = nr1; sf_info->nr[1] = nr2; sf_info->nr[2] = nr3; sf_info->slen[0] = slen1; sf_info->slen[1] = slen2; sf_info->slen[2] = slen3; sf_info->intensity_scale = intensity_scale; } grdat->preflag = preflag; /* return preflag */ /*--------------------------------------*/ if (block_type == 2) { if (mixed_block_flag) { /* mixed */ if (slen1 != 0) /* long block portion */ for (sfb = 0; sfb < 6; sfb++) sf[0].l[sfb] = bitget(m, slen1); else for (sfb = 0; sfb < 6; sfb++) sf[0].l[sfb] = 0; sfb = 3; /* start sfb for short */ } else { /* all short, initial short blocks */ sfb = 0; if (slen1 != 0) for (i = 0; i < nr1; i++, sfb++) { sf[0].s[0][sfb] = bitget(m, slen1); sf[0].s[1][sfb] = bitget(m, slen1); sf[0].s[2][sfb] = bitget(m, slen1); } else for (i = 0; i < nr1; i++, sfb++) { sf[0].s[0][sfb] = 0; sf[0].s[1][sfb] = 0; sf[0].s[2][sfb] = 0; } } /* remaining short blocks */ if (slen2 != 0) for (i = 0; i < nr2; i++, sfb++) { sf[0].s[0][sfb] = bitget(m, slen2); sf[0].s[1][sfb] = bitget(m, slen2); sf[0].s[2][sfb] = bitget(m, slen2); } else for (i = 0; i < nr2; i++, sfb++) { sf[0].s[0][sfb] = 0; sf[0].s[1][sfb] = 0; sf[0].s[2][sfb] = 0; } if (slen3 != 0) for (i = 0; i < nr3; i++, sfb++) { sf[0].s[0][sfb] = bitget(m, slen3); sf[0].s[1][sfb] = bitget(m, slen3); sf[0].s[2][sfb] = bitget(m, slen3); } else for (i = 0; i < nr3; i++, sfb++) { sf[0].s[0][sfb] = 0; sf[0].s[1][sfb] = 0; sf[0].s[2][sfb] = 0; } if (slen4 != 0) for (i = 0; i < nr4; i++, sfb++) { sf[0].s[0][sfb] = bitget(m, slen4); sf[0].s[1][sfb] = bitget(m, slen4); sf[0].s[2][sfb] = bitget(m, slen4); } else for (i = 0; i < nr4; i++, sfb++) { sf[0].s[0][sfb] = 0; sf[0].s[1][sfb] = 0; sf[0].s[2][sfb] = 0; } return; } /* long blocks types 0 1 3 */ sfb = 0; if (slen1 != 0) for (i = 0; i < nr1; i++, sfb++) sf[0].l[sfb] = bitget(m, slen1); else for (i = 0; i < nr1; i++, sfb++) sf[0].l[sfb] = 0; if (slen2 != 0) for (i = 0; i < nr2; i++, sfb++) sf[0].l[sfb] = bitget(m, slen2); else for (i = 0; i < nr2; i++, sfb++) sf[0].l[sfb] = 0; if (slen3 != 0) for (i = 0; i < nr3; i++, sfb++) sf[0].l[sfb] = bitget(m, slen3); else for (i = 0; i < nr3; i++, sfb++) sf[0].l[sfb] = 0; if (slen4 != 0) for (i = 0; i < nr4; i++, sfb++) sf[0].l[sfb] = bitget(m, slen4); else for (i = 0; i < nr4; i++, sfb++) sf[0].l[sfb] = 0; } /*-------------------------------------------------*/ <file_sep>/firmware/isoldr/loader/kos/src/sprintf.c /* ps2-load-ip sprintf.c Copyright (C)2002 <NAME> License: BSD $Id: sprintf.c,v 1.1 2002/10/30 05:34:13 bardtx Exp $ */ #include <stdio.h> #include <stdarg.h> int sprintf(char *out, const char *fmt, ...) { va_list args; int i; va_start(args, fmt); i = vsprintf(out, fmt, args); va_end(args); return i; } <file_sep>/modules/aicaos/arm/main.c #include <stdio.h> #include <stdint.h> #include "../aica_common.h" #include "task.h" AICA_ADD_REMOTE(sh4_puts, 0); static AICA_SHARED(arm_test) { static unsigned int nb = 0; printf("test %i\n", nb++); return 0; } AICA_SHARED_LIST = { AICA_SHARED_LIST_ELEMENT(arm_test, 0, 0), AICA_SHARED_LIST_END, }; int main(int argc, char **argv) { unsigned int nb = 0; sh4_puts(NULL, "world!"); while(1) { printf("Hello %i\n", nb++); task_reschedule(); } return 0; } <file_sep>/lib/freetype/Makefile # # FreeType 2 build system -- top-level Makefile # # Copyright 1996-2000, 2002, 2006 by # <NAME>, <NAME>, and <NAME>. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. # Project names # PROJECT := freetype PROJECT_TITLE := FreeType # The variable TOP_DIR holds the path to the topmost directory in the project # engine source hierarchy. If it is not defined, default it to `.'. # TOP_DIR ?= . # The variable OBJ_DIR gives the location where object files and the # FreeType library are built. # OBJ_DIR ?= $(TOP_DIR)/objs #all: # $(TARGET_LIB) include $(TOP_DIR)/builds/toplevel.mk TARGET_LIB = ../libfreetype_2.4.4.a #LIB_FILE = ./objs/.libs/libfreetype.a LIB_FILE = $(TARGET_LIB) #$(TARGET_LIB): $(LIB_FILE) # cp $(LIB_FILE) $(TARGET_LIB) # EOF <file_sep>/src/module.c /**************************** * DreamShell ##version## * * module.c * * DreamShell modules * * Created by SWAT * * http://www.dc-swat.ru * ***************************/ #include "ds.h" #ifdef DEBUG #define MODULE_DEBUG #endif extern export_sym_t ds_symtab[]; static symtab_handler_t st_ds = { { "sym/ds/kernel", 0, 0x00010000, 0, NMMGR_TYPE_SYMTAB, NMMGR_LIST_INIT }, ds_symtab }; extern export_sym_t gcc_symtab[]; static symtab_handler_t st_gcc = { { "sym/ds/gcc", 0, 0x00010000, 0, NMMGR_TYPE_SYMTAB, NMMGR_LIST_INIT }, gcc_symtab }; export_sym_t *export_lookup_by_addr(uint32 addr) { nmmgr_handler_t *nmmgr; nmmgr_list_t *nmmgrs; int i; symtab_handler_t *sth; uint dist = ~0; ptr_t a = addr; //(ptr_t) addr; export_sym_t *best = NULL; /* Get the name manager list */ nmmgrs = nmmgr_get_list(); /* Go through and look at each symtab entry */ LIST_FOREACH(nmmgr, nmmgrs, list_ent) { /* Not a symtab -> ignore */ if (nmmgr->type != NMMGR_TYPE_SYMTAB) continue; sth = (symtab_handler_t *)nmmgr; /* First look through the kernel table */ for (i = 0; sth->table[i].name; i++) { //if (sth->table[i].ptr == (ptr_t)addr) // return sth->table+i; if (a - sth->table[i].ptr < dist) { dist = a - sth->table[i].ptr; best = sth->table + i; } } } return best; } export_sym_t *export_lookup_ex(const char *name, const char *path) { nmmgr_handler_t *nmmgr; symtab_handler_t *sth; int i; nmmgr = nmmgr_lookup(path); if(nmmgr == NULL) { return NULL; } sth = (symtab_handler_t *)nmmgr; for(i = 0; sth->table[i].name; i++) { if(!strcmp(name, sth->table[i].name)) return sth->table + i; } return NULL; } klibrary_t *library_lookup_fn(const char * fn) { int old; klibrary_t *lib; old = irq_disable(); LIST_FOREACH(lib, &library_list, list) { if(!strncmp(lib->image.fn, fn, NAME_MAX)) break; } irq_restore(old); if(!lib) errno = ENOENT; return lib; } // Get exported symbol addr uint32 GetExportSymAddr(const char *name, const char *path) { export_sym_t *sym; if(path != NULL) { sym = export_lookup_ex(name, path); } else { sym = export_lookup(name); } return (sym != NULL ? sym->ptr : 0); } // Get exported symbol name const char *GetExportSymName(uint32 addr) { export_sym_t *sym; sym = export_lookup_by_addr(addr); return (sym != NULL ? sym->name : NULL); } int InitModules() { if(nmmgr_handler_add(&st_ds.nmmgr) < 0) { return -1; } if(nmmgr_handler_add(&st_gcc.nmmgr) < 0) { return -1; } return 0; } void ShutdownModules() { // EXPT_GUARD_BEGIN; // // LIST_FOREACH(cur, &library_list, list) { // library_close(cur); // } // // EXPT_GUARD_CATCH; // ds_printf("DS_ERROR: Failed unloading all modules\n"); // EXPT_GUARD_END; nmmgr_handler_remove(&st_ds.nmmgr); nmmgr_handler_remove(&st_gcc.nmmgr); } Module_t *OpenModule(const char *fn) { Module_t *m; char full_path[NAME_MAX]; char name[NAME_MAX / 2]; realpath(fn, full_path); char *file = strrchr(full_path, '/'); char *mname = file + 1; char *ext = strrchr(file, '.') + 1; memset(name, 0, sizeof(name)); strncpy(name, mname, ext - mname - 1); #ifdef MODULE_DEBUG ds_printf("DS_PROCESS: Opening module '%s' type '%s' from '%s'\n", name, ext, full_path); #endif if(name[0] && (m = library_lookup(name)) != NULL) { #ifdef MODULE_DEBUG ds_printf("DS: Module '%s' already opened\n", m->lib_get_name()); #endif m->refcnt++; return m; } if((m = library_lookup_fn(full_path)) != NULL) { #ifdef MODULE_DEBUG ds_printf("DS: Module '%s' already opened\n", m->lib_get_name()); #endif m->refcnt++; return m; } EXPT_GUARD_BEGIN; if((m = library_open(name, full_path)) == NULL) { EXPT_GUARD_RETURN NULL; } EXPT_GUARD_CATCH; m = NULL; #ifdef MODULE_DEBUG ds_printf("DS_ERROR: library_open failed\n"); #endif EXPT_GUARD_END; if(m != NULL) { strncpy(m->image.fn, full_path, NAME_MAX); } return m; } int CloseModule(Module_t *m) { if(m == NULL) { return -1; } if(m->refcnt <= 0) { int r = -1; EXPT_GUARD_BEGIN; r = library_close(m); EXPT_GUARD_CATCH; r = -1; #ifdef MODULE_DEBUG ds_printf("DS_ERROR: library_close failed\n"); #endif EXPT_GUARD_END; return r; } return --m->refcnt; } int PrintModuleList(int (*pf)(const char *fmt, ...)) { klibrary_t *cur; pf(" id base size name\n"); LIST_FOREACH(cur, &library_list, list) { pf("%04lu %p %08lu %s\n", cur->libid, cur->image.data, cur->image.size, cur->lib_get_name()); } pf("--end of list--\n"); return 0; } <file_sep>/sdk/bin/src/ciso/ciso.h /* This file is part of Ciso. Ciso is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Ciso is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Copyright 2005 BOOSTER Copyright 2011-2013 SWAT */ #ifndef __CISO_H__ #define __CISO_H__ /* compressed ISO(9660) header format */ #include <stdint.h> /*uintx_t */ typedef struct ciso_header { unsigned char magic[4]; /* +00 : 'C','I','S','O' */ uint32_t header_size; /* +04 : header size (==0x18) */ uint64_t total_bytes; /* +08 : number of original data size */ uint32_t block_size; /* +10 : number of compressed block size */ unsigned char ver; /* +14 : version 01 */ unsigned char align; /* +15 : align of index value */ unsigned char rsv_06[2]; /* +16 : reserved */ #if 0 // For documentation // Note : a link to a spec of the format would be welcomed // INDEX BLOCK uint32_t index[0]; /* +18 : block[0] index */ uint32_t index[1]; /* +1C : block[1] index */ : : uint32_t index[last]; /* +?? : block[last] */ uint32_t index[last+1]; /* +?? : end of last data point */ // DATA BLOCK unsigned char data[]; /* +?? : compressed or plain sector data */ #endif } CISO_H; // total size should be checked with a static assert /* note: file_pos_sector[n] = (index[n]&0x7fffffff) << CISO_H.align file_size_sector[n] = ( (index[n+1]&0x7fffffff) << CISO_H.align) - file_pos_sector[n] if(index[n]&0x80000000) // read 0x800 without compress else // read file_size_sector[n] bytes and decompress data */ /* ensure that header size is correct (control unwanted padding) */ enum { __ciso_static_assert = 1 / (sizeof(CISO_H) == 24) }; #endif <file_sep>/include/gl/gl.h #ifndef __GL_GL_H #define __GL_GL_H #define NOT_IMPLEMENTED 0 #define GLAPI #define GLAPIENTRY #include <sys/cdefs.h> __BEGIN_DECLS /* This file was created using Mesa 3-D 3.4's gl.h as a reference. It is not a complete gl.h header, but includes enough to use GL effectively. */ /* This is currently DC specific, so I don't feel toooo bad about this =) */ #include <dc/pvr.h> /* GL data types */ #include <arch/types.h> typedef unsigned int GLenum; typedef int GLboolean; typedef unsigned int GLbitfield; typedef void GLvoid; typedef int8 GLbyte; /* 1-byte signed */ typedef int16 GLshort; /* 2-byte signed */ typedef int32 GLint; /* 4-byte signed */ typedef uint8 GLubyte; /* 1-byte unsigned */ typedef uint16 GLushort; /* 2-byte unsigned */ typedef uint32 GLuint; /* 4-byte unsigned */ typedef int32 GLsizei; /* 4-byte signed */ typedef float GLfloat; /* single precision float */ typedef float GLclampf; /* single precision float in [0,1] */ /* For these next two, KOS is generally compiled in m4-single-only, so we just use floats for everything anyway. */ typedef float GLdouble; /* double precision float */ typedef float GLclampd; /* double precision float in [0,1] */ void glPixelStorei( GLenum pname, GLint param ); void glTexSubImage2D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels ); void glVertex2f( GLfloat x, GLfloat y ); void glVertex2i( GLint x, GLint y ); void glVertex2fv(const GLfloat *v); void glTexEnvf( GLenum target, GLenum pname, GLfloat param ); void glTranslated( GLdouble x, GLdouble y, GLdouble z ); /* Constants */ #define GL_FALSE 0 #define GL_TRUE 1 /* Data types */ #define GL_BYTE 0x1400 #define GL_UNSIGNED_BYTE 0x1401 #define GL_SHORT 0x1402 #define GL_UNSIGNED_SHORT 0x1403 #define GL_INT 0x1404 #define GL_UNSIGNED_INT 0x1405 #define GL_FLOAT 0x1406 #define GL_DOUBLE 0x140A #define GL_2_BYTES 0x1407 #define GL_3_BYTES 0x1408 #define GL_4_BYTES 0x1409 /* StringName */ #define GL_VENDOR 0x1F00 #define GL_RENDERER 0x1F01 #define GL_VERSION 0x1F02 #define GL_EXTENSIONS 0x1F03 /* Gets */ #define GL_ATTRIB_STACK_DEPTH 0x0BB0 #define GL_CLIENT_ATTRIB_STACK_DEPTH 0x0BB1 #define GL_COLOR_CLEAR_VALUE 0x0C22 #define GL_COLOR_WRITEMASK 0x0C23 #define GL_CURRENT_INDEX 0x0B01 #define GL_CURRENT_COLOR 0x0B00 #define GL_CURRENT_NORMAL 0x0B02 #define GL_CURRENT_RASTER_COLOR 0x0B04 #define GL_CURRENT_RASTER_DISTANCE 0x0B09 #define GL_CURRENT_RASTER_INDEX 0x0B05 #define GL_CURRENT_RASTER_POSITION 0x0B07 #define GL_CURRENT_RASTER_TEXTURE_COORDS 0x0B06 #define GL_CURRENT_RASTER_POSITION_VALID 0x0B08 #define GL_CURRENT_TEXTURE_COORDS 0x0B03 #define GL_INDEX_CLEAR_VALUE 0x0C20 #define GL_INDEX_MODE 0x0C30 #define GL_INDEX_WRITEMASK 0x0C21 #define GL_MODELVIEW_MATRIX 0x0BA6 #define GL_MODELVIEW_STACK_DEPTH 0x0BA3 #define GL_NAME_STACK_DEPTH 0x0D70 #define GL_PROJECTION_MATRIX 0x0BA7 #define GL_PROJECTION_STACK_DEPTH 0x0BA4 #define GL_RENDER_MODE 0x0C40 #define GL_RGBA_MODE 0x0C31 #define GL_TEXTURE_MATRIX 0x0BA8 #define GL_TEXTURE_STACK_DEPTH 0x0BA5 #define GL_VIEWPORT 0x0BA2 #define GL_UNPACK_ALIGNMENT 0x0CF5 #define GL_PACK_ALIGNMENT 0x0D05 /* Primitives types: all 0's are unsupported for now */ #define GL_POINTS 1 #define GL_LINES 2 #define GL_LINE_LOOP 3 #define GL_LINE_STRIP 4 #define GL_TRIANGLES 5 #define GL_TRIANGLE_STRIP 6 #define GL_TRIANGLE_FAN 7 #define GL_QUADS 8 #define GL_QUAD_STRIP 9 #define GL_POLYGON 10 //+HT Extensions inspired from MiniGL (Amiga) #define GL_NT_FLATFAN GL_POLYGON +1 #define GL_NT_FLATSTRIP GL_POLYGON +2 #define GL_NT_QUADS GL_POLYGON +3 /* FrontFaceDirection */ #define GL_CW 0x0900 #define GL_CCW 0x0901 #define GL_CULL_FACE 0x0B44 #define GL_FRONT 0x0404 #define GL_BACK 0x0405 /* Scissor box */ #define GL_LIST_BIT 0x00020000 #define GL_SCISSOR_TEST 0x0008 /* capability bit */ #define GL_KOS_USERCLIP_OUTSIDE 0x4000 /* capability bit */ #define GL_SCISSOR_BOX 0x0C10 /* Vertex Arrays */ #define GL_VERTEX_ARRAY 0x8074 #define GL_NORMAL_ARRAY 0x8075 #define GL_COLOR_ARRAY 0x8076 #define GL_INDEX_ARRAY 0x8077 #define GL_TEXTURE_COORD_ARRAY 0x8078 #define GL_EDGE_FLAG_ARRAY 0x8079 #define GL_VERTEX_ARRAY_SIZE 0x807A #define GL_VERTEX_ARRAY_TYPE 0x807B #define GL_VERTEX_ARRAY_STRIDE 0x807C #define GL_NORMAL_ARRAY_TYPE 0x807E #define GL_NORMAL_ARRAY_STRIDE 0x807F #define GL_COLOR_ARRAY_SIZE 0x8081 #define GL_COLOR_ARRAY_TYPE 0x8082 #define GL_COLOR_ARRAY_STRIDE 0x8083 #define GL_INDEX_ARRAY_TYPE 0x8085 #define GL_INDEX_ARRAY_STRIDE 0x8086 #define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 #define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 #define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A #define GL_EDGE_FLAG_ARRAY_STRIDE 0x808C #define GL_VERTEX_ARRAY_POINTER 0x808E #define GL_NORMAL_ARRAY_POINTER 0x808F #define GL_COLOR_ARRAY_POINTER 0x8090 #define GL_INDEX_ARRAY_POINTER 0x8091 #define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 #define GL_EDGE_FLAG_ARRAY_POINTER 0x8093 #define GL_V2F 0x2A20 #define GL_V3F 0x2A21 #define GL_C4UB_V2F 0x2A22 #define GL_C4UB_V3F 0x2A23 #define GL_C3F_V3F 0x2A24 #define GL_N3F_V3F 0x2A25 #define GL_C4F_N3F_V3F 0x2A26 #define GL_T2F_V3F 0x2A27 #define GL_T4F_V4F 0x2A28 #define GL_T2F_C4UB_V3F 0x2A29 #define GL_T2F_C3F_V3F 0x2A2A #define GL_T2F_N3F_V3F 0x2A2B #define GL_T2F_C4F_N3F_V3F 0x2A2C #define GL_T4F_C4F_N3F_V4F 0x2A2D /* Matrix modes */ #define GL_MATRIX_MODE 0x0BA0 #define GL_MATRIX_MODE_FIRST 1 #define GL_MODELVIEW 1 #define GL_PROJECTION 2 #define GL_TEXTURE 3 #define GL_MATRIX_COUNT 4 /* Special KOS "matrix mode" (for glKosMatrixApply only) */ #define GL_KOS_SCREENVIEW 0x100 /* "Depth buffer" -- we don't actually support a depth buffer because the PVR does all of that internally. But these constants are to ease porting. */ #define GL_NEVER 0x0200 #define GL_LESS 0x0201 #define GL_EQUAL 0x0202 #define GL_LEQUAL 0x0203 #define GL_GREATER 0x0204 #define GL_NOTEQUAL 0x0205 #define GL_GEQUAL 0x0206 #define GL_ALWAYS 0x0207 #define GL_DEPTH_TEST 0 #define GL_DEPTH_BITS 0 #define GL_DEPTH_CLEAR_VALUE 0 #define GL_DEPTH_FUNC 0 #define GL_DEPTH_RANGE 0 #define GL_DEPTH_WRITEMASK 0 #define GL_DEPTH_COMPONENT 0 /* Lighting constants */ #define GL_LIGHTING 0x0b50 #define GL_LIGHT0 0x0010 /* capability bit */ #define GL_LIGHT1 0x0000 #define GL_LIGHT2 0x0000 #define GL_LIGHT3 0x0000 #define GL_LIGHT4 0x0000 #define GL_LIGHT5 0x0000 #define GL_LIGHT6 0x0000 #define GL_LIGHT7 0x0000 #define GL_AMBIENT 0x1200 #define GL_DIFFUSE 0x1201 #define GL_SPECULAR 0 #define GL_SHININESS 0 #define GL_EMISSION 0 #define GL_POSITION 0x1203 #define GL_SHADE_MODEL 0x0b54 #define GL_FLAT 0x1d00 #define GL_SMOOTH 0x1d01 /* Fog */ #define GL_FOG 0x0004 /* capability bit */ #define GL_FOG_MODE 0x0B65 #define GL_FOG_DENSITY 0x0B62 #define GL_FOG_COLOR 0x0B66 #define GL_FOG_INDEX 0x0B61 #define GL_FOG_START 0x0B63 #define GL_FOG_END 0x0B64 #define GL_LINEAR 0x2601 #define GL_EXP 0x0800 #define GL_EXP2 0x0801 /* Hints */ #define GL_FOG_HINT 0x0C54 #define GL_PERSPECTIVE_CORRECTION_HINT 0x0c50 #define GL_POINT_SMOOTH_HINT 0x0C51 #define GL_LINE_SMOOTH_HINT 0x0C52 #define GL_POLYGON_SMOOTH_HINT 0x0C53 #define GL_DONT_CARE 0x1100 #define GL_FASTEST 0x1101 #define GL_NICEST 0x1102 #define GL_STENCIL_TEST 0x0B90 /* Misc bitfield things; we don't really use these either */ // #define GL_COLOR_BUFFER_BIT 0 // #define GL_DEPTH_BUFFER_BIT 0 #define GL_ALPHA_TEST 0x0BC0 /* Blending: not sure how we'll use these yet; the PVR supports a few of these so we'll want to eventually */ #define GL_BLEND 0x0BE2 /* capability bit */ #define GL_BLEND_SRC 2 #define GL_BLEND_DST 3 #define GL_ZERO 0 #define GL_ONE 1 #define GL_SRC_COLOR 0x0300 #define GL_ONE_MINUS_SRC_COLOR 0x0301 #define GL_SRC_ALPHA 0x0302 #define GL_ONE_MINUS_SRC_ALPHA 0x0303 #define GL_DST_ALPHA 0x0304 #define GL_ONE_MINUS_DST_ALPHA 0x0305 #define GL_DST_COLOR 0x0306 #define GL_ONE_MINUS_DST_COLOR 0x0307 /*#define GL_SRC_ALPHA_SATURATE 0x0308 unsupported */ /* Misc texture constants */ #define GL_TEXTURE_2D 0x0001 /* capability bit */ #define GL_TEXTURE_1D 0x0001 #define GL_KOS_AUTO_UV 0x8000 /* capability bit */ #define GL_TEXTURE_WRAP_S 0x2802 #define GL_TEXTURE_WRAP_T 0x2803 #define GL_TEXTURE_MAG_FILTER 0x2800 #define GL_TEXTURE_MIN_FILTER 0x2801 #define GL_TEXTURE_FILTER GL_TEXTURE_MIN_FILTER #define GL_FILTER_NONE 0 #define GL_FILTER_BILINEAR 1 #define GL_REPEAT 0x2901 #define GL_CLAMP 0x2900 #define GL_UNPACK_ROW_LENGTH 0x0CF2 /* Texture Environment */ #define GL_TEXTURE_ENV_MODE 0x2200 #define GL_REPLACE 0 #define GL_MODULATE 1 #define GL_DECAL 2 #define GL_MODULATEALPHA 3 #define GL_NEAREST 0x2600 /* Texture mapping */ #define GL_TEXTURE_ENV 0x2300 #define GL_TEXTURE_ENV_COLOR 0x2201 #define GL_NEAREST_MIPMAP_NEAREST 0x2700 #define GL_NEAREST_MIPMAP_LINEAR 0x2702 #define GL_LINEAR_MIPMAP_NEAREST 0x2701 #define GL_LINEAR_MIPMAP_LINEAR 0x2703 /* Display Lists */ #define GL_COMPILE 0x1300 #define GL_COMPILE_AND_EXECUTE 0x1301 #define GL_LIST_BASE 0x0B32 #define GL_LIST_INDEX 0x0B33 #define GL_LIST_MODE 0x0B30 /* Buffers, Pixel Drawing/Reading */ #if NOT_IMPLEMENTED #define GL_NONE 0x0 #define GL_LEFT 0x0406 #define GL_RIGHT 0x0407 #endif /*GL_FRONT 0x0404 */ /*GL_BACK 0x0405 */ /*GL_FRONT_AND_BACK 0x0408 */ #if NOT_IMPLEMENTED #define GL_FRONT_LEFT 0x0400 #define GL_FRONT_RIGHT 0x0401 #endif #define GL_BACK_LEFT 0x0402 #if NOT_IMPLEMENTED #define GL_BACK_RIGHT 0x0403 #define GL_AUX0 0x0409 #define GL_AUX1 0x040A #define GL_AUX2 0x040B #define GL_AUX3 0x040C #define GL_RED 0x1903 #define GL_GREEN 0x1904 #define GL_BLUE 0x1905 #endif #define GL_ALPHA 0x1906 #define GL_LUMINANCE 0x1909 #if NOT_IMPLEMENTED #define GL_LUMINANCE_ALPHA 0x190A #define GL_ALPHA_BITS 0x0D55 #define GL_RED_BITS 0x0D52 #define GL_GREEN_BITS 0x0D53 #define GL_BLUE_BITS 0x0D54 #define GL_INDEX_BITS 0x0D51 #define GL_SUBPIXEL_BITS 0x0D50 #define GL_AUX_BUFFERS 0x0C00 #define GL_READ_BUFFER 0x0C02 #define GL_DRAW_BUFFER 0x0C01 #define GL_DOUBLEBUFFER 0x0C32 #define GL_STEREO 0x0C33 #define GL_BITMAP 0x1A00 #define GL_COLOR 0x1800 #define GL_DEPTH 0x1801 #define GL_STENCIL 0x1802 #define GL_DITHER 0x0BD0 #endif #define GL_RGB 0x1907 #define GL_RGBA 0x1908 #define GL_COLOR_INDEX 0x1900 #define GL_ALL_ATTRIB_BITS 0x000FFFFF /* OpenGL 1.1 */ #if NOT_IMPLEMENTED #define GL_PROXY_TEXTURE_1D 0x8063 #define GL_PROXY_TEXTURE_2D 0x8064 #define GL_TEXTURE_PRIORITY 0x8066 #define GL_TEXTURE_RESIDENT 0x8067 #define GL_TEXTURE_INTERNAL_FORMAT 0x1003 #define GL_ALPHA4 0x803B #define GL_ALPHA8 0x803C #define GL_ALPHA12 0x803D #define GL_ALPHA16 0x803E #define GL_LUMINANCE4 0x803F #endif #define GL_LUMINANCE8 0x8040 #if NOT_IMPLEMENTED #define GL_LUMINANCE12 0x8041 #define GL_LUMINANCE16 0x8042 #define GL_LUMINANCE4_ALPHA4 0x8043 #define GL_LUMINANCE6_ALPHA2 0x8044 #define GL_LUMINANCE8_ALPHA8 0x8045 #define GL_LUMINANCE12_ALPHA4 0x8046 #define GL_LUMINANCE12_ALPHA12 0x8047 #define GL_LUMINANCE16_ALPHA16 0x8048 #endif #define GL_INTENSITY 0x8049 #if NOT_IMPLEMENTED #define GL_INTENSITY4 0x804A #endif #define GL_INTENSITY8 0x804B #if NOT_IMPLEMENTED #define GL_INTENSITY12 0x804C #define GL_INTENSITY16 0x804D #endif /* need for quake2 */ #define GL_R3_G3_B2 0x2A10 #define GL_RGB4 0x804F #define GL_RGB5 0x8050 #define GL_RGB8 0x8051 #define GL_RGB10 0x8052 #define GL_RGB12 0x8053 #define GL_RGB16 0x8054 #define GL_RGBA2 0x8055 #define GL_RGBA4 0x8056 #define GL_RGB5_A1 0x8057 #define GL_RGBA8 0x8058 #define GL_RGB10_A2 0x8059 #define GL_RGBA12 0x805A #define GL_RGBA16 0x805B #if NOT_IMPLEMENTED #define GL_CLIENT_PIXEL_STORE_BIT 0x00000001 #define GL_CLIENT_VERTEX_ARRAY_BIT 0x00000002 #define GL_ALL_CLIENT_ATTRIB_BITS 0xFFFFFFFF #define GL_CLIENT_ALL_ATTRIB_BITS 0xFFFFFFFF #endif /* Texture format definitions (yes, these vary from real GL) */ #define GL_ARGB1555 (PVR_TXRFMT_ARGB1555 | PVR_TXRFMT_NONTWIDDLED) #define GL_RGB565 (PVR_TXRFMT_RGB565 | PVR_TXRFMT_NONTWIDDLED) #define GL_ARGB4444 (PVR_TXRFMT_ARGB4444 | PVR_TXRFMT_NONTWIDDLED) #define GL_YUV422 (PVR_TXRFMT_YUV422 | PVR_TXRFMT_NONTWIDDLED) #define GL_BUMP (PVR_TXRFMT_BUMP | PVR_TXRFMT_NONTWIDDLED) #define GL_ARGB1555_TWID PVR_TXRFMT_ARGB1555 #define GL_RGB565_TWID PVR_TXRFMT_RGB565 #define GL_ARGB4444_TWID PVR_TXRFMT_ARGB4444 #define GL_YUV422_TWID PVR_TXRFMT_YUV422 #define GL_BUMP_TWID PVR_TXRFMT_BUMP /* KOS-specific defines */ #define GL_LIST_NONE 0x00 #define GL_LIST_FIRST 0x01 #define GL_LIST_OPAQUE_POLY 0x01 /* PVR2 modes */ #define GL_LIST_OPAQUE_MOD 0x02 #define GL_LIST_TRANS_POLY 0x04 #define GL_LIST_TRANS_MOD 0x08 #define GL_LIST_PUNCHTHRU 0x10 #define GL_LIST_END 0x20 /* no more lists */ #define GL_LIST_COUNT 5 /* KOS-DCPVR-Modifier-specific '?primatives?'*/ #define GL_KOS_MODIFIER_OTHER_POLY PVR_MODIFIER_OTHER_POLY #define GL_KOS_MODIFIER_FIRST_POLY PVR_MODIFIER_FIRST_POLY #define GL_KOS_MODIFIER_LAST_POLY PVR_MODIFIER_LAST_POLY /* Applied to primatives that will be affected by modifier volumes or cheap shadows */ #define GL_KOS_MODIFIER 0x2000 /* capability bit */ #define GL_KOS_CHEAP_SHADOW 0x1000 /* capability bit */ /* KOS near Z-CLIPPING */ #define GL_KOS_NEARZ_CLIPPING 0x0400 /* capability bit */ /* KOS-specific APIs */ int glKosInit(); /* Call before using GL */ void glKosShutdown(); /* Call after finishing with it */ void glKosGetScreenSize(GLfloat *x, GLfloat *y); /* Get screen size */ void glKosBeginFrame(); /* Begin frame sequence */ void glKosFinishFrame(); /* Finish frame sequence */ void glKosFinishList(); /* Finish with the current list */ void glKosMatrixIdent(); /* Set the DC's matrix regs to an identity */ void glKosMatrixApply(GLenum mode); /* Apply one of the GL matrices to the DC's matrix regs */ void glKosMatrixDirty(); /* Set matrix regs as dirtied */ void glKosPolyHdrDirty(); /* Set poly header context as dirtied */ void glKosPolyHdrSend(); /* Send the current KGL poly header */ /* Miscellaneous APIs */ void glClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); void glClear(GLbitfield mask); void glEnable(GLenum cap); void glDisable(GLenum cap); void glFrontFace(GLenum mode); void glCullFace(GLenum mode); void glFlush(); void glHint(GLenum target, GLenum mode); void glPointSize(GLfloat size); const GLubyte *glGetString(GLenum name); void glGetFloatv(GLenum pname, GLfloat *param); /* Blending functions */ void glBlendFunc(GLenum sfactor, GLenum dfactor); /* Depth buffer (non-functional, just stubs) */ void glClearDepth(GLclampd depth); void glDepthMask(GLboolean flag); void glDepthFunc(GLenum func); /* Transformation */ void glMatrixMode(GLenum mode); void glFrustum(GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat znear, GLfloat zfar); void glOrtho(GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat znear, GLfloat zfar); void glDepthRange(GLclampf n, GLclampf f); void glViewport(GLint x, GLint y, GLsizei width, GLsizei height); void glPushMatrix(void); void glPopMatrix(void); void glLoadIdentity(void); void glLoadMatrixf(const GLfloat *m); void glLoadTransposeMatrixf(const GLfloat *m); void glMultMatrixf(const GLfloat *m); void glMultTransposeMatrixf(const GLfloat *m); void glRotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z); void glScalef(GLfloat x, GLfloat y, GLfloat z); void glTranslatef(GLfloat x, GLfloat y, GLfloat z); /* Display lists */ GLAPI void GLAPIENTRY glDeleteLists( GLuint list, GLsizei range ); GLAPI GLuint GLAPIENTRY glGenLists(GLsizei range); GLAPI GLint GLAPIENTRY glIsList(GLuint list); GLAPI void GLAPIENTRY glNewList(GLuint list, GLenum mode); GLAPI void GLAPIENTRY glEndList(void); GLAPI void GLAPIENTRY glCallList(GLuint list); /* opengl 1.2 arrays */ GLAPI void GLAPIENTRY glEnableClientState(GLenum cap); GLAPI void GLAPIENTRY glDisableClientState(GLenum cap); GLAPI void GLAPIENTRY glArrayElement(GLint i); GLAPI void GLAPIENTRY glVertexPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); GLAPI void GLAPIENTRY glColorPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); GLAPI void GLAPIENTRY glNormalPointer(GLenum type, GLsizei stride, const GLvoid *pointer); GLAPI void GLAPIENTRY glTexCoordPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); GLenum glGetError (void); void glDrawElements( GLenum mode, GLsizei count, GLenum type, const GLvoid *indices ); void glDrawArrays( GLenum mode, GLint first, GLsizei count ); /* Drawing functions */ void glBegin(GLenum mode); void glEnd(void); void glVertex3f(GLfloat x, GLfloat y, GLfloat z); void glVertex3fv(const GLfloat *v); void glVertex4f(GLfloat x, GLfloat y, GLfloat z, GLfloat k); void glVertex4fv(const GLfloat *v); void glNormal3f(GLfloat nx, GLfloat ny, GLfloat nz); void glColor4ub(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); void glColor3f(GLfloat red, GLfloat green, GLfloat blue); void glColor3ub(GLubyte red, GLubyte green, GLubyte blue); void glColor3fv(const GLfloat *v); void glColor4f(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); void glColor4fv(const GLfloat *v); void glTexCoord4f( GLfloat s, GLfloat t, GLfloat r, GLfloat q ); void glTexCoord4fv(const GLfloat *v); void glTexCoord3f( GLfloat s, GLfloat t, GLfloat r ); void glTexCoord3fv(const GLfloat *v); void glTexCoord2f(GLfloat s, GLfloat t); void glTexCoord2fv(const GLfloat *v); void glTexCoord1f(GLfloat s); void glTexCoord1fv(const GLfloat *v); void glColorMask( GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha ); void glScissor(GLint x, GLint y, GLsizei width, GLsizei height); /* Texture API */ void glGenTextures(GLsizei n, GLuint *textures); void glDeleteTextures(GLsizei n, const GLuint *textures); void glBindTexture(GLenum target, GLuint texture); void glTexImage2D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); void glKosTex2D(GLint internal_fmt, GLsizei width, GLsizei height, pvr_ptr_t txr_address); void glTexEnvi(GLenum target, GLenum pname, GLint param); void glTexParameteri(GLenum target, GLenum pname, GLint param); void glGetTexParameteriv(GLenum target, GLenum pname, GLint *params ); /* Lighting */ void glShadeModel(GLenum mode); /* Fog */ void glFogf( GLenum pname, GLfloat param ); void glFogi( GLenum pname, GLint param ); void glFogfv( GLenum pname, const GLfloat *params ); void glFogiv( GLenum pname, const GLint *params ); /* Modifier Volumes - currently non-functional */ void glKosModBegin(GLenum mode); void glKosModEnd(void); void glKosModVolume9f(GLfloat ax, GLfloat ay, GLfloat az, GLfloat bx, GLfloat by, GLfloat bz, GLfloat cx, GLfloat cy, GLfloat cz); /* TODO */ void glPolygonStipple( const GLubyte *mask); void glAlphaFunc( GLenum func, GLclampf ref ); void glDrawBuffer( GLenum mode ); GLboolean glIsEnabled( GLenum cap ); void glGetBooleanv( GLenum pname, GLboolean *params ); void glGetDoublev( GLenum pname, GLdouble *params ); void glPolygonMode (GLenum face, GLenum mode); void glPolygonOffset( GLfloat factor, GLfloat units ); void glCopyTexSubImage2D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height ); void glCopyTexSubImage1D( GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width ); void glCopyTexImage2D( GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border ); void glCopyTexImage1D( GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border ); void glTexSubImage2D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels ); void glTexSubImage1D( GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels ); void glTexImage1D( GLenum target, GLint level, GLint internalFormat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels ); void glClearStencil( GLint s ); void glStencilOp( GLenum fail, GLenum zfail, GLenum zpass ); void glStencilMask( GLuint mask ); void glStencilFunc( GLenum func, GLint ref, GLuint mask ); void glReadPixels( GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels ); void glLoadMatrixd( const GLdouble *m ); void glLineWidth( GLfloat width ); void glFinish( void ); void glGetIntegerv( GLenum pname, GLint *params ); #define GL_DEPTH_BUFFER_BIT 0x00000100 #define GL_COLOR_BUFFER_BIT 0x00004000 #define GL_TEXTURE_BIT 0x00040000 #define GL_POLYGON_BIT 0x00000008 void glPushAttrib(GLbitfield mask); void glPopAttrib(void ); #define GL_MAX_TEXTURE_SIZE 0x0D33 #define GL_TEXTURE_BINDING_1D 0x8068 #define GL_TEXTURE_BINDING_2D 0x8069 #define GL_ALPHA_SCALE 0x0D1C #define GL_LINE 0x1B01 #define GL_FILL 0x1B02 #define GL_COLOR_MATERIAL 0x0B57 __END_DECLS #endif /* __GL_GL_H */ <file_sep>/modules/luaSDL/module.c /* DreamShell ##version## module.c - luaSDL module Copyright (C)2007-2013 SWAT */ #include <kos.h> #include <kos/exports.h> #include "ds.h" DEFAULT_MODULE_HEADER(luaSDL); int tolua_SDL_open(lua_State* tolua_S); int lib_open(klibrary_t * lib) { lua_State *L = GetLuaState(); if(L != NULL) { tolua_SDL_open(L); } RegisterLuaLib(lib_get_name(), (LuaRegLibOpen *)tolua_SDL_open); return nmmgr_handler_add(&ds_luaSDL_hnd.nmmgr); } int lib_close(klibrary_t * lib) { UnregisterLuaLib(lib_get_name()); return nmmgr_handler_remove(&ds_luaSDL_hnd.nmmgr); } <file_sep>/modules/mp3/libmp3/libmp3/main.c /* KallistiOS ##version## libmp3 main.c (c)2000-2001 <NAME> 2011 Modified by SWAT */ #include <kos.h> #include "mp3.h" /* void *sndserver_thread(void *blagh) { printf("snd_mp3_server: started\r\n"); printf("snd_mp3_server: pid is %d; capabilities: MP1, MP2, MP3\r\n", thd_get_current()->tid); sndmp3_mainloop(); printf("snd_mp3_server: exited\r\n"); return NULL; }*/ int mp3_init() { /* if (snd_stream_init() < 0) return -1; if (thd_create(1, sndserver_thread, NULL) != NULL) { sndmp3_wait_start(); return 0; } else return -1; */ return 0; } int mp3_start(const char *fn, int loop) { return sndmp3_start(fn, loop); //return spu_mp3_dec(fn); //sndmp3_start(fn, loop); } int mp3_stop() { return sndmp3_stop(); //sndmp3_stop(); //return 0; } int mp3_shutdown() { //sndmp3_shutdown(); return 0; } void mp3_volume(int vol) { //sndmp3_volume(vol); } <file_sep>/modules/aicaos/sh4/main.c #include <kos.h> #include "../aica_common.h" #include "aica_sh4.h" /* Wrapper to the real function. */ static AICA_SHARED(sh4_puts) { return puts((char *)in); } AICA_SHARED_LIST = { AICA_SHARED_LIST_ELEMENT(sh4_puts, 0x100, 0), AICA_SHARED_LIST_END, }; AICA_ADD_REMOTE(arm_puts, PRIORITY_DEFAULT); <file_sep>/modules/adx/module.c /* DreamShell ##version## module.c - adx module Copyright (C)2011-2014 SWAT */ #include "ds.h" #include "audio/adx.h" /* ADX Decoder Library */ #include "audio/snddrv.h" /* Direct Access to Sound Driver */ DEFAULT_MODULE_HEADER(adx); static int builtin_adx(int argc, char *argv[]) { if(argc < 2) { ds_printf("Usage: %s option args...\n\n" "Options: \n" " -p, --play -Start playing\n" " -s, --stop -Stop playing\n" " -e, --pause -Pause playing\n" " -r, --resume -Resume playing\n\n", argv[0]); ds_printf("Arguments: \n" " -l, --loop -Loop N times\n" " -f, --file -File for playing\n\n" "Examples: %s --play --file /cd/file.adx\n" " %s -s", argv[0], argv[0]); return CMD_NO_ARG; } int start = 0, stop = 0, loop = 0, pause = 0, resume = 0, restart = 0; char *file = NULL; struct cfg_option options[] = { {"play", 'p', NULL, CFG_BOOL, (void *) &start, 0}, {"stop", 's', NULL, CFG_BOOL, (void *) &stop, 0}, {"pause", 'e', NULL, CFG_BOOL, (void *) &pause, 0}, {"resume", 'r', NULL, CFG_BOOL, (void *) &resume, 0}, {"restart",'t', NULL, CFG_BOOL, (void *) &restart,0}, {"loop", 'l', NULL, CFG_INT, (void *) &loop, 0}, {"file", 'f', NULL, CFG_STR, (void *) &file, 0}, CFG_END_OF_LIST }; CMD_DEFAULT_ARGS_PARSER(options); if(start) { if(file == NULL) { ds_printf("DS_ERROR: Need file for playing\n"); return CMD_ERROR; } adx_stop(); /* Start the ADX stream, with looping enabled */ if(adx_dec(file, loop) < 1 ) { ds_printf("DS_ERROR: Invalid ADX file\n"); return CMD_ERROR; } /* Wait for the stream to start */ while(snddrv.drv_status == SNDDRV_STATUS_NULL) thd_pass(); } if(stop) { if(adx_stop()) ds_printf(" ADX streaming stopped\n"); } if(restart) { if(adx_restart()) ds_printf(" ADX streaming restarted\n"); } if(pause) { if(adx_pause()) ds_printf("ADX streaming paused\n"); } if(resume) { if(adx_resume()) ds_printf("ADX streaming resumed\n"); } if(!start && !stop && !pause && !resume) { ds_printf("DS_ERROR: There is no option.\n"); return CMD_NO_ARG; } else { return CMD_OK; } } int lib_open(klibrary_t * lib) { AddCmd(lib_get_name(), "ADX player", (CmdHandler *) builtin_adx); return nmmgr_handler_add(&ds_adx_hnd.nmmgr); } int lib_close(klibrary_t * lib) { RemoveCmd(GetCmdByName(lib_get_name())); adx_stop(); return nmmgr_handler_remove(&ds_adx_hnd.nmmgr); } <file_sep>/include/drivers/asic.h /** * \file asic.h * \brief Additional definitions for Dreamcast HOLLY ASIC * \date 2014-2015 * \author SWAT www.dc-swat.ru */ #ifndef _DS_ASIC_H #define _DS_ASIC_H #include <sys/cdefs.h> __BEGIN_DECLS #include <arch/types.h> #define ASIC_BIOS_PROT *((vuint32*)0xa05F74E4) #define ASIC_SYS_RESET *((vuint32*)0x005F6890) /** * Holly reset */ void asic_sys_reset(void); /** * Disabling IDE interface */ void asic_ide_disable(void); /** * Enabling IDE interface (BIOS check) */ void asic_ide_enable(void); __END_DECLS #endif /* _DS_ASIC_H */ <file_sep>/firmware/aica/codec/filter.c /* Copyright (C) 2006 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "filter.h" short filter(short x) { static short s[6] = {0, 0, 0, 0, 0, 0}; const short h[6] = { 126, 719, -5838, 10032}; short y; s[5] = s[4]; s[4] = s[3]; s[3] = s[2]; s[2] = s[1]; s[1] = s[0]; s[0] = x; y = ((s[0] + s[5])*h[0]) >> 16 + ((s[1] + s[4])*h[1]) >> 16 + ((s[2] + s[3])*h[2]) >> 16 + (s[4]*h[3]) >> 16; return y; }<file_sep>/firmware/aica/codec/profile.h #include <stdio.h> #include "systime.h" #ifndef _PROFILE_H_ #define _PROFILE_H_ long profile_time; const char *profile_name; #define PROFILE_START(name) \ do { \ profile_name = name; \ profile_time = systime_get_ms(); \ } while(0) #define PROFILE_END() \ do { \ iprintf("%s: %li ms\n", profile_name, systime_get_ms() - profile_time); \ } while(0) #endif /* _PROFILE_H_ */ <file_sep>/include/isofs/ciso.h /** * Copyright (c) 2011-2014 by SWAT <<EMAIL>> www.dc-swat.ru * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef _ISOFS_CISO_H #define _ISOFS_CISO_H #include <kos.h> /** * \file * CISO/ZISO support for isofs * * \author SWAT */ /* zlib compress */ #define CISO_MAGIC_CISO 0x4F534943 /* lzo compress */ #define CISO_MAGIC_ZISO 0x4F53495A typedef struct CISO_header { uint8 magic[4]; /* +00 : C’,'I’,'S’,'O’ */ uint32 header_size; uint64 total_bytes; uint32 block_size; uint8 ver; uint8 align; uint8 rsv_06[2]; } CISO_header_t; CISO_header_t *ciso_open(file_t fd); int ciso_close(CISO_header_t *hdr); int ciso_get_blocks(CISO_header_t *hdr, file_t fd, uint *blocks, uint32 sector, uint32 count); int ciso_read_sectors(CISO_header_t *hdr, file_t fd, uint8 *buff, uint32 start, uint32 count); #endif /* _ISOFS_CISO_H */ <file_sep>/applications/settings/modules/app_module.h /* DreamShell ##version## app_module.h - Settings app module header Copyright (C)2016-2023 SWAT */ #include "ds.h" void SettingsApp_Init(App_t *app); void SettingsApp_ShowPage(GUI_Widget *widget); void SettingsApp_ResetSettings(GUI_Widget *widget); void SettingsApp_ToggleNativeMode(GUI_Widget *widget); void SettingsApp_ToggleScreenMode(GUI_Widget *widget); void SettingsApp_ToggleScreenFilter(GUI_Widget *widget); void SettingsApp_ToggleApp(GUI_Widget *widget); void SettingsApp_ToggleRoot(GUI_Widget *widget); void SettingsApp_ToggleStartup(GUI_Widget *widget); void SettingsApp_TimeChange(GUI_Widget *widget); void SettingsApp_Time(GUI_Widget *widget); void SettingsApp_Time_Clr(GUI_Widget *widget); <file_sep>/src/events.c /**************************** * DreamShell ##version## * * events.c * * DreamShell events * * (c)2007-2023 SWAT * * http://www.dc-swat.ru * ***************************/ #include "ds.h" #include "video.h" #include "events.h" #include "console.h" static Item_list_t *events; static void FreeEvent(void *event) { free(event); } int InitEvents() { if((events = listMake()) == NULL) { return -1; } return 0; } void ShutdownEvents() { listDestroy(events, (listFreeItemFunc *) FreeEvent); } Item_list_t *GetEventList() { return events; } Event_t *GetEventById(uint32 id) { Item_t *i = listGetItemById(events, id); if(i != NULL) { return (Event_t *) i->data; } else { return NULL; } } Event_t *GetEventByName(const char *name) { Item_t *i = listGetItemByName(events, name); if(i != NULL) { return (Event_t *) i->data; } else { return NULL; } } Event_t *AddEvent(const char *name, uint16 type, Event_func *event, void *param) { Event_t *e; Item_t *i; if(name && GetEventByName(name)) return NULL; e = (Event_t *)calloc(1, sizeof(Event_t)); if(e == NULL) return NULL; e->name = name; e->event = event; e->state = EVENT_STATE_ACTIVE; e->type = type; e->param = param; if(type == EVENT_TYPE_VIDEO) { LockVideo(); } if((i = listAddItem(events, LIST_ITEM_EVENT, e->name, e, sizeof(Event_t))) == NULL) { FreeEvent(e); e = NULL; } else { e->id = i->id; } if(type == EVENT_TYPE_VIDEO) { UnlockVideo(); } return e; } int RemoveEvent(Event_t *e) { int rv = 0; if(e->type == EVENT_TYPE_VIDEO) { LockVideo(); } Item_t *i = listGetItemById(events, e->id); if(!i) rv = -1; else listRemoveItem(events, i, (listFreeItemFunc *) FreeEvent); if(e->type == EVENT_TYPE_VIDEO) { UnlockVideo(); } return rv; } int SetEventState(Event_t *e, uint16 state) { if(e->type == EVENT_TYPE_VIDEO) { LockVideo(); } e->state = state; if(e->type == EVENT_TYPE_VIDEO) { UnlockVideo(); } return state; } void ProcessInputEvents(SDL_Event *event) { Event_t *e; Item_t *i; SLIST_FOREACH(i, events, list) { e = (Event_t *) i->data; if(e->type == EVENT_TYPE_INPUT && e->state == EVENT_STATE_ACTIVE && e->event != NULL) { e->event(e, event, EVENT_ACTION_UPDATE); } } } void ProcessVideoEventsRender() { Event_t *e; Item_t *i; SLIST_FOREACH(i, events, list) { e = (Event_t *) i->data; if(e->type == EVENT_TYPE_VIDEO && e->state == EVENT_STATE_ACTIVE) { e->event(e, e->param, EVENT_ACTION_RENDER); } } } void ProcessVideoEventsUpdate(VideoEventUpdate_t *area) { Event_t *e; Item_t *i; SLIST_FOREACH(i, events, list) { e = (Event_t *) i->data; if(e->type == EVENT_TYPE_VIDEO && e->state == EVENT_STATE_ACTIVE) { e->event(e, area, EVENT_ACTION_UPDATE); } } } <file_sep>/modules/luaKOS/module.c /* DreamShell ##version## module.c - luaKOS module Copyright (C)2007-2014 SWAT */ #include <kos.h> #include <kos/exports.h> #include "ds.h" DEFAULT_MODULE_HEADER(luaKOS); int tolua_KOS_open(lua_State* tolua_S); int lib_open(klibrary_t * lib) { tolua_KOS_open(GetLuaState()); RegisterLuaLib(lib_get_name(), (LuaRegLibOpen *)tolua_KOS_open); return nmmgr_handler_add(&ds_luaKOS_hnd.nmmgr); } int lib_close(klibrary_t * lib) { UnregisterLuaLib(lib_get_name()); return nmmgr_handler_remove(&ds_luaKOS_hnd.nmmgr); }
3f017c2c3a55a2ac783045a23977765862ef4b20
[ "Ruby", "Lua", "Markdown", "Makefile", "Python", "Text", "C", "C++", "Shell" ]
518
C
DC-SWAT/DreamShell
f2551e18c06345fed0f5144245d6380203c20fa6
8e4310087eb7f8e9bed285b8c66992e4df9c9143
refs/heads/main
<file_sep># Project-01 Game Pulse ## Task The **Game Pulse** project is the first project assignment of the March 2021 cohort from University of New Hampshire's full-stack web developer coding bootcamp. Create an application that allows users to search the game and display the music playlist for user selection. This app will run in the browser and feature dynamically updated HTML, CSS, JavaScript, Third Party APIs. Need to also utilize Materialize for styling. ## User Story As a gamer who wants to jam out instead of listening to game sounds, intrigued by the unknown, I want to have a playlist generated for my listening pleasure and discover new music while gaming. ## Acceptance Criteria Given a Game Pulse project with form inputs 1. When I search for a game, then I am presented with thumbnails of the games. 2. When clicked on the load more button, then I am presented with more results if available. 3. When clicked on a thumbnail of a game, then results page is displayed with: 3.1 Results page, **Video Game Card** : Game name. Rating. Release date. 3.2 **Playlist card**: Spotify playlist Genres. 3.3 Shuffle button for playlist. 3.4 Save Pairing button to save to local storage. 3.5 Reshuffle to just reshuffle music. ## Technologies - HTML - CSS - JavaScript - jQuery - Games: [GiantBomb API](https://www.giantbomb.com/api) - Music: [Spotify]( https://developer.spotify.com/documentation/web-api/) ## Mockup The following image shows the web application's appearance and funcationality: ![Game Pulse Search Page](./res/images/searchpage.PNG) ![Game Pulse Pick A Game Page](./res/images/pickagamepage.PNG) ![Game Pulse Results Page](./res/images/resultspage.png) ## URL of the website https://unh-bootcamp-projects.github.io/project-1-group-e/ ## Github link https://github.com/UNH-Bootcamp-Projects/project-1-group-e.git <file_sep>'use strict'; $(function (){ let materializeElems = { modal: $('.modal'), sidenav: $('.sidenav'), }; let elements = { searchSection: $('.js-search-section'), gamesSection: $('.js-games-section'), resultSection: $('.js-result-section'), searchForm: $('.js-search-form'), gamesList: $('.js-games-list'), showMoreBtn: $('.js-load-more'), gameResults: $('.js-game-results'), startOver: $('.js-start-over'), musicResults: $('.js-music-results'), genreName: $('.js-genre-name'), musicShuffle: $('.js-music-shuffle'), saveForm: $('.js-save-pair-form'), tracksList: $('.js-tracks-list'), pairsList: $('.js-pairs-list'), homeLink: $('.js-home-link'), noResultsMsg: $('.js-noresults-message'), } let gameApiData = { url: 'https://www.giantbomb.com/api/', key: 'ca21f96f411cc413f9234dbec4a20f729ca3fb2b', } let musicApiData = { clientId: '9f0ad941c5394f4ca74562dbeaa29135', clientSecret: '<KEY>', } let savedPairs = JSON.parse(localStorage.getItem('savedPairs')) || {}; let currentPairData = { gameInfo: undefined, tracksInfo: [], musicGenre: undefined, }; function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } function hideElem(elem) { if (!elem.hasClass('hide')) { elem.addClass('hide'); } } function showElem(elem) { if (elem.hasClass('hide')) { elem.removeClass('hide'); } } function showSearchSection() { stopPlaying(); hideElem(elements.gamesSection); hideElem(elements.resultSection); showElem(elements.searchSection); } function showGamesSection() { stopPlaying(); hideElem(elements.searchSection); hideElem(elements.resultSection); showElem(elements.gamesSection); } function showResultSection() { hideElem(elements.searchSection); hideElem(elements.gamesSection); showElem(elements.resultSection); } /* Game Search */ function proxyFetch(url, options) { url = 'https://ben.hutchins.co/proxy/fetch/' + url; return fetch(url, options); } function searchGames(event) { event.preventDefault(); let eventElem = $(event.currentTarget); let isForm = eventElem.is('form'); let isLoadMore = eventElem.is(elements.showMoreBtn); let searchQuery = ''; let page = 1; let limit = 12; if (isForm) { let searchInput = eventElem.find('input[type="search"]'); elements.gamesList.text(''); searchQuery = searchInput.val().trim(); searchInput .val('') .one('keydown', () => { hideElem(elements.noResultsMsg); }); } if (isLoadMore) { searchQuery = eventElem.data('search-query'); page = eventElem.data('page'); } let requestUrl = `${gameApiData.url}search/?format=json&api_key=${gameApiData.key}&resources=game&query=${encodeURI(searchQuery)}&limit=${limit}&page=${page}`; proxyFetch(requestUrl) .then((response) => { if (response.ok){ return response.json(); } }) .then((data) => { if (data !== undefined && data.results.length > 0) { displayGamesSearchResults(data.results); let itemOnPage = data.number_of_page_results; let loadLimit = data.limit; if (itemOnPage === loadLimit) { elements.showMoreBtn .data({ 'search-query': searchQuery, 'page': ++page, }) .removeAttr('disabled') .removeClass('hide') .on('click.loadMore', loadMoreResults); } else { elements.showMoreBtn.addClass('hide'); } } else { if (isForm) { showElem(elements.noResultsMsg); } } }); } function loadMoreResults(event) { $(event.currentTarget) .attr('disabled', true) .off('click.loadMore'); searchGames(event); } function displayGamesSearchResults(searchedData) { searchedData.forEach((item) => { let gameInfo = { name: item.name, thumb: item.image.small_url, id: item.guid, releaseYear: item.original_release_date ? dayjs(item.original_release_date, 'YYYY-MM-DD').format('YYYY') : '', }; let gameItem = $(` <li class="game-item"> <div class="game-img" style="background-image: url(${gameInfo.thumb});"></div> <h3 class="game-name">${gameInfo.name}</h3> <span class="release-year">${gameInfo.releaseYear}</span> </li> `); gameItem .data('game-id', gameInfo.id) .on('click', selectGame); elements.gamesList.append(gameItem); }); showGamesSection(); } /* END Game Search */ /* Game Data */ function selectGame(event) { let eventElem = $(event.currentTarget); let gameId = eventElem.data('game-id'); if (gameId !== undefined) { let requestUrl = `${gameApiData.url}game/${gameId}/?format=json&api_key=${gameApiData.key}`; proxyFetch(requestUrl) .then((response) => { if (response.ok){ return response.json(); } }) .then((data) => { if (data !== undefined) { getMusicData(); displaySelectedGameData(data.results); showResultSection(); } }); } } function displaySelectedGameData(gameData) { let gameInfo = { name: gameData.name, img: gameData.image.medium_url, deck: gameData.deck, releaseDate: gameData.original_release_date ? dayjs(gameData.original_release_date, 'YYYY-MM-DD').format('D MMM YYYY') : '', genres: gameData.genres.map((item) => { return item.name; }), platforms: gameData.platforms.map((item) => { return item.abbreviation; }), }; displayGameElem(gameInfo); } function displayGameElem(gameData) { currentPairData.gameInfo = gameData; let gameElem = $(` <div class="game-image"> <img src="${gameData.img}" alt="${gameData.name}"> </div> <div class="game-info"> <h2 class="game-name">${gameData.name}</h2> <ul class="info-list"> <li class="info-item game-desc"><span class="label">Description:</span> ${gameData.deck}</li> ${gameData.releaseDate !== '' ? `<li class="info-item release-date"><span class="label">Release Date:</span> ${gameData.releaseDate}</li>` : ``} <li class="info-item game-genre"><span class="label">Genres:</span> ${gameData.genres.reduce((accum, value, index, array) => { return accum + (index !== array.length ? ', ' : '') + value; })}</li> <li class="info-item platform-icon"><span class="label">Platforms:</span> ${gameData.platforms.reduce((accum, value, index, array) => { return accum + (index !== array.length ? ', ' : '') + value; })}</li> </ul> </div> `); elements.gameResults.text('').append(gameElem); } /* END Game Data */ /* Music Data */ async function getMusicApiToken() { let result = await fetch('https://accounts.spotify.com/api/token', { method: 'POST', headers: { 'Content-Type' : 'application/x-www-form-urlencoded', 'Authorization' : 'Basic ' + btoa(musicApiData.clientId + ':' + musicApiData.clientSecret), }, body: 'grant_type=client_credentials', }); let data = await result.json(); return data.access_token; } async function getMusicGenres(token) { let result = await fetch('https://api.spotify.com/v1/recommendations/available-genre-seeds', { method: 'GET', headers: { 'Authorization' : 'Bearer ' + token}, }); let data = await result.json(); return data; } async function getMusicRecommendationByGenre() { let token = await getMusicApiToken(); let genres = await getMusicGenres(token).then((data) => { return data.genres; }); let limit = 10; let genreIndex = getRandomInt(genres.length); let result = await fetch(`https://api.spotify.com/v1/recommendations?seed_genres=${genres[genreIndex]}&limit=${limit}`, { method: 'GET', headers: { 'Authorization' : 'Bearer ' + token}, }); let data = await result.json(); elements.genreName.text(genres[genreIndex]); showElem(elements.genreName); currentPairData.musicGenre = genres[genreIndex]; return data; } function getMusicData() { if (!elements.musicShuffle.attr('disabled')) { elements.musicShuffle.attr('disabled', true); } hideElem(elements.genreName); stopPlaying(); elements.tracksList.text(''); getMusicRecommendationByGenre() .then((data) => { if (data !== undefined && data.tracks.length > 0) { displayMusicData(data.tracks); } }); } function displayMusicData(musicData) { currentPairData.tracksInfo = []; musicData.forEach((item) => { let trackInfo = { album: item.album.name, thumb: item.album.images[2] ? item.album.images[2].url : '', releaseYear: item.album.release_date ? dayjs(item.album.release_date, 'YYYY-MM-DD').format('YYYY') : '', artists: item.artists.map((item) => { return item.name; }), name: item.name, link: item.external_urls.spotify, previewUrl: item.preview_url, }; displayTrackItem(trackInfo); }); elements.musicShuffle.removeAttr('disabled'); } function displayTrackItem(trackData) { let trackItem = $(` <li class="track-item"> <a href="${trackData.link}" target="_blank" rel="external"> <div class="thumb"> <img src="${trackData.thumb}" alt="${trackData.album}"> </div> <div class="track-info"> <p class="track-name">${trackData.name}</p> <p class="about-track"> <span class="artists">${trackData.artists.reduce((accum, value, index, array) => { return accum + (index !== array.length ? ', ' : '') + value; })}</span> <span class="album">${trackData.album}</span> <span class="separator">&bull;</span> <span class="release-year">${trackData.releaseYear}</span> </p> </div> </a> </li> `); if (trackData.previewUrl !== null) { let trackPreviewBtn = $(` <button class="track-preview-btn btn-flat js-preview-audio"> <audio src="${trackData.previewUrl}"></audio> <i class="play-icon material-icons">play_circle_outline</i> <i class="pause-icon material-icons">pause_circle_outline</i> </button> `); trackPreviewBtn.on('click', playMusicPreview); trackItem.prepend(trackPreviewBtn); } currentPairData.tracksInfo.push(trackData); elements.tracksList.append(trackItem); } function playMusicPreview(event) { event.stopPropagation(); let eventElem = $(event.currentTarget); let audio = eventElem.find('audio')[0]; if (audio.paused == false) { audio.pause(); eventElem.removeClass('playing'); $(audio).off('ended.musicPreview'); } else { stopPlaying(); audio.volume = 0.1; audio.play(); eventElem.addClass('playing'); $(audio).one('ended.musicPreview', stopPlaying); } } function stopPlaying() { let audioPreview = $('.js-preview-audio.playing'); if (audioPreview.length > 0) { audioPreview.each(function () { let elem = $(this); let audio = elem.find('audio')[0]; elem.removeClass('playing'); audio.pause(); }); } } /* END Music Data */ /* Pair Data */ function savePairData(event) { event.preventDefault(); let pairName = $(event.currentTarget).find('.js-pair-name').val().trim(); if (currentPairData.gameInfo !== undefined && currentPairData.tracksInfo.length > 0 && pairName !== '') { let isExistedPair = savedPairs[pairName] ? true : false; savedPairs[pairName] = Object.assign({}, currentPairData); localStorage.setItem('savedPairs', JSON.stringify(savedPairs)); materializeElems.modal.modal('close'); if (!isExistedPair) { displayPairItem(pairName); } } } function displayPairsList() { elements.pairsList.text(''); let pairs = Object.keys(savedPairs); if (pairs.length > 0) { pairs.forEach(displayPairItem); } } function displayPairItem(pairName) { let pairElem = $(` <li class="pair-item">${pairName}</li> `); pairElem .data({ 'pair-name': pairName, }) .on('click', displayPairData); elements.pairsList.append(pairElem); } function displayPairData(event) { let eventElem = $(event.currentTarget); let pairName = eventElem.data('pair-name'); elements.genreName.text(savedPairs[pairName].musicGenre); displayGameElem(savedPairs[pairName].gameInfo); elements.tracksList.text(''); currentPairData.tracksInfo = []; savedPairs[pairName].tracksInfo.forEach(displayTrackItem); elements.musicShuffle.removeAttr('disabled'); materializeElems.sidenav.sidenav('close'); showResultSection(); } /* END Pair Data */ function init() { materializeElems.sidenav.sidenav({ edge: 'right', }); materializeElems.modal.modal(); displayPairsList(); elements.searchForm.on('submit', searchGames); elements.musicShuffle.on('click', getMusicData); elements.startOver.on('click', showSearchSection); elements.saveForm.on('submit', savePairData); elements.homeLink.on("click", showSearchSection); } init(); });
d0248093b1e21bd81d7cdd453f63d8ed4f5d88e8
[ "Markdown", "JavaScript" ]
2
Markdown
UNH-Bootcamp-Projects/project-1-group-e
b764ba56fe70e3a0458df8068c033c8fe23fb408
34266e1bfcf189c1f7cfd26fd4a51c902a1d9678
refs/heads/master
<file_sep># C_Codes List -> This contains Ondisk Implementation of List DataStructure. Whatever data is inserted in List is gets dumped in the file. which can be used to create incore list. <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "st.h" typedef struct STNode* link; struct STNode { Item item; link next; }; static link *heads, z; static int N, M; int hash(char *v, int M) { int h, a, b; a = 31415; b = 27183; for (h = 0; *v != '\0'; v++, a = (a * b)%(M-1)) { h = ((a * h) + (*v) ) %M; } return h; } int eq( char *a, char *b) { return (strcmp(a, b) == 0); } static link NEW(Item item, link next) { link x = malloc(sizeof(link)); x->item = item; x->next = next; return x; } Item search(link h, key v) { while (h != z) { if (eq(key(h->item), v)) { return h->item; } h = h->next; } return z->item; } void STinit(int max) { int i = 0; N = 0; M = N/5; heads = malloc(M * sizeof(link)); z = NEW(NULLItem, NULL); for (i = 0; i < M; i++) { heads[i] = z; } } void STinsert(Item item) { int i = hash(key(item), M); heads[i] = NEW(item, heads[i]); N++; } void STsearch(Key key) { int i = hash(key, M); return (search(heads[i], key)); } <file_sep>#ifndef ST_H #define ST_H #include "item.h" void STinit(int); void STinsert(Item); Item STsearch(Item); void STdelete(Item); #endif <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include "item.h" Key ITEMrandKey(void) { return NULL; } Item ITEMrand(Key key) { Item item = malloc(sizeof(Item)); item->key = malloc(sizeof(Key)); strcpy(item->key, key); item->value = (rand() % MAX_N); return item; } void ITEMshow(Item item) { if (item != NULLItem) { printf("Key -> %s, Value -> %d \n", item->key, item->value); }else { printf("NULLItem"); } } Key key(Item item) { if (item == NULLItem){ return NULL; } return (item->key)?item->key:NULL; } <file_sep>#include <stdio.h> #include <string.h> int main() { int input; int output; int i; int MSB; printf("Enter the input: "); scanf("%d", &input); if ((input <= 32 ) && (input >0)){ for (i = 6; i >=0; i--) { output = ((input >> i) && 1); if (output != 0) { printf("Found that MSb is %d for input %x \n", i, input); MSB = i; break; } } if (( 1 << MSB) != input) MSB = MSB + 1; output = 1 << (MSB); } else if (input == 0) output = 0; else if (input > 32) output = 32; else ouput = 16; printf ("Required output for the input %d is %d \n", input, output); return 0; } <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <unistd.h> #include "List.h" List *FileList; void (*destroy_func_ptr)(void *); void (*display_func_ptr)(void *); void destroy(void *data) { char *cdata = (char *)data; if (cdata != NULL) { free(cdata); } } void display(void *data) { char *buffer = (char *)data; printf("%s", buffer); } void FileToList(char *filename ) { FILE *fp; FILE *dest_fp; FileList = (List *)malloc(sizeof(List)); destroy_func_ptr = &destroy; display_func_ptr = &display; char buffer[BYTES_TO_READ]; size_t sz; unsigned long buf_size = 0; unsigned long bytes_to_read = 0; List_init(FileList, &destroy, &display); fp = fopen(filename, "rw"); dest_fp = fopen("copy.txt", "w"); fseek(fp, 0L, SEEK_END); sz = ftell(fp); bytes_to_read = sz; fseek(fp, 0L, SEEK_SET); printf("Size of file in Bytes : %ld \n", sz); while(bytes_to_read > 0) { assert(bytes_to_read); if (bytes_to_read > BYTES_TO_READ) { buf_size = BYTES_TO_READ; } else { buf_size = bytes_to_read; } fread(buffer, buf_size, 1, fp); List_ins_next(FileList, NULL, buffer, buf_size); fwrite(buffer, buf_size, 1, dest_fp); memset(buffer, 0, buf_size); if (bytes_to_read > BYTES_TO_READ) { bytes_to_read = bytes_to_read - BYTES_TO_READ; }else { bytes_to_read = 0; } } printf("\n"); // printf ("Actual Element in List :\n"); // List_display(FileList); fclose(fp); fclose(dest_fp); // List_destroy(FileList); //free(FileList); return; } int main(int argc, char *argv[]) { char *fileName = argv[1]; printf("FileName : %s\n", fileName); FileToList(fileName); List *l = NULL; List_Format_Dump(FileList); // l = List_Format_Extract(FileList->destroy, FileList->display); // printf("After List Extraction : \n"); // List_display(l); Object_Format_Dump(FileList); // l = Object_Format_Extract(FileList->destroy, FileList->display); // printf("After Object Extraction : \n"); // List_display(l); free(FileList); free(l); return 0; } <file_sep>#ifndef ITEM_H #define ITEM_H /* Simulate the Item for hash table*/ typedef char * Key; struct entry { Key key; int value; }; typedef struct entry * Item; #define MAX_N 1000 #define maxKey 100 #define NULLItem NULL Key ITEMrandKey(void); Item ITEMrand(Key ); void ITEMshow(Item ); Key key(Item ); #endif <file_sep>#include <stdio.h> typedef struct t_ { int a; int b; } t; int main() { t *temp; void *ptr = NULL; temp =(t *)ptr; printf ("NULL pointer casted "); return 0; } <file_sep>#include <stdio.h> int sif_set_num_vfs(int input_vfs) { int output_vfs; int MSB; int itr; if ((input_vfs <= 32 ) && (input_vfs > 0)){ for (itr = 6; itr >=0; itr--) { output_vfs = ((input_vfs >> itr) && 1); if (output_vfs != 0) { MSB = itr; break; } } if (( 1 << MSB) != input_vfs) MSB = MSB + 1; output_vfs = 1 << (MSB); } else if (input_vfs == 0) output_vfs = 0; else if (input_vfs > 32) output_vfs = 32; else output_vfs = 16; return (output_vfs); } int main() { int input; int output; // printf("Enter the output : "); // scanf("%d", &input); for (input = 0; input < 40; input++) { output = sif_set_num_vfs(input); printf("Input %d and output %d \n", input, output); } return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <assert.h> #include "List.h" void List_init(List *list, void (*destroy)(void *), void (*display)(void *)) { if (list == NULL) { list = (List *) malloc (sizeof(List)); } assert(list != NULL); list->size = 0; list->destroy = destroy; list->display = display; list->head = NULL; list->tail = NULL; list->dump = NULL; return; } uint8_t List_empty(List *list) { assert(list != NULL); if (list->size == 0) { return TRUE; } else { return FALSE; } } int List_ins_next(List *list, ListElmt *element, void *data, size_t buf_size) { assert(list != NULL); ListElmt *new_node = (ListElmt * ) malloc (sizeof(ListElmt)); ListElmt *temp = NULL; char *listdata = (char *)data; assert(new_node != NULL); new_node->data = (char *)malloc(buf_size); memcpy(new_node->data, listdata, buf_size); new_node->next = NULL; new_node->size = buf_size; new_node->idx = list->size; new_node->valid = 1; if (element == NULL) { if (List_size(list) == 0) { list->head = new_node; new_node->next = list->tail; } else { temp = list->head; while ((temp != NULL) && (temp->next != NULL)) { temp = temp->next; } temp->next = new_node; } } else { if (element->next == NULL) { new_node->next = list->tail; } new_node->next = element->next; element->next = new_node; } list->size++; return 0; } int List_rem_next(List *list, ListElmt *element, void **data) { assert(list); ListElmt *old_node = NULL; if (List_size(list) == 0) { return -1 ; } if (element == NULL) { /* Remove from Head */ *data = list->head->data; old_node = list->head; list->head = list->head->next; } else { if (element->next == NULL) { return -1; } *data = element->next->data; old_node = element->next; element->next = element->next->next; } assert(old_node); free(old_node); list->size--; return 0; } void List_display(List *l) { ListElmt *temp = List_head(l); if(temp == NULL) { return; } printf("list size : %d\n", l->size); while((temp != NULL) && (List_has_next(temp))) { l->display(temp->data); temp = List_next(temp); } if ((temp != NULL) && (temp->next == NULL)) { l->display(temp->data); } printf("\n"); return; } void List_destroy(List *list) { void *data; printf("Deletion Started \n"); printf("list size : %d\n", list->size); while(List_size(list) > 0) { if (List_rem_next(list, NULL, (void **)&data) == 0 && list->destroy != NULL) { list->display(data); list->destroy(data); } } memset(list, 0, sizeof(List)); return; } void List_Format_Dump(List *l) { FILE *list_fp = fopen(LIST_FILENAME, "wb+"); ListElmt *temp = List_head(l); OnDiskListElmt elmt; fseek(list_fp, 0L, SEEK_SET); if(temp == NULL) { fclose(list_fp); return; } if (l->dump == NULL) { temp = List_head(l); } else if (l->dump->next == NULL) { temp = List_head(l); } else { temp = l->dump->next; } while((temp != NULL) && (List_has_next(temp))) { memcpy(&elmt.data, temp->data, temp->size); elmt.key=temp->key; elmt.valid = temp->valid; elmt.size = temp->size; elmt.idx = temp->idx; fwrite(&elmt, sizeof(OnDiskListElmt), 1, list_fp); temp = List_next(temp); } if ((temp != NULL) && (temp->next == NULL)) { memcpy(&elmt.data, temp->data, temp->size); elmt.key=temp->key; elmt.valid = temp->valid; elmt.size = temp->size; elmt.idx = temp->idx; fwrite(&elmt, sizeof(OnDiskListElmt), 1, list_fp); } if (temp != NULL) { l->dump = temp; } fclose(list_fp); } List* List_Format_Extract(void (*destroy)(void *), void (*display)(void *)) { FILE *list_fp = fopen(LIST_FILENAME, "rb+"); OnDiskListElmt *elmt; uint64_t listcount = 0; int index = 0; List *l = (List *) malloc(sizeof(List)); List_init(l,destroy, display); size_t sz; fseek(list_fp, 0L, SEEK_END); sz = ftell(list_fp); listcount = sz/sizeof(OnDiskListElmt); printf("Total List Element Count : %llu\n", listcount); fseek(list_fp, 0L, SEEK_SET); elmt = (OnDiskListElmt *) malloc(listcount * sizeof(OnDiskListElmt)); fread(elmt, sizeof(OnDiskListElmt), listcount, list_fp); for (index = 0; index < listcount; index++) { List_ins_next(l, NULL, elmt[index].data, elmt[index].size); } fclose(list_fp); return l; } void Object_Format_Dump(List *l) { FILE *obj_fp = fopen(OBJECT_FILENAME, "wb+"); ListElmt *temp = List_head(l); Object *obj; unsigned long obj_count; unsigned long bin_remaining; unsigned long bin_to_copy = 0; unsigned long curr_idx = 0; unsigned long idx; unsigned long i = 0; if(temp == NULL) { fclose(obj_fp); return; } if (l->dump == NULL) { temp = List_head(l); } else if (l->dump->next == NULL) { temp = List_head(l); } else { temp = l->dump->next; } if (temp->idx == 0) { bin_remaining = l->size; } else { bin_remaining = l->size - (temp->idx + 1); } obj_count = bin_remaining/BIN_COUNT; if (obj_count == 0) { obj_count = 1; } else { obj_count = (bin_remaining % BIN_COUNT == 0)? obj_count : obj_count + 1; } // global_obj_count = global_obj_count + obj_count; obj = (Object *) malloc(obj_count * sizeof(Object)); printf("Number of Bins Per Object %d \n", BIN_COUNT); printf("Number of Objects to be created : %ld \n", obj_count); printf("Number of Bins To compress in Objects : %ld \n", bin_remaining); for (idx = 0; idx < obj_count; idx++) { /* calculation of number of bins to keep in object */ if (bin_remaining > BIN_COUNT) { bin_to_copy = BIN_COUNT; bin_remaining = bin_remaining - BIN_COUNT; } else { bin_to_copy = bin_remaining; bin_remaining = 0; } printf ("<------------------Object %ld ---------------->\n", idx); printf("Number of Bins in %ld Object : %ld \n", idx, bin_to_copy); printf("Number of Bins Remaining: %ld \n", bin_remaining); i = 0; while(i < bin_to_copy) { obj[idx].bins[i].key=temp->key; obj[idx].bins[i].valid= temp->valid; obj[idx].bins[i].size = temp->size; obj[idx].bins[i].idx = temp->idx; memcpy(&obj[idx].bins[i].data, temp->data, temp->size); temp = temp->next; i++; } obj[idx].index = idx; obj[idx].next_index = (bin_remaining != 0)? -1 : idx + 1; obj[idx].num = bin_to_copy; obj[idx].padding = 0; fwrite(&obj[idx], sizeof(Object), 1, obj_fp); printf("Current %ld Object has %ld bins \n", idx, i); printf("Done Dumping Object : %ld \n", idx); } l->dump = temp; fclose(obj_fp); printf("\n"); } List* Object_Format_Extract(void (*destroy)(void *), void (*display)(void *)) { FILE *obj_fp = fopen(OBJECT_FILENAME, "rb+"); Object *obj; ListElmt *temp; uint64_t obj_count = 0; uint64_t index = 0; uint64_t i=0; List *l = (List *) malloc(sizeof(List)); List_init(l,destroy, display); size_t sz; uint64_t bin_to_extract; fseek(obj_fp, 0L, SEEK_END); sz = ftell(obj_fp); obj_count = sz/sizeof(Object); fseek(obj_fp, 0L, SEEK_SET); obj = (Object *) malloc(obj_count * sizeof(Object)); fread(obj, sizeof(Object), obj_count, obj_fp); printf("-----------------Object Extract ---------------------\n"); printf("Number of Objects : %llu\n", obj_count); for (index = 0; index < obj_count; index++) { i = 0; bin_to_extract = obj[index].num; printf("Number of Bins in %llu Object : %llu \n", index, bin_to_extract); while (i < bin_to_extract) { List_ins_next(l, NULL, obj[index].bins[i].data, obj[index].bins[i].size); i++; } } fclose(obj_fp); return l; } /* bool list_search(List *list, char *item) { } ListElmt * list_search_elem(List *list, char *item) { } */ <file_sep>#ifndef LIST_H #define LIST_H #include <string.h> #include <stdlib.h> #include <stdio.h> #define eq(A, B) (strcmp(A, B) == 0) #define LIST_FILENAME "List.dat" #define OBJECT_FILENAME "Obj.dat" #define VALID 1 #define INVALID 0 #define TRUE 1 #define FALSE 0 /* Static Sizes */ #define BYTES_TO_READ 16 #define ONDISK_LIST_METADATA_SIZE 32 #define ONDISK_LIST_SIZE (ONDISK_LIST_METADATA_SIZE + BYTES_TO_READ) #define OBJECT_SIZE 256 #define OBJECT_METADATA_SIZE 16 #define OBJECT_PAYLOAD (OBJECT_SIZE - OBJECT_METADATA_SIZE) #define BIN_COUNT ((OBJECT_PAYLOAD % ONDISK_LIST_SIZE == 0) ? (OBJECT_PAYLOAD / ONDISK_LIST_SIZE) : (OBJECT_PAYLOAD / ONDISK_LIST_SIZE + 1)) //unsigned long global_obj_count = 1; /* Structure Definations */ typedef char * Item; typedef struct ListElmt_ { unsigned long key; uint32_t size; uint32_t valid; void *data; struct ListElmt_ *next; unsigned long idx; uint64_t padding:63; }__attribute__((packed, aligned(1))) ListElmt; /* Size -> mutliple of 8 Bytes*/ typedef struct OnDiskListElmt_ { char data[BYTES_TO_READ]; unsigned long key; unsigned long idx; uint32_t valid; uint32_t size; unsigned long padding; }OnDiskListElmt; typedef struct Object_ { OnDiskListElmt bins[BIN_COUNT]; unsigned long index; unsigned long next_index; unsigned long num; unsigned long padding; }Object; typedef struct List_ { /* can size be atomic */ /* Need to implement lock */ uint32_t size; //uint32_t (*match)(const void *key1, const void * key2); void (*destroy)(void *data); void (*display)(void *data); ListElmt *head; ListElmt *tail; ListElmt *dump; } List; /* List Macros */ #define List_size(list) ((list->size)) #define List_head(list) ((list->head)) #define List_tail(list) ((list->tail)) #define List_is_head(list, element) ((list->head == element) ? 1 : 0) #define List_is_tail(element) ((element == NULL) ? 1 : 0) #define List_data(element) \ do { \ char buffer[128] \ if (element == NULL) { \ strcpy(buffer, "Line : %s. API : %s, Node is Empty", __LINE__, __func__); \ assert(element == NULL); \ } else if (element->valid == INVALID) { \ strcpy(buffer, "Line : %s. API : %s, Node is invalid", __LINE__, __func__); \ assert(element->valid == VALID); \ } else { \ element->data; \ } \ }while(0) #define List_next(element) element->next #define List_has_next(element) ((element->next != NULL) ? 1 : 0) /* List APIs */ uint8_t List_empty(List *list); void List_init(List *list, void (*destroy)(void *data), void (*display) (void *)); int List_ins_next(List *list, ListElmt *element, void *data, size_t buf_size); int List_rem_next(List *list, ListElmt *element, void **data); void List_display(List *list); void List_destroy(List *list); void List_Format_Dump(List *list); List *List_Format_Extract(void (*destroy)(void *), void (*display)(void *)); void Object_Format_Dump(List *list); List* Object_Format_Extract(void (*destroy)(void *), void (*display)(void *)); /* bool list_search(List *list, char *item); ListElmt * list_search_elem(List *list, char *item); */ /* Futher Implementation */ /* int list_insert_at(List *list, int index, char *item); int list_insert_beg(List *list, char *item); int list_remove_at(List *list); int list_remove(List *list); */ #endif <file_sep>CC=gcc CFLAGS=-I DEPS=List.h test: test.o List.o $(CC) -o test test.o List.o
eff2dbb2e838ba99adf0d5670e3a76c0a0906b4f
[ "Markdown", "C", "Makefile" ]
12
Markdown
RajKamal2013/C_Codes
bd04dd0a81b21e64f05b949e0df41595b9040467
45cc44840ee0bb83cce6167c9b8c3abe21d7fb07
refs/heads/master
<file_sep>//<NAME> //HW03B #include <vector> #include <iostream> #include <fstream> #include <string> #include <algorithm> using namespace std; class trainStopData { friend ostream& operator<<(ostream& os, const trainStopData& rhs); public: trainStopData(const string& stop_id, const string& stop_name, double stop_lat, double stop_lon) : stop_id(stop_id), stop_name(stop_name), stop_lat(stop_lat), stop_lon(stop_lon) {} string get_id() const { return stop_id; } string get_stop_name() const { return stop_name; } double get_latitude() const { return stop_lat; } double get_longitude() const { return stop_lon; } private: string stop_id; //id of train stop (1st token) string stop_name; //name of station (4th token) double stop_lat; //latitude of train stop location double stop_lon; //logitude of train stop location }; ostream& operator<<(ostream& os, const trainStopData& rhs) { os << "ID: " << rhs.stop_id << ", Name: " << rhs.stop_name << ", Latitude: " << rhs.stop_lat << ", Longitude: " << rhs.stop_lon << endl; return os; } int main() { vector<trainStopData> data; ifstream ifs; ifs.open("MTA_train_stop_data.txt"); if (!ifs) { //checks if file exists cerr << "Could not open file" << endl; } string id = "", name = ""; double lat = 0, lon = 0; string dumb = ""; //place holder int count = 0; //counts what piece of info being read (going in order of member variable list 1-4) getline(ifs, dumb); //goes through first line which doesn't contain any relevant data while (getline(ifs, dumb, ',')) { if (dumb != "") { //checks to make sure the variable isn't empty string ++count; if (count == 1) { id = dumb; } else if (count == 2) { name = dumb; } else if (count == 3) { lat = stod(dumb); //converts string to double } else if (count == 4) { count = 0; lon = stod(dumb); //converts string to double trainStopData tsd(id, name, lat, lon); data.push_back(tsd); getline(ifs, dumb); //brings to next line } } } ifs.close(); for (size_t i = 0; i < data.size(); i++) { //prints out data cout << data[i] << endl; } }<file_sep>//<NAME> template <typename Object> class DList { private: // The basic doubly linked list node. // Nested inside of List, can be public // because the Node is itself private struct Node { Object data; Node *prev; Node *next; Node(const Object & d = Object{}, Node * p = nullptr, Node * n = nullptr) : data{ d }, prev{ p }, next{ n } { } Node(Object && d, Node * p = nullptr, Node * n = nullptr) : data{ std::move(d) }, prev{ p }, next{ n } { } }; class iterator { public: iterator() :current(nullptr) { } Object & operator* () { return current->data; } iterator & operator++ () { this->current = this->current->next; return *this; } iterator operator++ (int) { iterator old = *this; ++(*this); return old; } iterator & operator-- () { this->current = this->current->prev; return *this; } iterator operator-- (int) { iterator old = *this; --(*this); return old; } private: Node *current; // Protected constructor for iterator. // Expects the current position. iterator(Node *p) : current{ p } { } friend class DList<Object>; }; public: DList() { init(); } ~DList() { clear(); delete head; delete tail; } // Return iterator representing beginning of list. iterator begin() { return iterator(head->next); } // Return iterator representing endmarker of list. iterator end() { return iterator(tail); } // Return number of elements currently in the list. int size() const { return theSize; } // Return true if the list is empty, false otherwise. bool empty() const { return size() == 0; } void clear() { while (!empty()) { Node* deleteNode = head->next; head->next = deleteNode->next; deleteNode->next->prev = head; --theSize; } } // front, back, push_front, push_back, pop_front, and pop_back // are the basic double-ended queue operations. Object & front() { return *begin(); } const Object & front() const { return *begin(); } Object & back() { return *--end(); } const Object & back() const { return *--end(); } void push_front(const Object & x) { insert(begin(), x); } void push_back(const Object & x) { insert(end(), x); } void push_front(Object && x) { insert(begin(), std::move(x)); } void push_back(Object && x) { insert(end(), std::move(x)); } // Insert x before itr. iterator insert(iterator itr, const Object & x) { Node *p = itr.current; ++theSize; return iterator(p->prev = p->prev->next = new Node{ x, p->prev, p }); } // Insert x before itr. iterator insert(iterator itr, Object && x) { Node *p = itr.current; ++theSize; return iterator(p->prev = p->prev->next = new Node{ std::move(x), p->prev, p }); } //////////////////////////////////// void remove(const Object & x) { Node* headCopy = head; while (headCopy->next) { if (headCopy->next->data == x) { Node *p = headCopy->next; delete headCopy; headCopy = p; } headCopy = headCopy->next; } } private: int theSize; Node *head; Node *tail; void init() { theSize = 0; head = new Node; tail = new Node; head->next = tail; tail->prev = head; } }; template<class iter> void printList(iter start, iter stop) { while (start != stop) { cout << *start << endl; ++start; } } int main() { DList<int> doub; doub.push_front(1); doub.push_back(2); doub.push_back(3); doub.push_back(2); doub.push_back(4); printList(doub.begin(), doub.end()); doub.remove(2); printList(doub.begin(), doub.end()); }<file_sep>//<NAME> //hw05 #include <iostream> #include<vector> #include<string> #include<iterator> #include<algorithm> using namespace std; template<class RandItr> void mergeSort(RandItr temp, RandItr start, RandItr stop) { if (start != stop-1) { int center = (stop - start) / 2; mergeSort(temp, start, stop - center); mergeSort(temp, stop - center+1, stop); merge(start, stop-center, stop-center+1, stop, temp); } } template <class RandItr, class Object> void mergeSort(RandItr start, RandItr end) { int sz = end - start; vector<Object> tmp(sz); mergeSort<vector<Object>::iterator>(tmp.begin(), start, end); } // #2 class Student { public: Student(const string& who, double grade) : name(who), gpa(grade) {} string getName() const { return name; } double getGPA() const { return gpa; } private: string name; double gpa; }; class meFirst { public: meFirst(const string& me) : me(me){} bool operator()(const Student& lhs, const Student& rhs) { if (rhs.getName() == me) return false; else if (lhs.getName() < rhs.getName()) return true; else return false; } private: string me; }; //3 class boolObj { //boolean object class public: boolObj(bool value) : val(value) {} bool getValue() const { return val; } private: bool val; }; class check { //functor checking the boolean value of each boolObj public: bool operator()(const boolObj& rhs) { if (rhs.getValue()) return true; else return false; } }; template<class Comparable> vector<boolObj>::iterator sortBool(vector<boolObj>::iterator start, vector<boolObj>::iterator stop, Comparable boolCheck, vector<boolObj> boolVec) { if (start == stop - 1) return start; //checks if only one item is in vector int center = (stop - start) / 2; //finds the midpoint neeeded for divide and conquer approach if (!boolCheck(*start)) { //checks first if the value is false boolVec.push_back(boolObj(false)); } sortBool(start, stop - center, boolCheck, boolVec); sortBool(stop - center, stop, boolCheck, boolVec); if (boolCheck(*start)) { //after going through both halves for false boolObj, then checks for true values boolVec.push_back(boolObj(true)); } return boolVec.begin(); //returns the first iterator to the sorted bool vector } void printVec(vector<boolObj>::iterator start, int size) { //prints out the items in the boolVector for (int i = 0; i <= size; i++) { cout << boolalpha << start->getValue() << " "; } cout << noboolalpha << endl; } int main() { vector<int> vec = { 1,4,7,5,3,2 }; for (int num : vec) cout << num; cout << endl; //mergeSort<vector<int>::iterator, int>(vec.begin(), vec.end()); for (int num : vec) cout << num; cout << endl; //2 vector<Student> v; v.push_back(Student("yo", 3)); v.push_back(Student("whats", 4)); v.push_back(Student("good", 2)); sort(v.begin(), v.end(), meFirst("pop")); //3 vector<boolObj> vecB; vecB.push_back(boolObj(false)); vecB.push_back(boolObj(true)); vecB.push_back(boolObj(false)); vecB.push_back(boolObj(true)); check newCheck; vector<boolObj> temp; vector<boolObj>::iterator sortedVec = sortBool(vecB.begin(), vecB.end(), newCheck, temp); printVec(sortedVec, vecB.size()); }<file_sep>//<NAME> //hw04 //<NAME> //HW03B #include <vector> #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <iterator> #include <cmath> #include <functional> using namespace std; class trainStopData { friend ostream& operator<<(ostream& os, const trainStopData& rhs); public: trainStopData(const string& stop_id, const string& stop_name, double stop_lat, double stop_lon) : stop_id(stop_id), stop_name(stop_name), stop_lat(stop_lat), stop_lon(stop_lon) {} string get_id() const { return stop_id; } string get_stop_name() const { return stop_name; } double get_latitude() const { return stop_lat; } double get_longitude() const { return stop_lon; } char get_route() const { return stop_id[0]; } private: string stop_id; //id of train stop (1st token) string stop_name; //name of station (4th token) double stop_lat; //latitude of train stop location double stop_lon; //logitude of train stop location }; ostream& operator<<(ostream& os, const trainStopData& rhs) { os << "ID: " << rhs.stop_id << ", Name: " << rhs.stop_name << ", Latitude: " << rhs.stop_lat << ", Longitude: " << rhs.stop_lon << endl; return os; } //HAVERSINE DISTANCE double degrad(double d) { return d * 3.1415926535897 / 180; } double haverdist(double lat1, double longit1, double lat2, double longit2) { double r = 6371; double dlat = degrad(lat2 - lat1); double dlongit = degrad(longit2 - longit1); double a = sin(dlat / 2)*sin(dlat / 2) + cos(degrad(lat1))*cos(degrad(lat2))*sin(dlongit / 2)*sin(dlongit / 2); double c = 2 * atan2(sqrt(a), sqrt(1 - a)); return r*c; } //TEMPLATED FUNCTORS template<class Object> class isStopOnRoute { public: isStopOnRoute(char rt) : route(rt){} bool operator()(const Object& data) { return route == data.get_route(); } private: char route; }; template<class Object> class isSubwayStop { public: isSubwayStop(const string& id) : stopID(id) {} bool operator()(const Object& data) { return stopID == data.get_id(); } private: string stopID; }; template<class Object> class isSubwayStopNearX { public: isSubwayStopNearX(double lon, double lat, double d) : lon(lon), lat(lat), d(d) {} bool operator()(const Object& data) { return haverdist(abs(lat), abs(lon), abs(data.get_latitude()), abs(data.get_longitude())) <= d; } private: double lon; double lat; double d; }; template<class Object> class printTrainStopInfo { public: void operator()(const Object& data) { cout << data << endl; } }; //HW04 #1 template < class Iterator, class Comparable, class doIt> int perform_if(Iterator start, Iterator stop, Comparable pred, doIt op) { int how_many = 0; while (start != stop) { if (pred(*start)) { op(*start); how_many++; } ++start; } return how_many; } void menu(const vector<trainStopData> vec) { cout << "Which function would you like to call: A, B, C, or Quit?" << endl; char choice = ' '; cin >> choice; if (choice == 'A') { cout << "Which route?"; cin >> choice; //receives data from user cout << "Called " << perform_if(vec.begin(), vec.end(), isStopOnRoute<trainStopData>(choice), printTrainStopInfo<trainStopData>()) << " times" << endl; } else if (choice == 'B') { cout << "Which subway stop?" << endl; string stopID; cin >> stopID; //receives data from user cout << "Called " << perform_if(vec.begin(), vec.end(), isSubwayStop<trainStopData>(stopID), printTrainStopInfo<trainStopData>()) << " times" << endl; } else if (choice == 'C') { cout << "What location would you like?" << endl; int latitude, logitude; double dist; cin >> latitude >> logitude >> dist; //receives data from user cout << "Called" << perform_if(vec.begin(), vec.end(), isSubwayStopNearX<trainStopData>(latitude, logitude, dist), printTrainStopInfo<trainStopData>()) << " times" << endl; } else cout << "Quit" << endl; return; //Quit } //HW04 #2 int GCD(int a, int b) { if (b == 0) return a; else if (b > a) return GCD(b, a); else return GCD(b, a % b); } //HW04 #3 template<class Object, class Iter> Object recSumVec(Iter start, Iter stop) { if (start == stop-1) return *start; //checks if only one value in vector Object mid = (stop-start) / 2; //gets the value at the midpoint return recSumVec<int, vector<int>::iterator>(start, stop - mid) + recSumVec<int, vector<int>::iterator>(stop - mid, stop); } template<class Object> Object sumVector(const vector<Object> & a) { // driver program vector<Object> copy = std::move(a); Object sum = recSumVec<int, vector<int>::iterator>(copy.begin(), copy.end()); return sum; } int main() { vector<trainStopData> data; ifstream ifs; ifs.open("MTA_train_stop_data.txt"); if (!ifs) { //checks if file exists cerr << "Could not open file" << endl; } string id = "", name = ""; double lat = 0, lon = 0; string dumb = ""; //place holder int count = 0; //counts what piece of info being read (going in order of member variable list 1-4) getline(ifs, dumb); //goes through first line which doesn't contain any relevant data while (getline(ifs, dumb, ',')) { if (dumb != "") { //checks to make sure the variable isn't empty string ++count; if (count == 1) { id = dumb; } else if (count == 2) { name = dumb; } else if (count == 3) { lat = stod(dumb); //converts string to double } else if (count == 4) { count = 0; lon = stod(dumb); //converts string to double trainStopData tsd(id, name, lat, lon); data.push_back(tsd); getline(ifs, dumb); //brings to next line } } } ifs.close(); // #1 menu(data); cout << endl; // #2 cout << "GCD:" << endl; cout << GCD(12, 4) << endl; cout << GCD(2, 3) << endl; cout << GCD(8, 0) << endl << endl; // #3 vector<int> v = { 1,2,3,4,5 }; cout << "sumVector: " << endl << sumVector<int>(v) << endl; }<file_sep>//<NAME> //Vector Class HW #include <iostream> #include <string> #include <iterator> using namespace std; class Student { friend ostream& operator<<(ostream& os, const Student& rhs); public: Student(const string& name, double gpa) : name(name), gpa(gpa){} double getGPA() const { return gpa; } string getName() const { return name; } private: string name; double gpa; }; ostream& operator<<(ostream& os, const Student& rhs) { os << rhs.name << " " << rhs.gpa << endl; return os; } template <typename Object> class Vector { public: explicit Vector(int initSize = 0): theSize{ initSize }, theCapacity{ initSize + SPARE_CAPACITY } { objects = new Object[theCapacity]; } Vector(const Vector & rhs): theSize{ rhs.theSize }, theCapacity{ rhs.theCapacity }, objects{ nullptr } { objects = new Object[theCapacity]; for (int k = 0; k < theSize; ++k) objects[k] = rhs.objects[k]; } Vector & operator= (const Vector & rhs) { Vector copy = rhs; std::swap(*this, copy); return *this; } ~Vector() { delete[] objects; } Vector(Vector && rhs): theSize{ rhs.theSize }, theCapacity{ rhs.theCapacity }, objects{ rhs.objects } { rhs.objects = nullptr; rhs.theSize = 0; rhs.theCapacity = 0; } Vector & operator= (Vector && rhs) { std::swap(theSize, rhs.theSize); std::swap(theCapacity, rhs.theCapacity); std::swap(objects, rhs.objects); return *this; } bool empty() const { return size() == 0; } int size() const { return theSize; } int capacity() const { return theCapacity; } Object & operator[](int index) { return objects[index]; } const Object & operator[](int index) const { return objects[index]; } void resize(int newSize) { if (newSize > theCapacity) reserve(newSize * 2); theSize = newSize; } void reserve(int newCapacity) { if (newCapacity < theSize) return; Object *newArray = new Object[newCapacity]; for (int k = 0; k < theSize; ++k) newArray[k] = std::move(objects[k]); theCapacity = newCapacity; std::swap(objects, newArray); delete[] newArray; } // Stacky stuff void push_back(const Object & x) { if (theSize == theCapacity) reserve(2 * theCapacity + 1); objects[theSize++] = x; } // Stacky stuff void push_back(Object && x) { if (theSize == theCapacity) reserve(2 * theCapacity + 1); objects[theSize++] = std::move(x); } // Iterator stuff: not bounds checked typedef Object* iterator; typedef const Object* const_iterator; iterator begin() { return &objects[0]; } const_iterator begin() const { return &objects[0]; } iterator end() { return &objects[size()]; } const_iterator end() const { return &objects[size()]; } //erases the element that vItr points to and returns next element //vItr must exist iterator erase(iterator vItr) { iterator start = begin(); while (start != end()) { if (start == vItr) { iterator copy = start + 1; delete start; --theSize; return copy; } else if (start == nullptr) //cehcks if the value at start does not exist before the end is reached return vItr; start++; } return ++start; } static const int SPARE_CAPACITY = 2; private: int theSize; int theCapacity; Object * objects; }; template<class Itr> class check { public: bool operator()(const Itr val) { return val; } }; template< class Itr, class UnaryPred > void print_if(Itr start, Itr end, UnaryPred pred) { for (start; start != end; start++) { if (pred(start)) cout << *(*start) << endl; } } class GPA_in_range { public: GPA_in_range(double l, double h) : low(l), high(h){} bool gpaCheck(const Student& s) const { return low <= s.getGPA() && high >= s.getGPA(); } private: double low; double high; }; int main() { Vector<Student*> vec; vec.push_back(new Student("Jon", 3.1)); vec.push_back(new Student("Matt", 4.0)); vec.push_back(new Student("Jordan", 2.2)); GPA_in_range range(3.0, 4.0); for (int i = 0; i < vec.size(); i++) { //testing to see if student's GPA is in range [3.0,4.0] cout << boolalpha << vec[i]->getName() << " " << range.gpaCheck(*vec[i]) << endl; } cout<< endl << "print_if(vec.begin(), vec.end(), pred(vec.begin()));" << endl; print_if(vec.begin(), vec.end(), check); //tests the print_If statement and pred functor Vector<Student*>::iterator v = vec.begin(); //tests the erase() method vec.erase(v); //causes RUNTIME error, infinite loop? not sure why though }<file_sep>//<NAME> //hw06 #include <vector> #include <iostream> #include <string> #include <algorithm> #include <utility> using namespace std; //1 template <typename Object> class List { private: struct Node { Object data; Node *next; Node(const Object & d = Object{}, Node * n = nullptr) : data{ d }, next{ n } { } Node(Object && d, Node * n = nullptr) : data{ std::move(d) }, next{ n } { } }; public: class iterator { public: iterator() : current(nullptr) { } Object & operator* (){ return current->data; } const Object & operator* () const { return current->data; } iterator & operator++ (){ this->current = this->current->next; return *this; } iterator operator++ (int){ iterator old = *this; ++(*this); return old; } bool operator== (const iterator & rhs) const { return current == rhs.current; } bool operator!= (const iterator & rhs) const { return !(*this == rhs); } private: Node * current; iterator(Node *p) : current(p){ } friend class List<Object>; }; public: List(){ header = new Node; } ~List(){ clear(); delete header; } List(const List & rhs) : header(new Node) { Node* copyHead = rhs.header->next; iterator head = header; while (copyHead) { insert_after(head, copyHead->data); copyHead = copyHead->next; ++head; } } List & operator= (const List & rhs){ List copy = rhs; std::swap(*this, copy); return *this; } List(List && rhs) : header(new Node){ header->next = rhs.header->next; rhs.header->next = nullptr; } List & operator= (List && rhs){ std::swap(header, rhs.header); return *this; } iterator begin() const{ return iterator(header->next); } iterator end() const { return iterator(nullptr); } iterator before_begin() const { return iterator(header); } bool empty() const { return header->next == nullptr; } void clear() { while (!empty()) pop_front(); } void pop_front() { erase_after(before_begin()); } iterator insert_after(iterator itr, const Object & x) { Node *p = itr.current; p->next = new Node{ x, p->next }; return iterator(p->next); } void remove(const Object & x) { Node * prev = header; while (prev->next != nullptr) { if (prev->next->data == x) erase_after(iterator(prev)); else prev = prev->next; } } iterator erase_after(iterator itr) { Node *p = itr.current; Node *oldNode = p->next; p->next = oldNode->next; delete oldNode; return iterator(p->next); } Object& back() { Node* copy = header; while (copy->next) { copy = copy->next; } return copy->data; } const Object & back() const { Node* copy = header; while (copy->next) { copy = copy->next; } return copy->data; } Object & front() { return header->next->data; } const Object & front() const { return header->next->data; } void sort() { if (empty()) return; Node* copy = header->next; while (copy->next) { if (copy->data > copy->next->data) { swap(copy->data, copy->next->data); } copy = copy->next; } } void merge(List & alist) { sort(); alist.sort(); iterator start1 = begin(); iterator start2 = alist.begin(); iterator stop1 = end(); iterator stop2 = alist.end(); while (true) { if (*start1 == back()) { while (start2 != stop2) { insert_after(start1, *start2); ++start2; } return; } if (*start2 <= *start1) { insert_after(start1, *start2); ++start2; } else { ++start1; } } } void remove_adjacent_duplicates() { if (!empty() && header->next->next) { Node* copy = header->next; iterator curr = begin(); while (copy->next) { if (copy->next->data == copy->data) { erase_after(curr); } copy = copy->next; ++curr; } } } template<class Predicate> void remove_if(Predicate pred) { Node* copy = header; iterator curr = before_begin(); while (copy->next) { if (pred(copy->next->data)) { erase_after(curr); } copy = copy->next; ++curr; } } iterator insert_after(iterator itr, Object && x) { Node *p = itr.current; p->next = new Node{ std::move(x), p->next }; return iterator(p->next); } private: Node *header; }; template<class iter> void printList(iter start, iter stop) { while(start != stop){ cout << *start << endl; ++start; } } //2 template<class Object> class Queue { public: Queue(const Object& x) : begin(new Node(x)) {} Queue(const Object&& x) : begin(new Node(x)) {} Object& front() { return begin->data; } Object& back(){ return end->data; } bool empty() { return begin == nullptr; } void enqueue(const Object& obj) { end->next = new Node(obj, end->next); } void enqueue(const Object&& obj) { //begin = new Node(move(obj), begin); //end = end->next; end->next = new Node(move(obj), end->next); } void dequeue() { Node *p = begin->next; delete begin; begin = p; } private: struct Node { Object data; Node *next; Node(const Object & d = Object(), Node * n = nullptr) : data{ d }, next{ n } { } Node(Object && d, Node * n = nullptr) : data{ std::move(d) }, next{ n } { } }; Node* begin; Node* end = begin; }; class isEven { public: bool operator()(int num){ return num % 2 == 0; } }; int main() { List<int> numbers; List<int>::iterator current = numbers.before_begin(); for (int i = 1; i <= 10; i++) { numbers.insert_after(current, i); current++; } cout << "numbers.front() " << numbers.front() << endl; cout << "List(const List & rhs) " << endl; List<int> numbers2 = numbers; printList<List<int>::iterator>(numbers2.begin(), numbers2.end()); cout << "merge(List & alist) " << endl; numbers.merge(numbers2); printList(numbers.begin(), numbers.end()); cout << "insert_after(numbers.begin(), 3) " << endl; numbers.insert_after(numbers.begin(), 3); printList(numbers.begin(), numbers.end()); cout << "void remove_if(Predicate pred) " << endl; //isEven check; //numbers.remove_if(check); printList(numbers.begin(), numbers.end()); cout << "void remove_adjacent_duplicates() " << endl; numbers.remove_adjacent_duplicates(); printList(numbers.begin(), numbers.end()); ///////////////////////////////// cout << endl << "==========================" << endl; Queue<char> letters('a'); letters.enqueue('b'); letters.enqueue('c'); letters.enqueue('d'); cout << "Testing enqueue() and front() " << letters.front() << endl; letters.dequeue(); cout << "dequeue() " << letters.front() << endl; cout << "back() " << letters.back() << endl; cout << boolalpha << "empty() " << letters.empty() << noboolalpha << endl; }<file_sep>//<NAME> #include <iostream> #include <cmath> using namespace std; int sumDigits(int x) { return (abs(x) < 10) ? abs(x) : sumDigits(abs(x) / 10) + (abs(x) % 10); } //divide and conquer find the largest value in a vector int main() { //terinary operator int a = 5; int b = (a % 2 == 0) ? 10 : 20; //cout << b << endl; //recursion cout << sumDigits(2) << endl; cout << sumDigits(123) << endl; cout << sumDigits(90) << endl; cout << sumDigits(-123) << endl; }<file_sep>//<NAME> //hw10 #include <iostream> #include <vector> #include <queue> using namespace std; //1 template<class Comparable> //object must have overloaded < operator void print_kth_largest(vector<Comparable>& a, int k) { priority_queue<Comparable> pq(a.begin(), a.end()); int repeatCounter = 0; if (pq.empty()) { //checks in case container was empty cout << "There is no " << k << " largest element" << endl; return; } for(int i = 1; i != k; i++) { if (i > a.size() - repeatCounter) { cout << k << " is out of range" << endl; return; } Comparable prev = pq.top(); pq.pop(); while (!pq.empty() && prev == pq.top()) {//if multiple elements have the same value pq.pop(); ++repeatCounter; } } Comparable kVal = pq.top(); cout << k << " largest = "; while (!pq.empty() && pq.top() == kVal) { //if multiple elements have the same value cout << pq.top() << " "; pq.pop(); } cout << endl; } namespace k { int main() { //1 vector<int> vec(10); for (size_t i = 0; i < vec.size(); i++) { vec[i] = (rand() % 100); //filled with random numbers between 0 and 99 } vec.push_back(67); vec.push_back(67); for (int x : vec) cout << x << " "; cout << endl; print_kth_largest(vec, 3); //case when multiple equal values print_kth_largest(vec, 5); //normal case print_kth_largest(vec, 8); //normal case print_kth_largest(vec, 9); print_kth_largest(vec, 10); //smallest value print_kth_largest(vec, 12); //when k value = size of container print_kth_largest(vec, 13); //when k value goes past the size of container //print_kth_largest(vec, 11); return 0; } } <file_sep>//<NAME> //hw08 #include <map> #include<vector> #include <string> #include <iostream> #include<fstream> #include <queue> using namespace std; //1 int wordValue(string& word, const vector<int>& values) { int value = 0; for (size_t i = 0; i < word.size(); i++) { word[i] = tolower(word[i]); //converts the letter to lower case int pos = word.at(i)-97; //finds the correct index for the letter value += values[pos]; //adds the letter point value to the total word value } return value; } ////////////////////////////////////////////// //2 template<class Comparable> struct BinaryNode { Comparable element; BinaryNode *left; BinaryNode *right; BinaryNode(const Comparable & theElement, BinaryNode *lt, BinaryNode *rt) : element{ theElement }, left{ lt }, right{ rt } { } BinaryNode(Comparable && theElement, BinaryNode *lt, BinaryNode *rt) : element{ std::move(theElement) }, left{ lt }, right{ rt } { } }; // BinarySearchTree class // // CONSTRUCTION: zero parameter // // ******************PUBLIC OPERATIONS********************* // void insert( x ) --> Insert x // bool contains( x ) --> Return true if x is present // boolean isEmpty( ) --> Return true if empty; else false // void makeEmpty( ) --> Remove all items // ******************ERRORS******************************** template <typename Comparable> class BinarySearchTree { public: typedef BinaryNode<Comparable> Node; BinarySearchTree() : root{ nullptr } { } /** * Copy constructor */ BinarySearchTree(const BinarySearchTree & rhs) : root{ nullptr } { root = clone(rhs.root); } /** * Move constructor */ BinarySearchTree(BinarySearchTree && rhs) : root{ rhs.root } { rhs.root = nullptr; } /** * Destructor for the tree */ ~BinarySearchTree() { makeEmpty(); } /** * Copy assignment */ BinarySearchTree & operator=(const BinarySearchTree & rhs) { BinarySearchTree copy = rhs; std::swap(*this, copy); return *this; } /** * Move assignment */ BinarySearchTree & operator=(BinarySearchTree && rhs) { std::swap(root, rhs.root); return *this; } /** * Returns true if x is found in the tree. */ bool contains(const Comparable & x) const { return contains(x, root); //see private methods } /** * Test if the tree is logically empty. * Return true if empty, false otherwise. */ bool isEmpty() const { return root == nullptr; } /** * Make the tree logically empty. */ void makeEmpty() { makeEmpty(root); } /** * Insert x into the tree; duplicates are ignored. */ void insert(const Comparable & x) { insert(x, root); } /** * Insert x into the tree; duplicates are ignored. */ void insert(Comparable && x) { insert(std::move(x), root); } ////////////// //2 void printRange(const Comparable& low, const Comparable& high) const { printRange(low, high, root); //see private methods } void printStringy() const { //prints a stingy BST Node* curr = root; while (curr) { cout << curr->element; curr = curr->right; } cout << endl; } void stringy() { stringy(root); //see private methods sortStringy(); } double average_node_depth(int size) const { //returns a rounded double because it is a more accurate average than integer division return std::round((double)average_node_depth(root, 0) / (double)size); //see private methods } ///////////////////////////////// //3 void listNodes() { Node* curr = root; queue<Node*> nodes; nodes.push(curr); Node* l = curr->left; Node* r = curr->right; while (l && !r) { nodes.push(l); Node* temp = l->right; l = l->left; r = temp; } while (r && !l) { nodes.push(r); Node* temp = r->left; r = r->right; l = temp; } while (l && r) { nodes.push(l); nodes.push(r); if (l->left) nodes.push(l->left); if (l->right) l = l->right; else { l = l->left; } if (r->right) nodes.push(r->right); if (r->left) r = r->left; else { r = r->right; } } //double counting of some nodes will be handled in the following code cout << nodes.front()->element; Comparable prev = nodes.front()->element; //this is to make sure prev element wasn't a duplicate nodes.pop(); while (!nodes.empty()) { if (nodes.front()->element != prev) { //checks element with previous outputed element cout << nodes.front()->element; prev = nodes.front()->element; } nodes.pop(); } cout << endl; } private: BinaryNode<Comparable> *root; /** * Internal method to insert into a subtree. * x is the item to insert. * t is the node that roots the subtree. * Set the new root of the subtree. */ void insert(const Comparable & x, Node * & t) { if (t == nullptr) t = new Node{ x, nullptr, nullptr }; else if (x < t->element) insert(x, t->left); else if (t->element < x) insert(x, t->right); else ; // Duplicate; do nothing } /** * Internal method to insert into a subtree. * x is the item to insert. * t is the node that roots the subtree. * Set the new root of the subtree. */ void insert(Comparable && x, Node * & t) { if (t == nullptr) t = new Node{ std::move(x), nullptr, nullptr }; else if (x < t->element) insert(std::move(x), t->left); else if (t->element < x) insert(std::move(x), t->right); else ; // Duplicate; do nothing } /** * Internal method to make subtree empty. */ void makeEmpty(Node * & t) { if (t != nullptr) { makeEmpty(t->left); makeEmpty(t->right); delete t; } t = nullptr; } /** * Internal method to clone subtree. */ Node * clone(Node *t) const { if (t == nullptr) return nullptr; else return new Node{ t->element, clone(t->left), clone(t->right) }; } bool contains(const Comparable& x, Node* root) const { if (!root) return false; if (root->element == x) return true; else if (root->element < x) return contains(x, root->right); else return contains(x, root->left); } void printRange(const Comparable& low, const Comparable& high, const Node* curr) const { if (!curr) return; else if (curr->element < low) { //if current element is too low printRange(low, high, curr->right); } else if (high < curr->element) { //if current element is too high printRange(low, high, curr->left); } else { cout << curr->element; printRange(low, high, curr->left); printRange(low, high, curr->right); } } Node* findMin(Node* t) const { //finds the minimum node in a binary search tree if (!t) return nullptr; while (t->left) t = t->left; return t; // ////////////////////////////////////// // //Node* min = curr; // //while (curr) { // // if (curr->element < min->element) //checks if current node element is the smallest element // // min = curr; // // if (curr->right && curr->right->element < curr->element) // // curr = curr->right; // // else // // curr = curr->left; // //} // //return min; // //This was slightly modified version of findMinStringy() which found the lowest node based on actual element value } Node* findMinStringy(Node* curr) const { //finds the minimum node in an unbalanced stringy search tree Node* min = curr; while (curr) { if (curr->element < min->element) //checks if current node element is the smallest element min = curr; curr = curr->right; } return min; } void sortStringy() { //sorts an unordered stringy BST Node* copy = root; while (copy) { std::swap(copy->element, findMinStringy(copy)->element); //swaps the elements copy = copy->right; } } void stringy(Node*& curr) { //creates a stringy BST if (!curr) return; if (findMin(curr->right)) { //finds minimum value of right side of tree findMin(curr->right)->left = curr->left; //sets the left side of tree to the left side of right's minimum node curr->left = nullptr; stringy(curr->right); //goes to next element on right side } else { curr->right = curr->left; //if there is no elements to right, then just shift all the left side of current node to the right side curr->left = nullptr; stringy(curr->right); } } //void stringy1(Node* curr) { // if (!curr) return; // else { // if (findMin(curr->left)) { // std::swap(curr->element, findMin(curr->left)->element); // if (findMin(curr->right)) { //finds minimum value of right side of tree // findMin(curr->right)->left = curr->left; //sets the left side of tree to the left side of right's minimum node // curr->left = nullptr; // } // else { // curr->right = curr->left; //if there is no elements to right, then just shift all the left side of current node to the right side // curr->left = nullptr; // } // } // else { // if (findMin(curr->right) && findMin(curr->right)->element < curr->element) { //if the root had no left tree, then find the minimum element in right tree // std::swap(curr->element , findMin(curr->right)->element); // } // } // stringy1(curr->right); // // } // } //stringy1() was a second attempt at part c but I could not get it to work properly. It only printed out half the stringy tree correctly. //I leave it here as a look into how I tried rethinking my original solution /////////////////////////////// int average_node_depth(Node* curr, int counter ) const { if (!curr) return -1; else return (average_node_depth(curr->left, counter++) + average_node_depth(curr->right, counter++) + counter) ; //returns the sum of the depths at each node } }; int main() { //1 ifstream lpv("Letter_point_value.txt"); if (!lpv) cerr << "Could not open file" << endl; vector<int> letterValues(26); char letter; int val; while (lpv >> val >> letter) { letterValues[(int)letter - 65] = val; } ifstream words("ENABLE.txt"); if (!words) cerr << "Could not open file" << endl; map<string, int> wordsWithFriends; string word; while (words >> word) { wordsWithFriends[word] = wordValue(word, letterValues); //adds point value to word key in the map //cout << word << " " << wordsWithFriends[word] << endl; } /////////////// //2 BinarySearchTree<int> bst; bst.insert(5); bst.insert(1); bst.insert(4); bst.insert(8); bst.insert(9); bst.insert(7); bst.insert(3); bst.insert(2); bst.insert(0); bst.insert(6); cout << endl; //a cout << "Contains 4? " << boolalpha << bst.contains(4) << endl; cout << "Contains 11? " << bst.contains(11) << noboolalpha << endl; //b cout << "print from 3 to 8 " << endl; bst.printRange(3, 8); cout << endl; cout << "print from 0 to 9 " << endl; bst.printRange(0, 9); cout << endl; //c BinarySearchTree<int> b = bst; b.stringy(); cout << "Stringy b "; b.printStringy(); //d cout << "Avg depth of tree bst " << bst.average_node_depth(10) << endl; cout << "Avg depth of stringy tree b " << b.average_node_depth(10) << endl; ///////////////// //3 cout << "Nodes in bst: "; bst.listNodes(); cout << "Nodes in b: "; b.listNodes(); cout << endl; //it runs in worst case O(n) because it will take roughly O(n) to go through every element in the queue //after it was filled. The while loop will take O(n) as well since it will need to be traversed through every element }<file_sep>//<NAME> //hw07 #include <string> #include <fstream> #include <iostream> #include "Tokenizer.cpp" #include <stack> using namespace std; struct Symbol { char token; int theLine; Symbol() {} Symbol(char tok, int line) : token(tok), theLine(line) {} }; class Balance { public: Balance(istream & is) :tok(is), errors(0) {} int checkBalance() { int errorCount = 0; stack<char> bal; char ch = tok.getNextOpenClose(); while (ch != '\0') { if (ch == '(' || ch == '[' || ch == '{') { bal.push(ch); } else if (ch == ')' || ch == ']' || ch == '}') { Symbol oParen(bal.top(), tok.getLineNumber()); Symbol cParen(ch, tok.getLineNumber()); if (bal.empty()) {//if a close parenthese has no open parentheses on the stack ++errorCount; cerr << "No matching open parenthese at line " << tok.getLineNumber() << endl; } else if (!checkMatch(oParen, cParen)) { ++errorCount; } else bal.pop(); } ch = tok.getNextOpenClose(); } if (!bal.empty()) { //if endOfFile is reached but the stack is not empty ++errorCount; cerr << "End of File reached but open parenthese not matched with closed" << endl; } return errorCount; }// returns the number of mismatched parenthesis private: Tokenizer tok; int errors; bool checkMatch(const Symbol& oParen, const Symbol& cParen) { if ((int)oParen.token + 1 != (int)cParen.token && (int)oParen.token + 2 != (int)cParen.token) { //checks ANSCII values for parentheses (they're adjacent values or off by 2 values on ANSCII table) cerr << "Error at line " << cParen.theLine << endl; return false; } return true; } }; int main() { ifstream someCode("code.txt"); Balance checkSomeCode(someCode); cout << "checkBalance() " << checkSomeCode.checkBalance() << endl; }<file_sep>//<NAME> //hw10b #include <iostream> #include <unordered_map> #include <list> #include <queue> #include <stack> #include <fstream> #include <sstream> #include <vector> #include <algorithm> using namespace std; //this code is from hw09 solutions class trainStopData { public: trainStopData(const string& id, const string& name, double lat, double lon) : stop_id(id), stop_name(name), stop_lat(lat), stop_lon(lon) {} string get_id() const { return stop_id; } string get_stop_name() const { return stop_name; } double get_latitude() const { return stop_lat; } double get_longitude() const { return stop_lon; } private: string stop_id; string stop_name; double stop_lat; double stop_lon; }; // Fill up all the keys with the stop_ids from MTA_train_stop_data void initializeMap(unordered_map < string, list<string> >& adjList) { // Open the MTA_train_stop_data.txt file ifstream stopFile("MTA_train_stop_data.txt"); if (!stopFile) { cerr << "The file for train stop data cannot be found.\n"; exit(1); } // Read the file line-by-line string line; getline(stopFile, line); // Note: I'm going to fill up a vector first, so that I can add adjacencies for stops on the same line // You don't have to do it this way, and this may not be the best approach vector<string> stops; while (getline(stopFile, line)) { // Get the stop_id, which is the first element on each line stringstream eachLine(line); string element; // We use comma-delimiting to get the stop_id, which is before the first comma // This will store the stop_id into element getline(eachLine, element, ','); // Get rid of the stops that have 'N' or 'S' after them // If you don't do this, it's totally fine, since it won't break the rest of our code // Note: I'm going to fill up a vector first, so that I can add adjacencies for stops on the same route // You don't have to do it this way, and this may not be the best approach if (element[element.size() - 1] != 'N' && element[element.size() - 1] != 'S') stops.push_back(element); } // Sort the vector of stops, so you ensure that all the stops on the same route are listed in order sort(stops.begin(), stops.end()); // At this point, I have a vector that's sorted in order, so the stops on the same line that are one stop away // from each other are listed together, in order. for (int i = 0; i < stops.size(); i++) { // Create the adjacency list for this stop list<string> adj; // For the first element, we can't check the element before us, so this is an edge case if (i == 0) { // Make sure that there's actually a next stop, and that the first character of that stop // is the same as the first character of this stop. If so, it's on the same route and we add // it to our adjacency list. if (stops.size() > 0 && stops[i][0] == stops[i + 1][0]) adj.push_back(stops[i + 1]); // For the last element, we can't check the element after us, so this is an edge case } else if (i == stops.size() - 1) { // Make sure that there's more than just one stop, and that the first character of the // last stop is the same as the first character of this stop (that means they're on the same route) if (stops.size() > 0 && stops[i - 1][0] == stops[i][0]) adj.push_back(stops[i - 1]); // Otherwise, check the element both before and after } else { // Add the previous stop if it's on the same route if (stops[i - 1][0] == stops[i][0]) adj.push_back(stops[i - 1]); // Add the following stop if it's on the same route if (stops[i][0] == stops[i + 1][0]) adj.push_back(stops[i + 1]); } // Insert this stop into the map adjList.insert({ stops[i], adj }); } stopFile.close(); } // Add the transfers to each adjacency list void addTransfers(unordered_map < string, list<string> >& adjList) { // Open the transfers.txt file ifstream transfersFile("transfers.txt"); if (!transfersFile) { cerr << "The file for train stop data cannot be found.\n"; exit(1); } // Read the file line-by-line string line; getline(transfersFile, line); while (getline(transfersFile, line)) { // Get the first two elements in each line stringstream eachLine(line); string fromStop; string toStop; // Get the from_stop_id getline(eachLine, fromStop, ','); // Get the to_stop_id getline(eachLine, toStop, ','); // Add the toStop to the adjacency list of the fromStop // Make sure that the two are different stops if (fromStop != toStop) adjList[fromStop].push_back(toStop); } transfersFile.close(); } void printList(const list<string>& ls) { for (list<string>::const_iterator a = ls.begin(); a != ls.end(); a++) cout << *a << " "; cout << endl; } //2 //this is the provided code for hw10, modified to handle the adjacency list solution from hw09 const int DEFAULT_VAL = -1; // must be less than 0 typedef unordered_map < string, list<string> > Graph; // The graph is given in an adjacency list. // Vertices are indexed from 0 to V-1 // The indices of the vertices adjacent to vertex i // are in the list Graph[i]. // Graph can be directed or undirected. struct vertexInf // Stores information for a vertex { int dist; // distance to vertex from the source string prev; // previous node in BFS tree }; void printpath(const string& j, unordered_map<string, vertexInf> & vinfo) { stack<string> t; string current = j; while (current != string()) { t.push(current); current = vinfo[current].prev; } while (!t.empty()) { cout << t.top() << " "; t.pop(); } } // Breadth First Search // The unweighted shortest path algorithm on the graph g, with vertex i as the source // Prints the length (number of edges) of the shortest path from the source to every vertex // in the graph void shortestpaths(Graph & g, const string& s) { //string must be key inside graph queue<string> q; // q is the queue of vertex numbers unordered_map<string, vertexInf> vertices(g.size()); // stores BFS info for the vertices for (unordered_map<string, list<string>>::iterator w = g.begin(); w != g.end(); w++) // Initialize distances and prev values { vertices[w->first].dist = DEFAULT_VAL; vertices[w->first].prev = string(); } vertices[s].dist = 0; q.push(s); while (!q.empty()) { string v = q.front(); q.pop(); for (list<string>::iterator w = g[v].begin(); w != g[v].end(); w++) { if (vertices[*w].dist == DEFAULT_VAL) // distance of *w from source not determined yet { vertices[*w].dist = vertices[v].dist + 1; vertices[*w].prev = v; q.push(*w); } } } for (unordered_map<string, list<string>>::iterator w = g.begin(); w != g.end(); w++) // print distances from source and paths { cout << "vertex " << w->first << endl; cout << "distance: " << vertices[w->first].dist << endl; cout << "shortest path: "; printpath(w->first, vertices); cout << endl; } } int main() { unordered_map < string, list<string> > adjList; initializeMap(adjList); addTransfers(adjList); shortestpaths(adjList, "635"); cout << "140: "; printList(adjList.find("140")->second); cout << "S13: "; printList(adjList.find("S13")->second); } <file_sep>//<NAME> #include <vector> #include <iostream> #include "time.h" #include "Math.h" using namespace std; class timer { public: timer() : start(clock()) {} double elapsed() { return (clock() - start) / CLOCKS_PER_SEC; } void reset() { start = clock(); } private: double start; }; /** * Cubic maximum contiguous subsequence sum algorithm. */ int maxSubSum1(const vector<int> & a) { int maxSum = 0; for (size_t i = 0; i < a.size(); ++i) for (size_t j = i; j < a.size(); ++j) { int thisSum = 0; for (size_t k = i; k <= j; ++k) thisSum += a[k]; if (thisSum > maxSum) maxSum = thisSum; } return maxSum; } /** * Quadratic maximum contiguous subsequence sum algorithm. */ int maxSubSum2(const vector<int> & a) { int maxSum = 0; for (size_t i = 0; i < a.size(); ++i) { int thisSum = 0; for (size_t j = i; j < a.size(); ++j) { thisSum += a[j]; if (thisSum > maxSum) maxSum = thisSum; } } return maxSum; } /** * Linear-time maximum contiguous subsequence sum algorithm. */ int maxSubSum4(const vector<int> & a) { int maxSum = 0, thisSum = 0; for (size_t j = 0; j < a.size(); ++j) { thisSum += a[j]; if (thisSum > maxSum) maxSum = thisSum; else if (thisSum < 0) thisSum = 0; } return maxSum; } void funcA(int n) { int sum = 0; for (int i = 0; i < n; i++) ++sum; } void funcB(int n) { int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; ++j) ++sum; } void funcC(int n) { int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < i; ++j) ++sum; } void funcD(int n) { int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; ++j) for (int k = 0; k < n; ++k) ++sum; } int main() { timer t; double nuClicks; vector<int> items; cout.setf(ios::fixed, ios::floatfield); cout.precision(12); cout << CLOCKS_PER_SEC << endl << endl; //Question 1 for (size_t i = 0; i < pow(2, 7); i++) { //n = 2^7 (I implemented the Math library to save writing) int x = (rand() % 2001) - 1000; items.push_back(x); } cout << "n = 2^7" << endl; t.reset(); maxSubSum1( items ); nuClicks = t.elapsed(); cout << "Cubic: " << nuClicks << endl; t.reset(); maxSubSum2(items); nuClicks = t.elapsed(); cout << "Quadratic: " << nuClicks << endl; t.reset(); maxSubSum4(items); nuClicks = t.elapsed(); cout << "Linear: " << nuClicks << endl; items.clear(); cout << "=======================" << endl; for (size_t i = 0; i < pow(2, 8); i++) { //n = 2^8 (I implemented the Math library to save writing) int x = (rand() % 2001) - 1000; items.push_back(x); } cout << "n = 2^8" << endl; t.reset(); maxSubSum1(items); nuClicks = t.elapsed(); cout << "Cubic: " << nuClicks << endl; t.reset(); maxSubSum2(items); nuClicks = t.elapsed(); cout << "Quadratic: " << nuClicks << endl; t.reset(); maxSubSum4(items); nuClicks = t.elapsed(); cout << "Linear: " << nuClicks << endl; items.clear(); cout << "=======================" << endl; for (size_t i = 0; i < pow(2, 9); i++) { //n = 2^9 (I implemented the Math library to save writing) int x = (rand() % 2001) - 1000; items.push_back(x); } cout << "n = 2^9" << endl; t.reset(); maxSubSum1(items); nuClicks = t.elapsed(); cout << "Cubic: " << nuClicks << endl; t.reset(); maxSubSum2(items); nuClicks = t.elapsed(); cout << "Quadratic: " << nuClicks << endl; t.reset(); maxSubSum4(items); nuClicks = t.elapsed(); cout << "Linear: " << nuClicks << endl; items.clear(); cout << "=====================" << endl; for (size_t i = 0; i < pow(2, 10); i++) { //n = 2^10 (I implemented the Math library to save writing) int x = (rand() % 2001) - 1000; items.push_back(x); } cout << "n = 2^10" << endl; t.reset(); maxSubSum1(items); nuClicks = t.elapsed(); cout << "Cubic: " << nuClicks << endl; t.reset(); maxSubSum2(items); nuClicks = t.elapsed(); cout << "Quadratic: " << nuClicks << endl; t.reset(); maxSubSum4(items); nuClicks = t.elapsed(); cout << "Linear: " << nuClicks << endl; items.clear(); cout << "=====================" << endl; for (size_t i = 0; i < pow(2, 11); i++) { //n = 2^11 (I implemented the Math library to save writing) int x = (rand() % 2001) - 1000; items.push_back(x); } cout << "n = 2^11" << endl; t.reset(); maxSubSum1(items); nuClicks = t.elapsed(); cout << "Cubic: " << nuClicks << endl; t.reset(); maxSubSum2(items); nuClicks = t.elapsed(); cout << "Quadratic: " << nuClicks << endl; t.reset(); maxSubSum4(items); nuClicks = t.elapsed(); cout << "Linear: " << nuClicks << endl; items.clear(); cout << "=====================" << endl; for (size_t i = 0; i < pow(2, 12); i++) { //n = 2^12 (I implemented the Math library to save writing) int x = (rand() % 2001) - 1000; items.push_back(x); } cout << "n = 2^12" << endl; t.reset(); maxSubSum1(items); nuClicks = t.elapsed(); cout << "Cubic: " << nuClicks << endl; t.reset(); maxSubSum2(items); nuClicks = t.elapsed(); cout << "Quadratic: " << nuClicks << endl; t.reset(); maxSubSum4(items); nuClicks = t.elapsed(); cout << "Linear: " << nuClicks << endl; items.clear(); //============================ //Question 2 cout << "===================" << endl; for (int i = 256; i <= 4096; i *= 2) { cout << "n = " << i << endl; t.reset(); funcA(i); //2A nuClicks = t.elapsed(); cout << "2A: " << nuClicks << endl; t.reset(); funcB(i); //2B nuClicks = t.elapsed(); cout << "2B: " << nuClicks << endl; t.reset(); funcC(i); //2C nuClicks = t.elapsed(); cout << "2C: " << nuClicks << endl; t.reset(); funcD(i); //2D nuClicks = t.elapsed(); cout << "2D: " << nuClicks << endl; } }<file_sep>//<NAME> //hw10 question 2 #include <iostream> #include <unordered_map> #include <list> #include <fstream> #include <sstream> #include <vector> #include <queue> #include <stack> #include <algorithm> using namespace std; class trainStopData; const int DEFAULT_VAL = -1; class MTA { public: MTA() {} MTA(const string& fileName); //see definitions below trainStopData class for all the methods typedef list<trainStopData>::iterator itr; itr findTrainStop(const string& id); void shortestpaths(const trainStopData& s); void addNewLine(const string& newLineFile, const string& newTransfersFile); protected: unordered_map<char, list<trainStopData>> data; //needs to be protected in order for trainStopData class to be able to use the unordered_map }; //this code is from the previous hw09 solution with some personal changes class trainStopData { friend bool operator<(const trainStopData& lhs, const trainStopData& rhs); //see function definition below class friend ostream& operator<<(ostream& os, const trainStopData& rhs); public: trainStopData(const string& id, const string& name, double lat, double lon, const string& transfers = "transfers.txt") : stop_id(id), stop_name(name), stop_lat(lat), stop_lon(lon), transferFile(transfers) { addTransfers(); } trainStopData(const trainStopData& rhs) { stop_id = std::move(rhs.stop_id); stop_name = std::move(rhs.stop_name); stop_lat = std::move(rhs.stop_lat); stop_lon = std::move(rhs.stop_lon); } string get_id() const { return stop_id; } string get_stop_name() const { return stop_name; } double get_latitude() const { return stop_lat; } double get_longitude() const { return stop_lon; } int numOfAdjacentStations() const { return adjList.size(); } private: string stop_id; string stop_name; double stop_lat; double stop_lon; string transferFile; list<trainStopData> adjList; //this is an adjacency list for every trainStop }; void addTransfers(MTA data) { ifstream transfersFile(transferFile); if (!transfersFile) { cerr << "The file for train stop data cannot be found.\n"; exit(1); } // Read the file line-by-line string line; getline(transfersFile, line); while (getline(transfersFile, line)) { // Get the first two elements in each line stringstream eachLine(line); string fromStop; string toStop; // Get the from_stop_id getline(eachLine, fromStop, ','); // Get the to_stop_id getline(eachLine, toStop, ','); // Add the toStop to the adjacency list of the fromStop // Make sure that the two are different data if (fromStop != toStop && fromStop == stop_id) { /* && MTA::findTrainStop(toStop) != data[stop_id[0]].end()*/ trainStopData to = *data.findTrainStop(toStop); adjList.push_back(to); } transfersFile.close(); } cout << stop_name << endl; for (list<trainStopData>::iterator start = adjList.begin(); start != adjList.end(); start++) { cout << *start << endl; } cout << endl; } ostream& operator<<(ostream& os, const trainStopData& rhs) { os << rhs.stop_name; return os; } ////////////////////////////// //MTA CLASS METHOD DEFINITIONS ////////////////////////////// MTA::MTA(const string& fileName) { ifstream ifs; ifs.open(fileName); if (!ifs) { //checks if file exists cerr << "Could not open MTA file" << endl; exit(1); } string id = "", name = ""; double lat = 0, lon = 0; string dumb = ""; //place holder int count = 0; //counts what piece of info being read (going in order of member variable list 1-4) getline(ifs, dumb); //goes through first line which doesn't contain any relevant data while (getline(ifs, dumb, ',')) { if (dumb != "") { //checks to make sure the variable isn't empty string ++count; if (count == 1) { id = dumb; } else if (count == 2) { name = dumb; } else if (count == 3) { lat = stod(dumb); //converts string to double } else if (count == 4) { count = 0; lon = stod(dumb); //converts string to double if (id[3] < 65) { trainStopData tsd(id, name, lat, lon); data[id[0]].push_back(tsd); //adds the station name to the id key } getline(ifs, dumb); //brings to next line } } } ifs.close(); } typedef list<trainStopData>::iterator itr; itr MTA::findTrainStop(const string& id) { char trainLine = id[0]; itr start = data[trainLine].begin(); while (start != data[trainLine].end()) { if (start->get_id() == id) return start; ++start; } return start; } void MTA::shortestpaths(const trainStopData& tStop) { //train stop must exist //struct vertexInf { // Stores information for a vertex // int dist; // distance to vertex from the source // int prev; // previous node in BFS tree //}; //queue<int> q; // q is the queue of vertex numbers //vector<vertexInf> vertices(data.size()); // stores BFS info for the vertices // // info for vertex j is in position j //for (int j = 0; j < vertices.size(); ++j) { // vertices[j].dist = DEFAULT_VAL; vertices[j].prev = DEFAULT_VAL; //} //vertices[s].dist = 0; //q.push(s); //while (!q.empty()) //{ // int v = q.front(); // q.pop(); // for (list<string>::const_iterator w = g[v].begin(); w != g[v].end(); w++) // { // if (vertices[*w].dist == DEFAULT_VAL) // distance of *w from source not determined yet // { // vertices[*w].dist = vertices[v].dist + 1; // vertices[*w].prev = v; // q.push(*w); // } // } //} //for (int j = 0; j < vertices.size(); j++) { // print distances from source and paths // cout << "vertex " << j << endl; // cout << "distance: " << vertices[j].dist << endl; // cout << "shortest path: "; // stack<trainStopData> t; // trainStopData current = j; // while (current != DEFAULT_VAL){ // t.push(current); // current = vinfo[current].prev; // } // while (!t.empty()){ // cout << t.top() << " "; // t.pop(); // } // cout << endl; //} } void MTA::addNewLine(const string& newLineFile, const string& newTransfersFile) { //passing in file containing trainStopData for a new line (such as the future T line on 2nd Ave) as well as file for all the transfers for new line ifstream ifs(newLineFile); if (!ifs) { //checks if file exists cerr << "Could not open file TSD" << endl; exit(0); } string id = "", name = ""; double lat = 0, lon = 0; string dumb = ""; //place holder int count = 0; //counts what piece of info being read (going in order of member variable list 1-4) getline(ifs, dumb); //goes through first line which doesn't contain any relevant data while (getline(ifs, dumb, ',')) { if (dumb != "") { //checks to make sure the variable isn't empty string ++count; if (count == 1) { id = dumb; } else if (count == 2) { name = dumb; } else if (count == 3) { lat = stod(dumb); //converts string to double } else if (count == 4) { count = 0; lon = stod(dumb); //converts string to double if (id[3] < 65) { trainStopData tsd(id, name, lat, lon, newTransfersFile); //passes in an updated transfers file needed for finding the adjacent stations data[id[0]].push_back(tsd); //adds the station name to the id key } getline(ifs, dumb); //brings to next line } } } ifs.close(); } int main() { //this code is from the previous hw string MTAfilename = "MTA_train_stop_data.txt"; MTA mta(MTAfilename); list<trainStopData>::iterator stop = mta.findTrainStop("306"); //id must exist //mta.shortestpaths(*stop); } <file_sep>//<NAME> //HW02 #include <vector> #include <iostream> using namespace std; class IntArray { public: //constructor explicit IntArray(int n = 0) : size(n), array(new int[n]) { cout << "Constructor" << endl; } //copy constructor IntArray(const IntArray& rhs) : size(rhs.size), array(new int[rhs.size]) { for (int i = 0; i < size; i++) { array[i] = rhs.array[i]; } cout << "Copy Constructor" << endl; } //move copy constructor IntArray(IntArray&& rhs) : array(rhs.array), size(rhs.size) { rhs.array = nullptr; cout << "Move Copy Constructor" << endl; } //destructor ~IntArray() { delete[] array; cout << "Destructor" << endl; } //move assignment operator IntArray& operator=(IntArray&& rhs) { //int* temp = array; //array = rhs.array; //rhs.array = temp; std::swap(array, rhs.array); size = rhs.size; cout << "Move Assignment Operator" << endl; return *this; } private: int * array; int size; }; int main() { IntArray a(4); IntArray b(a); IntArray c = IntArray(2); //does not call correct constructor (not sure why) a = IntArray(3); } <file_sep>//<NAME> //hw09 #include <iostream> #include <vector> #include <fstream> #include <string> #include <list> #include <unordered_map> using namespace std; template< class HashedObj > class HashTable { public: explicit HashTable(int size = 101) :currentSize(0) { arr.resize(size); } std::hash<HashedObj> hf; // create a hash function object void makeEmpty() { arr.clear(); currentSize = 0; } bool find(const HashedObj& x){ size_t i = hf(x) % arr.size(); size_t pos = i; //holds starting position while (arr[i].element != x) { if (i == arr.size() - 1) i = -1; //if the current position is the size of the arr ++i; if (i == pos) { //if all the positions are active in the arr (current pos = starting pos) return false; } } return true; } bool insert(const HashedObj & x) { if (find(x)) return false; size_t i = hf(x) % arr.size(); HashEntry h(x, ACTIVE); if (arr[i].info != 0) arr[i] = h; else { size_t pos = i; //holds starting position while (arr[i].info == 0) { if (i == arr.size()) i = -1; //if the current position is the size of the arr ++i; if (i == pos) { //if all the positions are active in the arr (current pos = starting pos) rehash(); } } arr[i] = h; } if (++currentSize >= arr.size() * MAXLOADFACTOR) rehash(); return true; } bool remove(const HashedObj & x){ size_t i = hf(x) % arr.size(); vector<HashEntry>::iterator itr = std::find(arr.begin(), arr.end(), x); if (itr == arr.end()) return false; arr.erase(itr); --currentSize; return true; } enum EntryType { ACTIVE, EMPTY, DELETED }; private: struct HashEntry { HashedObj element; EntryType info; HashEntry(const HashedObj & e = HashedObj(), EntryType i = EMPTY) : element(e), info(i) {} bool operator==(const HashedObj& x) { return element == x; } }; vector<HashEntry> arr; int currentSize; double MAXLOADFACTOR = 0.5; void rehash() { vector< HashEntry > oldarr = std::move(arr); makeEmpty(); arr.resize(2 * oldarr.size() + 1); // better to resize to a prime size for (size_t i = 0; i < oldarr.size(); i++){ arr.push_back(std::move(oldarr[i])); } } }; void fillData(unordered_map<char, list<pair<string, string>>>& data) { ifstream ifstr; ifstr.open("MTA_train_stop_data.txt"); if (!ifstr) { //checks if file exists cerr << "Could not open file" << endl; } string id, name; string dumb = ""; //place holder int count = 0; //counts what piece of info being read (going in order of member variable list 1-4) getline(ifstr, dumb); //goes through first line which doesn't contain any relevant data while (getline(ifstr, dumb, ',')) { if (dumb != "") { //checks to make sure the variable isn't empty string ++count; if (count == 1) { id = dumb; } else if (count == 2) { name = dumb; } else if (count == 4) { count = 0; if (id[3] < 65) { data[id[0]].push_back(pair<string, string>(id, name)); //adds the station name to the id key } getline(ifstr, dumb); //brings to next line } } } ifstr.close(); } pair<string, string> findAdjacent(list<pair<string, string>>& trainLines, const string& id) { //will either return an iterator to the following station or return end() typedef list<pair<string, string>>::iterator itr; itr start = trainLines.begin(); if (start->first == id) { itr next = ++start; return pair<string, string>(".", next->second); } while (start->first != id) { if (start == trainLines.end()) { itr prev = --start; return pair<string, string>(prev->second, "."); } ++start; } itr copy = start; if (start != trainLines.end()) { return pair<string, string>((--start)->second, (copy++)->second); } else { return pair<string, string>((--start)->second, "."); } } string findStationName(list<pair<string, string>>& trainLines, const string& id) { list<pair<string, string>>::iterator start = trainLines.begin(); while (start->first != id) { start++; } return start->second; } int main() { //1 HashTable<int> ht(10); cout << "insert() " << boolalpha << ht.insert(3) << endl; ht.insert(5); ht.insert(23); ht.insert(41); ht.insert(15); cout << "remove() " << ht.remove(23) << endl;; cout << "find() " << ht.find(3) << endl; cout << "find() " << ht.find(23) << noboolalpha << endl; ////////////////////////////////////// //2 ////////////////////////////////////// unordered_map<char, list<pair<string, string>>> data; //creates this map with the train line as a char and then the list of stops on the line and their ids as a list of pairs (station name and id) //makes for O(1) find and insert fillData(data); for (auto& x : data) { //checking data stored in train stop data unordered_map cout << x.first << ": "; for (auto& s : x.second) { cout << s.first << ", "; // << s.second << " "; } cout << endl; } cout << "start" << endl; unordered_map<string, list<string>> transfers; ifstream ifs("transfers.txt"); if (!ifs) //checks if file exists cerr << "Cannot open ifs"; string s; getline(ifs, s); //removes the first like that just holds string idetifiers for the different columns of data string from, to; //these are ids for the stations while (getline(ifs, s)) { from = s.substr(0, 3); to = s.substr(4, 3); pair<string, string> adjStations = findAdjacent(data[from[0]], to); if (adjStations.first != ".") transfers[findStationName(data[from[0]], from)].push_back(adjStations.first); //places the previous station's name into the current station's list of adjacent stations if (adjStations.second != ".") transfers[findStationName(data[from[0]], from)].push_back(adjStations.second); //places the next station's name into the current station's list of adjacent stations } ifs.close(); for (auto& x : transfers) { if (x.second.begin() != x.second.end()) { //only prints out stations where there are transfers cout << x.first << ": "; for (auto& s : x.second) { cout << s << "; "; } cout << endl; } } }<file_sep>//<NAME> #include <vector> #include <iostream> #include <fstream> #include <string> #include <queue> #include <stack> using namespace std; class Maze { private: vector<vector<char>> maze; //creates matrix class Coordinates { //way of storing location in matrix public: Coordinates(int x, int y) : x(x), y(y) {} Coordinates(const Coordinates& rhs) : x(rhs.x), y(rhs.y) {} bool above, below, left, right = false; //stores if any location around the point is a possible path to take (for stack/ queue implementation) void setX(int row) { x = row; } void setY(int col) { y = col; } int getX() const { return x; } int getY() const { return y; } bool operator==(const Coordinates& rhs) { return x == rhs.x && y == rhs.y; } private: int x; int y; }; public: Maze(ifstream& ifs) { createMaze(ifs); } void createMaze(ifstream& ifs) { string line; while (getline(ifs, line)) { //takes each line from the file vector<char> charVec; for (size_t i = 0; i < line.length(); i++) { charVec.push_back(*line.substr(i, 1).c_str()); //places X or . in correct spot in matrix } maze.push_back(charVec); //adds each line to the maze } } bool inRange(const vector<vector<char>>& maze, Coordinates point) { if (point.getX() < maze.size() && -1 < point.getX() && point.getY() < maze[0].size() && -1 < point.getY()) { return true; } return false; } //e must be located someplace inside maze in reachable location void recLocation(Coordinates curr, Coordinates prev) { try { if (maze[curr.getX()][curr.getY()] == 'e') { cout << "Location, Row: " << curr.getX() << " Column: " << curr.getY() << endl; throw "a"; return; } } catch (string s) { //was not able to get my program to end without this try/catch block oops LOL return; } cout << "Row Col" << endl; cout << curr.getX() << " " << curr.getY() << endl; cout << prev.getX() << " " << prev.getY() << endl << endl; Coordinates below(curr.getX() + 1, curr.getY()); if (inRange(maze, below) && !(below == prev) && (maze[curr.getX() + 1][curr.getY()] == '.' || maze[curr.getX() + 1][curr.getY()] == 'e')) { //else { cerr << "Moved down" << endl; recLocation(below, curr); } Coordinates right(curr.getX(), curr.getY() + 1); if (inRange(maze, right) && !(right == prev) && (maze[curr.getX()][curr.getY() + 1] == '.' || maze[curr.getX()][curr.getY() + 1] == 'e')) { cerr << "Moved right" << endl; recLocation(right, curr); } Coordinates above(curr.getX() - 1, curr.getY()); if (inRange(maze, above) && !(above == prev) && (maze[curr.getX() - 1][curr.getY()] == '.' || maze[curr.getX() - 1][curr.getY()] == 'e')) { cerr << "Moved up" << endl; recLocation(above, curr); } Coordinates left(curr.getX(), curr.getY() - 1); if (inRange(maze, left) && !(left == prev) && (maze[curr.getX()][curr.getY() - 1] == '.' || maze[curr.getX()][curr.getY() - 1] == 'e')) { cerr << "Moved left" << endl; recLocation(left, curr); } } Coordinates findLocation() { Coordinates start(0, 0); for (size_t row = 0; row < maze.size(); row++) { for (size_t col = 0; col < maze[row].size(); col++) { //finding location of s using brute force if (maze[row][col] == 's') { start = Coordinates(row, col); return start; } } } return start; } bool isIntersection(Coordinates curr) { bool isInt = false; Coordinates b(curr.getX() + 1, curr.getY()); Coordinates r(curr.getX(), curr.getY() + 1); Coordinates a(curr.getX() - 1, curr.getY()); Coordinates l(curr.getX(), curr.getY() - 1); if ((inRange(maze, b) && maze[b.getX()][b.getY()] != 'x' && curr.below == false)) { curr.below = true; isInt == true; } if ((inRange(maze, a) && maze[a.getX()][a.getY()] != 'x' && curr.above == false)) { curr.above = true; isInt == true; } if ((inRange(maze, l) && maze[l.getX()][l.getY()] != 'x' && curr.left == false)) { curr.left = true; isInt = true; } if ((inRange(maze, r) && maze[r.getX()][r.getY()] != 'x' && curr.right == false)) { curr.right = true; isInt = true; } return isInt; } void stackLocation(Coordinates curr) { stack<Coordinates> path; stack<Coordinates> intersections; path.push(curr); if (isIntersection(curr)) path.push(curr); while (!path.empty() && maze[path.top().getX()][path.top().getY()] != 'e') { Coordinates below(curr.getX() + 1, curr.getY()); curr = below; //current location is now one below previous location while (inRange(maze, curr) && (maze[curr.getX()][curr.getY()] == '.' || maze[curr.getX()][curr.getY()] == 'e')) { curr.below = true; cerr << "Moved down" << endl; path.push(curr); if (isIntersection(curr)) intersections.push(curr); curr.setX(curr.getX() + 1); //keeps moving down while it is able to move there } curr.below = false; Coordinates right(curr.getX(), curr.getY() + 1); curr = right; while (inRange(maze, curr) && (maze[curr.getX()][curr.getY()] == '.' || maze[curr.getX()][curr.getY()] == 'e')) { curr.right = true; cerr << "Moved right" << endl; path.push(curr); if (isIntersection(curr)) intersections.push(curr); curr.setY(curr.getY() + 1); } curr.right = false; Coordinates above(curr.getX() - 1, curr.getY()); curr = above; while (inRange(maze, curr) && (maze[curr.getX()][curr.getY()] == '.' || maze[curr.getX()][curr.getY()] == 'e')) { curr.above = true; cerr << "Moved up" << endl; path.push(curr); if (isIntersection(curr)) intersections.push(curr); curr.setX(curr.getX() - 1); } curr.above = false; Coordinates left(curr.getX(), curr.getY() - 1); curr = left; while (inRange(maze, curr) && (maze[curr.getX()][curr.getY()] == '.' || maze[curr.getX()][curr.getY()] == 'e')) { curr.left = true; cerr << "Moved left" << endl; path.push(curr); if (isIntersection(curr)) intersections.push(curr); curr.setY(curr.getY() - 1); } curr.left = false; if (maze[curr.getX()][curr.getY()] != 'e'){ while (!(path.top() == intersections.top())) { path.pop(); } } curr = path.top(); } cout << curr.getX() << " " << curr.getY() << endl; } void print_maze() { for (size_t row = 0; row < maze.size(); row++) { for (size_t col = 0; col < maze[row].size(); col++) { //finding location of s using brute force cout << maze[row][col]; } cout << endl; } } }; int main() { Maze myMaze(ifstream("maze.txt")); myMaze.recLocation(myMaze.findLocation(), myMaze.findLocation()); myMaze.print_maze(); //myMaze.stackLocation(myMaze.findLocation()); }
f22b198ef9ae8b971ee99f2d7416be45b6498a0d
[ "C++" ]
16
C++
mattavallone/CS2134-Data-Structures-And-Algorithms
979a62ab1d20df95947b228f649dab5d5f4f8f28
9fefe9178f738129385dbbccd1d9c7b32b633f30
refs/heads/master
<file_sep>package com.example.crawler; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.example.crawler.adapter.ZhiLianAdapter; import com.example.crawler.bean.ZhiLianBean; import com.example.crawler.utils.ExcelUtils; import com.example.crawler.utils.ToastUtil; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MainActivity extends BaseActivity { private TextView textView = null; private ListView listView = null; private Button button = null; private Handler handler = new Handler(); ExecutorService executorService; String url = "http://sou.zhaopin.com/jobs/searchresult.ashx?jl=长沙&kw=注册会计师&sm=0&sg=cd73d4b7281248829da3fa422ce9f43f&p="; private ArrayList<ZhiLianBean> zhiLianBeanArrayList = new ArrayList<>(); private int position = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setViews(); executorService = Executors.newFixedThreadPool(1); executorService.execute(new Runnable() { public void run() { for(int i = 0;i<6;i++){ parseWEBHtml(); position++; } } }); } @Override protected void onDestroy() { super.onDestroy(); executorService.shutdown(); } private void parseHTML() { /** * 解析HTML标签 */ String html = "<html><head><title>First parse</title></head>" + "<body><p id='aaa'>Parsed HTML into a doc.</p></body></html>"; Document doc = Jsoup.parse(html); // textView.setText(doc.getElementById("aaa").text()); // textView.setText(doc.getElementsByTag("p").text()); textView.setText(doc.body().text()); } private void setViews() { textView = (TextView) findViewById(R.id.text); textView.setText("正在加载"); listView = (ListView) findViewById(R.id.listview); button=(Button) findViewById(R.id.create_excel); button.setEnabled(false); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { button.setEnabled(false); new AsyncTask<Void,Void,Void>(){ @Override protected Void doInBackground(Void... voids) { createExcel(); return null; } }.execute(); } }); //parseHTML(); } private void createExcel() { final String path = Environment.getExternalStorageDirectory().getPath()+"/注册会计师.xls"; File file = new File(path); if(file.exists()){ file.delete(); } ExcelUtils.writeExcel(path,"智联招聘",zhiLianBeanArrayList); runOnUiThread(new Runnable() { @Override public void run() { ToastUtil.getInstance(getApplicationContext()).showLongToast("生成excel成功,存储路径 :"+path); button.setEnabled(true); } }); } private void parseWEBHtml() { /** * 1.公司名称标签:gsmc * 2.薪水标签: zwyx * 3.岗位职责标签: newlist_deatil_last */ try { final Document doc = Jsoup.connect(url+position).get(); final Elements eJob = doc.getElementsByClass("zwmc"); final Elements eCompany = doc.getElementsByClass("gsmc"); final Elements eSalary = doc.getElementsByClass("zwyx"); final Elements eRes = doc.getElementsByClass("newlist_deatil_last"); Log.d("jxd","aaa : "+eCompany.text()); for(int i = 0; i<eCompany.size()&&i<eSalary.size()&&i<eRes.size();i++){ ZhiLianBean z = new ZhiLianBean(); z.setJobs(eJob.get(i+1).text().trim()); z.setCompanyName(eCompany.get(i+1).text().trim()); z.setSalary(eSalary.get(i+1).text().trim()); z.setResponsibilities(eRes.get(i).text().trim()); zhiLianBeanArrayList.add(z); } if(position == 5){ runOnUiThread(new Runnable() { @Override public void run() { /** * 网页标题 doc.title() * 网页内容 doc.body().text() */ button.setEnabled(true); textView.setVisibility(View.GONE); ZhiLianAdapter zhiLianAdapter = new ZhiLianAdapter(MainActivity.this,zhiLianBeanArrayList); listView.setAdapter(zhiLianAdapter); // textView.setText(elements.text()); } }); } } catch (IOException e) { e.printStackTrace(); } } @Override public void initData() { // new Thread(new Runnable() { // @Override // public void run() { // try { // //还是一样先从一个URL加载一个Document对象。 // Document doc = Jsoup.connect("http://home.meishichina.com/recipe.html").get(); // // Elements elements = doc.getElementsByTag("top-bar"); // for(Element e : elements) { // System.out.println(e.text()); // } // // // }catch(Exception e) { // Log.i("mytag", e.toString()); // } // } // }).start(); } } <file_sep>apply plugin: 'com.android.application' android { compileSdkVersion 24 defaultConfig { applicationId "com.example.crawler" minSdkVersion 15 targetSdkVersion 24 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' applicationVariants.all { variant -> variant.getPackageApplication().outputDirectory = new File(outputDir()) variant.outputs.all { output -> if (variant.buildType.name.equals('release') || variant.buildType.name.equals('debug')) { outputFileName = "Crawler.apk" } } } } } } def outputDir() { return project.buildDir.absolutePath + "/outputs/apk" } dependencies { implementation 'org.jsoup:jsoup:1.9.2' implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.hynnet:jxl:2.6.12.1' } <file_sep># Crawler android爬取某招聘网站数据并保存至excel,学习知识点android jsoup 和jxl框架 <file_sep>package com.example.crawler.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.crawler.R; import com.example.crawler.bean.ZhiLianBean; import java.util.ArrayList; /** * Created by jingxiongdi on 2018/4/17. */ public class ZhiLianAdapter extends BaseAdapter { private LayoutInflater mInflater; private Context mContext; private ArrayList<ZhiLianBean> zhiLianBeans = null; public ZhiLianAdapter(Context c,ArrayList list){ mContext = c; zhiLianBeans = list; mInflater = LayoutInflater.from(mContext); } @Override public int getCount() { return zhiLianBeans.size(); } @Override public Object getItem(int position) { return zhiLianBeans.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); if (viewHolder != null) { convertView = mInflater.inflate(R.layout.list_item_zhilian, null); viewHolder.companyName = (TextView) convertView.findViewById(R.id.company_name); viewHolder.salary = (TextView) convertView.findViewById(R.id.salary); viewHolder.jobs = (TextView) convertView.findViewById(R.id.jobs); viewHolder.responsibilities = (TextView) convertView.findViewById(R.id.responsibilities); convertView.setTag(viewHolder); } } else { viewHolder = (ViewHolder) convertView.getTag(); } ZhiLianBean zhiLianBean = zhiLianBeans.get(position); viewHolder.companyName.setText(zhiLianBean.getCompanyName()); viewHolder.jobs.setText(zhiLianBean.getJobs()); viewHolder.salary.setText(zhiLianBean.getSalary()); viewHolder.responsibilities.setText(zhiLianBean.getResponsibilities()); return convertView; } private static class ViewHolder { private TextView companyName; private TextView jobs; private TextView salary; private TextView responsibilities; } }
e2a27778b0d3ea76abe2359f49f5762f2857172f
[ "Markdown", "Java", "Gradle" ]
4
Java
jingxiongdi/Crawler
f86ba03d980c95a1ab37564db67d78d37dc73313
1fc83bcc438ba872b2735ebcc75b62c97a7c06cc
refs/heads/master
<file_sep>// // ManagedObject.swift // Griddle // // Created by <NAME> on 6/6/15. // Copyright (c) 2015 Inlined. All rights reserved. // import Foundation import Eventful import Firebase protocol UnsafeYielder { func yieldUnsafe(val: AnyObject!) } public class Property<T : AnyObject> : Observable<T>, UnsafeYielder { var target: ManagedObject! let keyPath: String public init(keyPath: String) { self.keyPath = keyPath } public func bind(target: ManagedObject) { assert(self.target == nil) self.target = target } func yieldUnsafe(val: AnyObject!) { yield(val as? T) } func set(val: T!) { target.set(val, forKeyPath:keyPath) } } infix operator <- { assignment } func <-<T : AnyObject>(property: Property<T>, val: T!) { property.set(val) } public class ManagedObject { private var serverData = FDataSnapshot() private var dirtyData = [String:AnyObject]() private var yielders = [String:UnsafeYielder]() private var ref : Firebase! private var eventHandle: UInt = 0 public init(atURL: String) { ref = Firebase(url:atURL) eventHandle = ref.observeEventType(.Value, withBlock: { [unowned self] snapshot in self.updateSnapshot(snapshot) }) } func get(keyPath: String) -> AnyObject? { if let dirtyVal: AnyObject = dirtyData[keyPath] { if dirtyVal is NSNull { return nil } return dirtyVal } return serverData.valueForKeyPath(keyPath) } func set(value: AnyObject!, forKeyPath: String) { dirtyData[forKeyPath] = value ?? NSNull() yielders[forKeyPath]?.yieldUnsafe(value) } // TODO: Make Promise<Void> easier to use; right now it can't even be initialized. public func save() -> Promise<Int> { let done = Promise<Int>() ref.updateChildValues(dirtyData) { err, _ in if err == nil { // TODO: dirtyData needs to be purged, but when will we get the updated snapshot? done.resolve(0) } else { done.fail(err) } } return done } // TODO(Thomas): Don't send events for data which hasn't changed. func updateSnapshot(snapshot: FDataSnapshot!) { serverData = snapshot for child in snapshot.children { let typedChild = child as! FDataSnapshot if let yielder = yielders[typedChild.key] { yielder.yieldUnsafe(typedChild.value) } } } /* public func property<T>(keyPath: String) -> Property<T> { if let existing = yielders[keyPath] { return existing as! Property<T> } let newProp = Property<T>(target:self, keyPath:keyPath) yielders[keyPath] = newProp return newProp }*/ }<file_sep>platform :ios, '8.0' use_frameworks! pod 'Firebase', '>= 2.3.1' pod 'Eventful', '>= 0.0.2'
7a1c1ec14f0d36d9b6409ffbd7d5ddd37dfa3a97
[ "Swift", "Ruby" ]
2
Swift
inlined/griddle
87a6524c1f0255f3bb0d0cb6c8d78e71870cbe2a
dc93f8392a2bc6ddf7940b5a567f84e79cdf05c6
refs/heads/master
<file_sep>setwd("G:\\¡¾Coursera¡¿\\Exploratory Analysis\\W1\\×÷̉µ") rawdata <-read.table("file:///G:/¡¾Coursera¡¿/Exploratory Analysis/W1/×÷̉µ/household_power_consumption.txt", header=TRUE, sep=";", stringsAsFactors=FALSE, dec=".") head(rawdata) Data<-rbind(subset(rawdata, Date=="1/2/2007"), subset(rawdata, Date=="2/2/2007")) str(Data) DT <- strptime(paste(Data$Date, Data$Time, sep=" "), "%d/%m/%Y %H:%M:%S") Global_active_power <- as.numeric(Data$Global_active_power) Global_reactive_power <- as.numeric(Data$Global_reactive_power) Voltage <- as.numeric(Data$Voltage) submetering_1 <- as.numeric(Data$Sub_metering_1) submetering_2 <- as.numeric(Data$Sub_metering_2) submetering_3 <- as.numeric(Data$Sub_metering_3) png("Plot 4.png", width=480, height=480) par(mfrow = c(2, 2)) plot(DT, Global_active_power, type="l", xlab="", ylab="Global Active Power", cex=0.3) plot(DT, Voltage, type="l", xlab="datetime", ylab="Voltage") plot(DT, submetering_1, type="l", ylab="Energy Submetering", xlab="") lines(DT, submetering_2, type="l", col="red") lines(DT, submetering_3, type="l", col="blue") legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=, lwd=3, col=c("black", "red", "blue"), bty="o") plot(DT, Global_reactive_power, type="l", xlab="datetime", ylab="Global_reactive_power") dev.off()<file_sep>setwd("G:\\¡¾Coursera¡¿\\Exploratory Analysis\\W1\\×÷̉µ") rawdata <-read.table("file:///G:/¡¾Coursera¡¿/Exploratory Analysis/W1/×÷̉µ/household_power_consumption.txt", header=TRUE, sep=";", stringsAsFactors=FALSE, dec=".") head(rawdata) Data<-rbind(subset(rawdata, Date=="1/2/2007"), subset(rawdata, Date=="2/2/2007")) str(Data) DT <- strptime(paste(Data$Date, Data$Time, sep=" "), "%d/%m/%Y %H:%M:%S") Global_active_power <- as.numeric(Data$Global_active_power) png("Plot 1.png", width=480, height=480) hist(Global_active_power, col="red", main="Global Active Power", xlab="Global Active Power (kilowatts)") dev.off()<file_sep>setwd("G:\\¡¾Coursera¡¿\\Exploratory Analysis\\W1\\×÷̉µ") rawdata <-read.table("file:///G:/¡¾Coursera¡¿/Exploratory Analysis/W1/×÷̉µ/household_power_consumption.txt", header=TRUE, sep=";", stringsAsFactors=FALSE, dec=".") head(rawdata) Data<-rbind(subset(rawdata, Date=="1/2/2007"), subset(rawdata, Date=="2/2/2007")) str(Data) DT <- strptime(paste(Data$Date, Data$Time, sep=" "), "%d/%m/%Y %H:%M:%S") Global_active_power <- as.numeric(Data$Global_active_power) png("Plot 2.png", width=480, height=480) plot(DT, Global_active_power, type="l", xlab="", ylab="Global Active Power (kilowatts)") dev.off()<file_sep>setwd("G:\\¡¾Coursera¡¿\\Exploratory Analysis\\W1\\×÷̉µ") rawdata <-read.table("file:///G:/¡¾Coursera¡¿/Exploratory Analysis/W1/×÷̉µ/household_power_consumption.txt", header=TRUE, sep=";", stringsAsFactors=FALSE, dec=".") head(rawdata) Data<-rbind(subset(rawdata, Date=="1/2/2007"), subset(rawdata, Date=="2/2/2007")) str(Data) DT <- strptime(paste(Data$Date, Data$Time, sep=" "), "%d/%m/%Y %H:%M:%S") Global_active_power <- as.numeric(Data$Global_active_power) submetering_1 <- as.numeric(Data$Sub_metering_1) submetering_2 <- as.numeric(Data$Sub_metering_2) submetering_3 <- as.numeric(Data$Sub_metering_3) png("Plot 3.png", width=480, height=480) plot(DT, submetering_1, type="l", ylab="Energy Submetering", xlab="") lines(DT, submetering_2, type="l", col="red") lines(DT, submetering_3, type="l", col="blue") legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=1, lwd=2.5, col=c("black", "red", "blue")) dev.off()
3cc0728a00757db4b4e8747bf900b6b68d5ac9f6
[ "R" ]
4
R
sabrinaxu/ExData_Plotting1
1d5da1dfd1f81473011f4a7347141cf100432351
3e0f97492da241453bc3e5b69afce672c70c23a3
refs/heads/master
<file_sep>using System.Text; namespace WHMCS_API.Extensions { public static class ByteArrExts { public static string ToHexString(this byte[] barray) { StringBuilder sb = new StringBuilder(); foreach (byte t in barray) { sb.Append(t.ToString("x2")); } return sb.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace WHMCS_API { public static class APIEnums { public enum ValidateLoginParams { [StringValue("email")] Email, [StringValue("password2")] Password } public enum DomainWhoisParams { [StringValue("domain")] Domain } public enum AddClientParams { [StringValue("firstname")] Firstname, [StringValue("lastname")] Lastname, [StringValue("email")] Email, [StringValue("address1")] Address1, [StringValue("city")] City, [StringValue("state")] State, [StringValue("postcode")] Postcode, [StringValue("countrycode")] CountryCode, [StringValue("phonenumber")] PhoneNumber, [StringValue("password2")] Password, [StringValue("noemail")] NoEmail, [StringValue("companyname")] CompanyName, [StringValue("address2")] Address2, [StringValue("securityqid")] SecurityQuestionID, [StringValue("securityqans")] SecurityQuestionAnswer, [StringValue("cardtype")] CardType, [StringValue("cardnum")] CardNumber, [StringValue("expdate")] ExpiricyDate, [StringValue("startdate")] StartDate, [StringValue("issuenumber")] IssueNumber, [StringValue("cvv")] CVV, [StringValue("currency")] Currency, [StringValue("groupid")] GroupID, [StringValue("customfields")] CustomFields, [StringValue("language")] Language, [StringValue("clientip")] ClientIP, [StringValue("notes")] Notes, [StringValue("skipvalidation")] SkipValidation } public enum GetClientsDetailsParams { [StringValue("clientid")] ClientID, [StringValue("email")] Email, [StringValue("stats")] Stats } public enum GetOrdersParams { [StringValue("limitstart")] LimitStart, [StringValue("limitnum")] LimitNumber, [StringValue("id")] OrderID, [StringValue("userid")] UserID, [StringValue("status")] Status } public enum GetTransactionsParams { [StringValue("invoiceid")] InvoiceID, [StringValue("clientid")] ClientID, [StringValue("transid")] TransactionID } public enum GetClientsProductsParams { [StringValue("limitstart")] ResultsStartOffset, [StringValue("limitnum")] ResultsLimit, [StringValue("clientid")] ClientID, [StringValue("serviceid")] ServiceID, [StringValue("pid")] ProductID, [StringValue("domain")] Domain, [StringValue("username2")] Username } public enum GetInvoicesParams { [StringValue("limitstart")] LimitStart, [StringValue("limitnum")] LimitNumber, [StringValue("userid")] UserID, [StringValue("status")] Status } public enum ModuleChangePasswordParams { [StringValue("accountid")] ServiceID, [StringValue("servicepassword")] NewPassword } public enum ModuleCustomCommandParams { [StringValue("accountid")] ServiceID, [StringValue("func_name")] Command } public enum GetInvoiceParams { [StringValue("invoiceid")] InvoiceID } public enum GetClientsDomainsParams { [StringValue("limitstart")] LimitStart, [StringValue("limitnum")] LimitNumber, [StringValue("clientid")] ClientID, [StringValue("domainid")] DomainID, [StringValue("domain")] Domain } public enum UpdateClientProductParams { [StringValue("serviceid")] ServiceID, [StringValue("pid")] PackageID, [StringValue("serverid")] ServerID, [StringValue("nextduedate")] NextDueDate, [StringValue("terminationDate")] TerminationDate, [StringValue("completedDate")] CompletedDate, [StringValue("domain")] Domain, [StringValue("firstpaymentamount")] FirstPaymentAmount, [StringValue("recurringamount")] RecurringAmount, [StringValue("paymentmethod")] PaymentMethod, [StringValue("subscriptionid")] SubscriptionID, [StringValue("status")] Status, [StringValue("notes")] Notes, [StringValue("serviceusername")] ServiceUsername, [StringValue("servicepassword")] ServicePassword, [StringValue("overideautosuspend")] OverideAutoSuspend, [StringValue("overidesuspenduntil")] OverideSuspendUntil, [StringValue("ns1")] NameServer1, [StringValue("ns2")] NameServer2, [StringValue("dedicatedip")] DedicatedIP, [StringValue("assignedips")] AssignedIPs, [StringValue("diskusage")] DiskUsage, [StringValue("disklimit")] DiskLimit, [StringValue("bwusage")] BandwidthUsage, [StringValue("bwlimit")] BandwidthLimit, [StringValue("suspendreason")] SuspendReason, [StringValue("promoid")] PromoID, [StringValue("unset")] Unset, [StringValue("autorecalc")] AutoRecalculate, [StringValue("customfields")] CustomFields, [StringValue("configoptions")] ConfigurationOptions } public static class UpdateClientProductSubEnums { public enum Status { Null, [StringValue("Terminated")] Terminated, [StringValue("Active")] Active, [StringValue("Pending")] Pending, [StringValue("Suspended")] Suspended, [StringValue("Canceled")] Canceled, [StringValue("Fraud")] Fraud } public enum Unset { [StringValue("ns1")] NameServer1, [StringValue("ns2")] NameServer2, [StringValue("serviceusername")] ServiceUsername, [StringValue("servicepassword")] ServicePassword, [StringValue("subscriptionid")] SubscriptionID, [StringValue("dedicatedip")] DedicatedIP, [StringValue("assignedips")] AssignedIPs, [StringValue("notes")] Notes, [StringValue("suspendreason")] SuspendReason } public enum OverideAutoSuspend { Null, [StringValue("on")] True, [StringValue("off")] False } public enum AutoRecalculate { Null, [StringValue("true")] True, [StringValue("false")] False } } /// <summary> /// Actions Supported by the WHMCS API that are implemented in this Wrapper /// </summary> public enum Actions { [StringValue("ValidateLogin")] ValidateLogin, [StringValue("DomainWhois")] DomainWhois, [StringValue("AddClient")] AddClient, [StringValue("GetClientsDetails")] GetClientsDetails, [StringValue("GetOrders")] GetOrders, [StringValue("GetTransactions")] GetTransactions, [StringValue("GetClientsProducts")] GetClientsProducts, [StringValue("GetInvoices")] GetInvoices, [StringValue("GetInvoice")] GetInvoice, [StringValue("GetClientsDomains")] GetClientsDomains, [StringValue("ModuleChangePw")] ModuleChangePassword, [StringValue("ModuleCustom")] ModuleCustomCommand, [StringValue("UpdateClientProduct")] UpdateClientProduct } } /// <summary> /// Creates an attribute called StringValue /// </summary> public class StringValue : Attribute { private readonly string _value; public StringValue(string value) { _value = value; } public string Value { get { return _value; } } } /// <summary> /// Used to get the string out of the Enum /// </summary> public static class EnumUtil { public static string GetString(Enum value) { string output = null; Type type = value.GetType(); FieldInfo fi = type.GetField(value.ToString()); StringValue[] attrs = fi.GetCustomAttributes(typeof(StringValue), false) as StringValue[]; if (attrs.Length > 0) { output = attrs[0].Value; } return output; } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WHMCS_API.ValidateLogin { public class ValidateLogin { [JsonProperty("result")] public string Result { get; set; } [JsonProperty("userid")] public int UserID { get; set; } [JsonProperty("contactid")] public int ContactID { get; set; } [JsonProperty("passwordhash")] public string PasswordHash { get; set; } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WHMCS_API { public class DomainWhoIs { [JsonProperty("result")] public string Result { get; set; } [JsonProperty("status")] public string Status { get; set; } [JsonProperty("whois")] public string WhoIs { get; set; } } } <file_sep>namespace WHMCS_API.Extensions { public static class StringExts { public static string EncodeToBase64(this string plainText) { var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); return System.Convert.ToBase64String(plainTextBytes); } } } <file_sep># WHMCS API C# Wrapper This is an library to comunicate with the WHMCS API<br/> Currently these functions are already implemented * [Add Client](https://github.com/hitmanpt/whmcs-api/wiki/AddClient%28%29) * [Domain WhoIs](https://github.com/hitmanpt/whmcs-api/wiki/DomainWhoIs%28%29) * [Get Clients Details](https://github.com/hitmanpt/whmcs-api/wiki/GetClientsDetails%28%29) * [Get Clients Domains](https://github.com/hitmanpt/whmcs-api/wiki/GetClientsDomains%28%29) * [Get Clients Products](https://github.com/hitmanpt/whmcs-api/wiki/GetClientsProducts%28%29) * [Get Invoice](https://github.com/hitmanpt/whmcs-api/wiki/GetInvoice%28%29) * [Get Invoices](https://github.com/hitmanpt/whmcs-api/wiki/GetInvoices%28%29) * [Get Orders](https://github.com/hitmanpt/whmcs-api/wiki/GetOrders%28%29) * [Get Transactions](https://github.com/hitmanpt/whmcs-api/wiki/GetTransactions%28%29) * [Module Change Password](https://github.com/hitmanpt/whmcs-api/wiki/ModuleChangePassword%28%29) * [Module Custom Command](https://github.com/hitmanpt/whmcs-api/wiki/ModuleCustomCommand%28%29) * [Validate Login](https://github.com/hitmanpt/whmcs-api/wiki/ValidateLogin%28%29) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=A3JFH2WA6U9YU) How to install<br /> .NET Core Version [NuGet](https://www.nuget.org/packages/WHMCS_API/1.0.0) Packet Manager Console on VisualStudio `Install-Package WHMCS_API -Version 1.0.0`<br /> .NET Framework Version [NuGet](https://www.nuget.org/packages/WHMCS_API/0.9.13) Packet Manager Console on VisualStudio `Install-Package WHMCS_API -Version 0.9.13` <br />or<br /> <a href="https://github.com/hitmanpt/whmcs-api/releases">Releases</a> project page (need to also download Newtonsoft.Json if not already included on your project) The implemented functions are designed to be very easy to use The following code demonstrates to to implement the GetClientDetails on an ASP.net MVC app<br /> More information on the project Wiki <a href="https://github.com/hitmanpt/whmcs-api/wiki/Getting-Started">Getting Started</a> ``` using WHMCS_API; namespace YOUR_APP { public class YOUR_CLASS { [HttpPost] public ActionResult ClientDetails(int clientID) { string username = "WHMCS_USERNAME"; string password = "<PASSWORD>"; string accessKey = "WHNMCS_ACCESS_KEY"; string whmcsUrl = "WHMCS_USERFRONTEND_URL"; //ex: https://example.com/client API api = new API(username, password, accessKey, whmcsUrl); ViewBag.UserDetails = api.GetClientsDetails(clientID, Stats: true); //The model passed is of type GetClientsDetails return View(); } } } ``` You can still use this library to call non implemented<br /> Read more at the project Wiki <a href="https://github.com/hitmanpt/whmcs-api/wiki/%5BAdvanced-Usage%5D-Unsuported-Actions">[Advanced Usage] Unsuported Actions</a> You can also create custom functions of already implemented functions.<br /> Read more at the project Wiki <a href="https://github.com/hitmanpt/whmcs-api/wiki/%5BAdvanced-Usage%5D-Supported-Actions">[Advanced Usage] Supported Actions</a> [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=A3JFH2WA6U9YU) <file_sep>using System.Security.Cryptography; using System.Text; using static WHMCS_API.Extensions.ByteArrExts; namespace WHMCS_API.Cryptography { public static class Hashing { public static string CalculateMD5Hash(string input) { MD5 md5 = MD5.Create(); byte[] inputBytes = Encoding.ASCII.GetBytes(input); byte[] hash = md5.ComputeHash(inputBytes); return hash.ToHexString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace WHMCS_API { public class API { JsonSerializerSettings settings; private readonly Call _call; public API(string Username, string Password, string AccessKey, string Url) { _call = new Call(Username, Password, AccessKey, Url); settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore }; } public ValidateLogin.ValidateLogin ValidateLogin(string Email, string Password) { NameValueCollection data = new NameValueCollection() { { "action", APIEnums.Actions.ValidateLogin.ToString() }, { EnumUtil.GetString(APIEnums.ValidateLoginParams.Email), Email }, { EnumUtil.GetString(APIEnums.ValidateLoginParams.Password), Password } }; string req = _call.MakeCall(data); JObject result = JObject.Parse(req); if (result["result"].ToString() == "success") return JsonConvert.DeserializeObject<ValidateLogin.ValidateLogin>(req, settings); else throw new Exception("An API Error Ocurred", new Exception(result["message"].ToString())); } public DomainWhoIs DomainWhoIs(string Domain) { NameValueCollection data = new NameValueCollection() { { "action", APIEnums.Actions.DomainWhois.ToString() }, { EnumUtil.GetString(APIEnums.DomainWhoisParams.Domain), Domain }, }; string req = _call.MakeCall(data); JObject result = JObject.Parse(req); if (result["result"].ToString() == "success") return JsonConvert.DeserializeObject<DomainWhoIs>(req, settings); else throw new Exception("An API Error Ocurred", new Exception(result["message"].ToString())); } public int AddClient(AddClient ClientInfo) { NameValueCollection data = new NameValueCollection() { { "action", APIEnums.Actions.AddClient.ToString() } }; //Processes all the data in ClientInfo model into the data NameValueCollection foreach (string key in ClientInfo.ClientInfo) { data.Add(key, ClientInfo.ClientInfo[key]); } JObject result = JObject.Parse(_call.MakeCall(data)); if (result["result"].ToString() == "success") return Convert.ToInt32(result["clientid"]); else throw new Exception("An API Error Ocurred", new Exception(result["message"].ToString())); } public GetClientsDetails.GetClientsDetails GetClientsDetails(int ClientID = -1, string ClientEmail = "", bool Stats = false) { if (ClientID == -1 && ClientEmail == "") throw new Exception("ClientID or ClientEmail needed"); NameValueCollection data = new NameValueCollection() { { "action", APIEnums.Actions.GetClientsDetails.ToString() }, { EnumUtil.GetString(APIEnums.GetClientsDetailsParams.Stats), Stats.ToString() }, }; if (ClientID != -1) data.Add(EnumUtil.GetString(APIEnums.GetClientsDetailsParams.ClientID), ClientID.ToString()); if (ClientEmail != "" && ClientID == -1) data.Add(EnumUtil.GetString(APIEnums.GetClientsDetailsParams.Email), ClientEmail); string req = _call.MakeCall(data); JObject result = JObject.Parse(req); if (result["result"].ToString() == "success") return JsonConvert.DeserializeObject<GetClientsDetails.GetClientsDetails>(req, settings); else throw new Exception("An API Error occurred", new Exception(result["message"].ToString())); } public GetOrders.GetOrders GetOrders(int LimitStart = 0, int LimitNumber = 25, int OrderID = -1, int UserID = -1, string Status = "") { NameValueCollection data = new NameValueCollection() { { "action", APIEnums.Actions.GetOrders.ToString() }, { EnumUtil.GetString(APIEnums.GetOrdersParams.LimitStart), LimitStart.ToString() }, { EnumUtil.GetString(APIEnums.GetOrdersParams.LimitNumber), LimitNumber.ToString() } }; if (OrderID != -1) data.Add(EnumUtil.GetString(APIEnums.GetOrdersParams.OrderID), OrderID.ToString()); if (UserID != -1) data.Add(EnumUtil.GetString(APIEnums.GetOrdersParams.UserID), UserID.ToString()); if (Status != "") data.Add(EnumUtil.GetString(APIEnums.GetOrdersParams.Status), Status); return JsonConvert.DeserializeObject<GetOrders.GetOrders>(_call.MakeCall(data), settings); } public GetTransactions.GetTransactions GetTransactions(int InvoiceID = -1, int ClientID = -1, string TransactionID = "") { NameValueCollection data = new NameValueCollection() { { "action", APIEnums.Actions.GetTransactions.ToString() } }; if (InvoiceID != -1) data.Add(EnumUtil.GetString(APIEnums.GetTransactionsParams.InvoiceID), InvoiceID.ToString()); if (ClientID != -1) data.Add(EnumUtil.GetString(APIEnums.GetTransactionsParams.ClientID), ClientID.ToString()); if (TransactionID != "") data.Add(EnumUtil.GetString(APIEnums.GetTransactionsParams.TransactionID), TransactionID); return JsonConvert.DeserializeObject<GetTransactions.GetTransactions>(_call.MakeCall(data), settings); } public GetClientsProducts.GetClientsProducts GetClientsProducts(int LimitStart = 0, int LimitNum = 25, int ClientID = -1, int ServiceID = -1, int ProductID = -1, string Domain = "", string Username = "") { NameValueCollection data = new NameValueCollection() { { "action", APIEnums.Actions.GetClientsProducts.ToString() }, { EnumUtil.GetString(APIEnums.GetClientsProductsParams.ResultsStartOffset), LimitStart.ToString()}, { EnumUtil.GetString(APIEnums.GetClientsProductsParams.ResultsLimit), LimitNum.ToString()}, }; if (ClientID != -1) data.Add(EnumUtil.GetString(APIEnums.GetClientsProductsParams.ClientID), ClientID.ToString()); if (ServiceID != -1) data.Add(EnumUtil.GetString(APIEnums.GetClientsProductsParams.ServiceID), ServiceID.ToString()); if (ProductID != -1) data.Add(EnumUtil.GetString(APIEnums.GetClientsProductsParams.ProductID), ProductID.ToString()); if (Domain != "") data.Add(EnumUtil.GetString(APIEnums.GetClientsProductsParams.Domain), Domain); if (Username != "") data.Add(EnumUtil.GetString(APIEnums.GetClientsProductsParams.Username), Username); return JsonConvert.DeserializeObject<GetClientsProducts.GetClientsProducts>(_call.MakeCall(data), settings); } public GetInvoices.GetInvoices GetInvoices(int LimitStart = 0, int LimitNumber = 25, int UserID = -1, string Status = "") { NameValueCollection data = new NameValueCollection() { { "action", APIEnums.Actions.GetInvoices.ToString() }, { EnumUtil.GetString(APIEnums.GetInvoicesParams.LimitStart), LimitStart.ToString() }, { EnumUtil.GetString(APIEnums.GetInvoicesParams.LimitNumber), LimitNumber.ToString() } }; if (UserID != -1) data.Add(EnumUtil.GetString(APIEnums.GetInvoicesParams.UserID), UserID.ToString()); if (Status != "") data.Add(EnumUtil.GetString(APIEnums.GetInvoicesParams.Status), Status); return JsonConvert.DeserializeObject<GetInvoices.GetInvoices>(_call.MakeCall(data), settings); } public GetInvoice.GetInvoice GetInvoice(int InvoiceID) { NameValueCollection data = new NameValueCollection() { { "action", EnumUtil.GetString(APIEnums.Actions.GetInvoice) }, { EnumUtil.GetString(APIEnums.GetInvoiceParams.InvoiceID), InvoiceID.ToString() } }; string req = _call.MakeCall(data); JObject result = JObject.Parse(req); if (result["result"].ToString() == "success") return JsonConvert.DeserializeObject<GetInvoice.GetInvoice>(req, settings); else throw new Exception("An API Error Ocurred", new Exception(result["message"].ToString())); } public GetClientsDomains.GetClientsDomains GetClientsDomains(int LimitStart = 0, int LimitNumber = 25, int ClientID = -1, int DomainID = -1, string Domain = "") { NameValueCollection data = new NameValueCollection() { { "action", EnumUtil.GetString(APIEnums.Actions.GetClientsDomains) }, { EnumUtil.GetString(APIEnums.GetClientsDomainsParams.LimitStart), LimitStart.ToString() }, { EnumUtil.GetString(APIEnums.GetClientsDomainsParams.LimitNumber), LimitNumber.ToString() } }; if (ClientID != -1) data.Add(EnumUtil.GetString(APIEnums.GetClientsDomainsParams.ClientID), ClientID.ToString()); if (DomainID != -1) data.Add(EnumUtil.GetString(APIEnums.GetClientsDomainsParams.DomainID), DomainID.ToString()); if (Domain != "") data.Add(EnumUtil.GetString(APIEnums.GetClientsDomainsParams.Domain), Domain); return JsonConvert.DeserializeObject<GetClientsDomains.GetClientsDomains>(_call.MakeCall(data), settings); } public bool ModuleChangePassword(int ServiceID, string NewPassword, bool getException = true) { NameValueCollection data = new NameValueCollection() { { "action", EnumUtil.GetString(APIEnums.Actions.ModuleChangePassword) }, { EnumUtil.GetString(APIEnums.ModuleChangePasswordParams.ServiceID), ServiceID.ToString() }, { EnumUtil.GetString(APIEnums.ModuleChangePasswordParams.NewPassword), NewPassword } }; JObject result = JObject.Parse(_call.MakeCall(data)); if (result["result"].ToString() == "success") return true; else if(result["result"].ToString() != "success" && getException) throw new Exception("An API Error Ocurred", new Exception(result["message"].ToString())); return false; } public bool ModuleCustomCommand(int ServiceID, string Command, bool getException = true) { NameValueCollection data = new NameValueCollection() { { "action", EnumUtil.GetString(APIEnums.Actions.ModuleCustomCommand) }, { EnumUtil.GetString(APIEnums.ModuleCustomCommandParams.ServiceID), ServiceID.ToString() }, { EnumUtil.GetString(APIEnums.ModuleCustomCommandParams.Command), Command } }; JObject result = JObject.Parse(_call.MakeCall(data)); if (result["result"].ToString() == "success") return true; else if (result["result"].ToString() != "success" && getException) throw new Exception("An API Error Ocurred", new Exception(result["message"].ToString())); return false; } public bool UpdateClientProduct(UpdateClientProduct.UpdateClientProduct ClientProductUpdateInfo) { JObject result = JObject.Parse(_call.MakeCall(ClientProductUpdateInfo.nvm)); if (result["result"].ToString() == "success") return true; else throw new Exception("An API Error Ocurred", new Exception(result["message"].ToString())); } } }
91688a2ee19d1ad490b4628aaa5fe93b5cb0f5d8
[ "Markdown", "C#" ]
8
C#
PedroCavaleiro/whmcs-api
2372d9f8bbfa2df9f530aaa5a1e2543a032c0d87
f06801117ae03aae79ded93e1c5e2035f988284b
refs/heads/master
<repo_name>Kemoshousha309/budget.github.io<file_sep>/README.md # budget application for calculate the budget (html, css, js) <file_sep>/forEach.js // var myData = function(name, job, age){ // this.name = name; // this.job = job; // this.age = age; // this.gender = "male"; // }; // // myData.prototype.forEach = function() { // // }; // myData.prototype = { // forEach:function(func){ // for(var i = 0; i < Object.keys(this).length; i++){ // func(Object.keys(this)[i], this); // } // } // } // var myArray = []; // var kareem = new myData("<NAME>", "devoloper", 20); // kareem.forEach(function(curKey){ // console.log(kareem.curKey); // }); // console.log(kareem.name, myArray); var date = new Date(); console.log(date.getFullYear(), date.toLocaleString("default", { month: "long" }));
3bc20401fbb116324b95ce5ceec76c81848b4297
[ "Markdown", "JavaScript" ]
2
Markdown
Kemoshousha309/budget.github.io
353de82903cad4d0911d3f0c87a45b3f6fe66eef
e2469a5b1a9708e2fbcc9d158ceb79bde0366156
refs/heads/main
<file_sep>all: main.o gcc -o ./a.out main.o main.o: main.c gcc -c main.c <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <signal.h> #include <unistd.h> #include <fcntl.h> static void sighandler(int sig) { if (sig == SIGINT) { // 2 - SIGINT - interupt process stream, ctrl-C int fh = open("exit.log", O_WRONLY | O_TRUNC | O_CREAT, 0777); char * x = "program exited due to SIGNINT"; write(fh, x, strlen(x)); exit(0); } if (sig == SIGUSR1) { // 10 - SIGUSR1 printf("ppid: %d\n", getppid()); } } int main() { signal(SIGINT, sighandler); signal(SIGUSR1, sighandler); while (1) { /* code */ printf("pid: %d\n", getpid()); sleep(1); } return 0; }
707f0547c54b68a84a44ba1e4de699bc31ba15e0
[ "C", "Makefile" ]
2
Makefile
jasonjiangstuy/systems-14
90fbd0114e076a81aa58586b04dda6b83084a38c
57013e6a3a4b8fd2beae79097021057d3d75dba1
refs/heads/master
<file_sep>const takeNoArgs = (method) => function() { return method(this.props); }; const takeFirstArg = (method) => function(arg1) { return method(this.props, arg1); }; const methodCreators = { componentWillMount: takeNoArgs, componentDidMount: takeNoArgs, componentWillReceiveProps: takeFirstArg, shouldComponentUpdate: takeFirstArg, componentWillUpdate: takeFirstArg, componentDidUpdate: takeFirstArg, componentWillUnmount: takeNoArgs }; if (process.env.NODE_ENV !== 'production') { Object.freeze(methodCreators); } export default methodCreators; <file_sep>import React from 'react'; import { render, unmountComponentAtNode } from 'react-dom'; import { bindActionCreators, createStore } from 'redux'; import { connect, Provider } from 'react-redux'; import NameTag from './NameTag'; const NameTagContainer = connect(props => props)(NameTag); const store = createStore((state = { name: 'Jeremy' }, action) => { if (action.type === 'CHANGE_NAME') { return { name: action.payload }; } return state; }); const actions = bindActionCreators({ changeName: (name) => ({ type: 'CHANGE_NAME', payload: name }) }, store.dispatch); render( <Provider store={store}> <NameTagContainer/> </Provider>, document.getElementById('main') ); setTimeout(() => actions.changeName('Bob'), 1000); setTimeout(() => unmountComponentAtNode(document.getElementById('main')), 2000); <file_sep>import React from 'react'; import { expect } from 'chai'; import classify from '../../src/classify'; const FunctionalText = ({ content }) => <div>{content}</div>; describe('displayName', () => { it('uses a default', () => { const Text = classify(FunctionalText); expect(Text.displayName).to.equal('Component'); }); it('uses a default when methods are the second arg', () => { const Text = classify(FunctionalText, { componentWillMount() {} }); expect(Text.displayName).to.equal('Component'); expect(Text.prototype.componentWillMount).to.be.a('function'); }); it('uses the provided displayName', () => { const Text = classify(FunctionalText, 'Text'); expect(Text.displayName).to.equal('Text'); }); it('uses the provided displayName when methods are supplied', () => { const Text = classify(FunctionalText, 'Text', { componentWillMount() {} }); expect(Text.displayName).to.equal('Text'); expect(Text.prototype.componentWillMount).to.be.a('function'); }); }); <file_sep>import React from 'react'; import classify from '../../src/classify'; const lifecycleFunction = (name, handler = () => {}) => (props, ...args) => { console.log(name, props, ...args); return handler(props, ...args); }; const componentWillMount = lifecycleFunction('componentWillMount'); const componentDidMount = lifecycleFunction('componentDidMount'); const componentWillReceiveProps = lifecycleFunction('componentWillReceiveProps'); const shouldComponentUpdate = lifecycleFunction( 'shouldComponentUpdate', (currentProps, nextProps, nextState) => true ); const componentWillUpdate = lifecycleFunction('componentWillUpdate'); const componentDidUpdate = lifecycleFunction('componentDidUpdate'); const componentWillUnmount = lifecycleFunction('componentWillUnmount'); const NameTag = ({ name }) => ( <div>Hello, my name is {name}</div> ); export default classify(NameTag, 'NameTag', { componentWillMount, componentDidMount, componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate, componentDidUpdate, componentWillUnmount }); <file_sep>### v1.1.0 * Add support for React 15 ### v1.0.1 - 2015-12-28 **Bug Fixes:** * Forgot the "files" prop in package.json, preventing prepublished files from being available when installing via npm. ### v1.0.0 - 2015-12-23 **Initial Release** <file_sep>import chai from 'chai'; import sinonChai from 'sinon-chai'; chai.use(sinonChai); require('./classify/lifecycleFunctions'); require('./classify/displayName'); <file_sep>import React from 'react'; import methodCreators from './methodCreators'; const DEFAULT_DISPLAY_NAME = 'Component'; export default function classify(Component, displayName = DEFAULT_DISPLAY_NAME, methods = {}) { if (typeof displayName === 'object') { methods = displayName; displayName = DEFAULT_DISPLAY_NAME; } class Wrapper extends React.Component { render() { return Component(this.props); } } Wrapper.displayName = displayName; Object.keys(methods).forEach((methodName) => { const methodCreator = methodCreators[methodName]; const method = methodCreator(methods[methodName]); Object.defineProperty(Wrapper.prototype, methodName, { writable: true, enumerable: false, configurable: true, value: method }); }); return Wrapper; } <file_sep># react-classify [![Circle CI](https://circleci.com/gh/jfairbank/react-classify.svg?style=svg)](https://circleci.com/gh/jfairbank/react-classify) Wrap functional React components with a component class, so you can use lifecycle hook functions and have a backing instance for testing or other purposes. ## Install $ npm install react-classify ## Usage Use the default export `classify` to wrap your functional React component in a class. This allows your component to have a wrapped backing instance which may be useful for tests or other reasons. Additionally, you can provide lifecycle hook functions. ```js import React from 'react'; import { render } from 'react-dom'; import classify from 'react-classify'; function componentWillMount(props) { console.log('NameTag mounting with props', props); } const FunctionalNameTag = ({ name }) => ( <div>Hello, my name is {name}</div> ); const NameTag = classify(FunctionalNameTag, 'NameTag', { componentWillMount }); render( <NameTag name="Jeremy"/>, document.getElementById('main') ); // Logs 'NameTag mounting with props { name: "Jeremy" }' ``` ## API ### `classify` ```js classify( componentFunction: (props: Object) => ReactElement, [displayName: string], [methods: { [componentWillMount: (props: Object) => void], [componentDidMount: (props: Object) => void], [componentWillReceiveProps: (currentProps: Object, nextProps: Object) => void], [shouldComponentUpdate: (currentProps: Object, nextProps: Object) => boolean], [componentWillUpdate: (currentProps: Object, nextProps: Object) => void], [componentDidUpdate: (currentProps: Object, prevProps: Object) => void], [componentWillUnmount: (props: Object) => void] }] ): React.Component ``` ### `displayName` You can provide a `displayName` for your wrapped component for debugging purposes via the second argument. ```js const FunctionalNameTag = ({ name }) => ( <div>Hello, my name is {name}</div> ); const NameTag = classify(FunctionalNameTag, 'NameTag'); console.assert(NameTag.displayName === 'NameTag'); ``` ### Lifecycle Functions All lifecycle functions are optional. Notice that lifecycle functions all take the current `props` as the first parameter. They may take an additional argument based on whether you're updating the `props` for the component. #### `componentWillMount(props: Object): void` Invoked once immediately before the initial rendering occurs. #### `componentDidMount(props: Object): void` Invoked once immediately after the initial rendering occurs. #### `componentWillReceiveProps(currentProps: Object, nextProps: Object): void` Invoked when a component is receiving new props. This function is not called for the initial render. #### `shouldComponentUpdate(currentProps: Object, nextProps: Object): boolean` Invoked before rendering when new props are being received. This function is not called for the initial render. Return `false` to prevent a component update. #### `componentWillUpdate(currentProps: Object, nextProps: Object): void` Invoked immediately before rendering when new props are being received. This function is not called for the initial render. #### `componentDidUpdate(currentProps: Object, prevProps: Object): void` Invoked immediately after the component's updates are flushed to the DOM. This function is not called for the initial render. #### `componentWillUnmount(props: Object): void` Invoked immediately before a component is unmounted from the DOM.
f12e3e91867a8c0abb440dc5af82ff6d2c1ae38e
[ "JavaScript", "Markdown" ]
8
JavaScript
jfairbank/react-classify
37ff06987b7e10cc5980c97f0648791dff488c8d
8597725c8148e69114747cd7a5b4e5f623747ce0
refs/heads/master
<file_sep> import requests from bs4 import BeautifulSoup #response = requests.get("http://www.omdbapi.com/?i=tt3896198&apikey=8aba35e0") response = requests.get("https://www.drupal.org/project/issues") responseContent = response.content.decode('utf-8') filePath = "./issues.csv" logFile = open(filePath, 'a') logFile.write("Project,Title,Status,Replies,AssignedTo") issuesHtml = BeautifulSoup(responseContent, 'html.parser') projectTitles = issuesHtml.find_all("td", class_="views-field-field-project-title") issueTitles = issuesHtml.find_all("td", class_="views-field-title") issueStatus = issuesHtml.find_all("td", class_="views-field-field-issue-status") #issuePriority = issuesHtml.find_all("td", class_="views-field-field-issue-priority") #issueCategory = issuesHtml.find_all("td", class_="views-field-field-issue-category") #issueVersion = issuesHtml.find_all("td", class_="views-field-field-issue-version") issueReplies = issuesHtml.find_all("td", class_="views-field-comment-count") issueAssignment = issuesHtml.find_all("td", class_="views-field-field-issue-assigned") result = [] projectResult = [] titleResult = [] statusResult = [] #priorityResult = [] #categoryResult = [] #versionResult = [] repliesResult = [] assignmentResult = [] #print(issueStatus) #Create an array of all proejct and title #the dictoinary should contain data in the following format # project1 dict({"project":"Block field", "title":"Convert WTB tests to BTB (and fix failing tests)"}) #result = dict("project": "", "title": "", "status": "") #results = {} for listOfProjectTd in projectTitles: for linkWithTitle in listOfProjectTd: for projectTitle in linkWithTitle: projectResult.append(projectTitle) for listOfTitlesTd in issueTitles: for linkWithTitle in listOfTitlesTd: for Title in linkWithTitle: titleResult.append(Title) for listOfIssueStatusTd in issueStatus: for linkWithIssueStatus in listOfIssueStatusTd: for IssueStatus in linkWithIssueStatus: statusResult.append(IssueStatus) for listOfrepliesTd in issueReplies: for linkWithIssueReplies in listOfrepliesTd: for replies in linkWithIssueReplies: repliesResult.append(replies) for listOfassignmentTd in issueAssignment: for linkWithAssignment in listOfassignmentTd: for assignedTo in linkWithAssignment: assignmentResult.append(assignedTo) #print (statusResult) #print (repliesResult) print (assignmentResult) for i in range(1, len(projectResult)): logFile.write(projectResult[i] + ',' + titleResult[i] + ',' + statusResult[i] + ',' + repliesResult[i] + ',' + assignmentResult[i]) #results #logFile.write(l + "\n")
a7b89d86aee5dc8627f77a02639cdd9e90916342
[ "Python" ]
1
Python
rewatthapa/Crawling
6fb770a52b58d1c86e0182001d7184229bf68b33
777a7d2ee6ad3f5716c6b326f69065910a72873b
refs/heads/master
<repo_name>anjanasarath/graviton-ui-web<file_sep>/app/src/components/searchparking.js import React, { PropTypes } from 'react'; import ReactDom from 'react-dom'; import Autocomplete from 'react-google-autocomplete'; import { Button, Card, CardBody, CardTitle, CardText } from 'mdbreact'; import Styles from '../styles/searchparking'; import DropDown from './dropDown'; const SearchParking = () => ( <div className="d-flex search-container gbackground"> <div className="d-flex flex-row-reverse justify-content-center align-items-center col-sm-7 col-12 pt-10 pb-10"> <Card className='search-card mr-lg-2'> <CardBody> <CardTitle className='text-white search-park-title'>Find parking in</CardTitle> <CardText className='text-white mobile-hidden'> Choose from millions of available spaces, or reserve your space in advance. Join over 1.5 million drivers enjoying easy parking. </CardText> <CardText className='text-white desktop-hidden'> Choose from millions of spaces. Trusted by 1.5 million drivers. </CardText> <Autocomplete className='search-auto-complete bg-white' placeholder="Where do you want to park?" onPlaceSelected={(place) => { console.log(place); }} types={['(regions)']} componentRestrictions={{country: "mx"}} /> <div className='dropdown mt-2'> <span> <DropDown/> </span> </div> <div className='d-flex mt-2'> <div className='col-6 p-0'> <Button className='search-button'>Search</Button> </div> <div className='col-6 p-0'> <Button className='search-button float-right'>I feel lucky</Button> </div> </div> </CardBody> </Card> </div> <div className='search-image-container col-sm-5 d-none d-sm-inline' style={Styles.dImage}> </div> </div> ); export default SearchParking; <file_sep>/app/src/components/review.js import React from "react"; import Slider from "react-slick"; import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card'; import MediaQuery from 'react-responsive'; import User1 from '../images/users/user1.jpg'; import User2 from '../images/users/user2.jpg'; import User3 from '../images/users/user3.jpg'; import User4 from '../images/users/user4.jpg'; const stars = (props) => { let stars = []; for (let i=0; i<props.rating && i<5; i++) { stars.push(<div key = {i} className = 'fa fa-star text-yellow'></div>); } return stars; }; const UserReview = (props) => ( <div className="review-section row"> <div className="col-md-1 d-none d-md-inline"> <img className="rounded-circle user-profile-image" src={props.image}/> </div> <div className="col-md-11 col-sm-12 pl-5 row"> <div> <h6>{props.name}</h6> <div>{stars(props).map((star)=>star)}</div> </div> <div className='d-md-none flex-fill pl-3'> <img className="rounded-circle user-profile-image" src={props.image}/> </div> <div className="w-100">{props.location}</div> <div>{props.comments}</div> </div> </div> ); const Review = (props) => ( <div className='pb-6 pb-sm-10'> <div className='review-slider'> <Slider {...props.settings}> <div> <UserReview image={User1} name="<NAME>" rating={5} location="Car park on High Holborn, London" comments="Very easy. The convenient parking made our stay all the more enjoyable. Cheaper than the train and cheaper than other car parks too. Easy booking system and pre-payment takes the stress out of finding the cash or texting to pay. We will definitely use again." /> </div> <div> <UserReview image={User2} name="<NAME>" rating={5} location="Driveway on Vicarage Road, Birmingham" comments="Not used to reviewing parking spaces, but have to say this one was perfect! We used it as away supporters attending a Fulham game. Very convenient 10 minute walk to the ground, easy to find and a quick escape on the South Circular afterwards. Great service." /> </div> <div> <UserReview image={User3} name="<NAME>" rating={5} location="Car park on Whiteladies Road, Bristol" comments="Simple and easy-to-use app, perfect for my commute into work. Saves on stress of having to find a space in the morning in such a difficult area to find parking. Very happy with the service, has made my journey much easier and hope to use on a regular basis." /> </div> <div> <UserReview image={User4} name="<NAME>" rating={5} location="Car park on Melton Street, London" comments="I used this space for a hospital appointment in London. The whole JustPark experience has been great! So easy to find and book a space - at a brilliant price too! Will definitely use again, saved us a bundle of money and stress. Thank you JustPark :-)" /> </div> </Slider> </div> </div> ); const webSettings = { dots: true, infinite: true, rows: 2, slidesPerRow: 2, arrows: false, autoplay: false, accessibility: true, autoplaySpeed: 2500, variableWidth: false, dotsClass: 'slick-dots', }; const mobileSettings = { ...webSettings, rows: 1, slidesPerRow: 1, slidesToShow: 1, slidesToScroll: 1, autoplay: true, }; const UserReviews = () => ( <div className='lh-1-5 review-container justify-content-center'> <div className='text-center'> <h2 className='review-title pt-sm-5 pt-4'>Reviews</h2> </div> <MediaQuery query='(min-device-width: 80em)'> <Review settings={webSettings}/> </MediaQuery> <MediaQuery query='(max-device-width: 80em)'> <Review settings={mobileSettings}/> </MediaQuery> </div> ); export default UserReviews; <file_sep>/app/src/components/downloadapp.js import React from 'react'; import ReactDom from 'react-dom'; import MediaQuery from 'react-responsive'; import PhoneImg from '../images/appdownload/phone.png'; const DownloadApp = (props) => ( <div className="d-flex download-container download-text align-items-center"> <div className="col-md-6 col-sm-6"> <div className='mw-20'> <h2>Download the app</h2> <ul className='g-list-inline'> <li><h6>5 star rated on both app stores</h6></li> <li><h6>20,000+ reservable locations</h6></li> <li><h6>Find, pay & extend on-the-go</h6></li> <li><h6>Handy reminders</h6></li> <li><h6>Easy navigation</h6></li> <li><h6>Quick rebooking</h6></li> <li><h6>Smart notifications</h6></li> </ul> <div className='text-align-center d-flex'> <div className='appstore col-6 col-md-6 col-sm-6'></div> <div className='google col-6 col-md-6 col-sm-6'></div> </div> </div> </div> <MediaQuery query='(min-device-width: 40em)'> <div className="col-md-6 col-sm-6 d-table h-100"> <div className="d-table-cell align-bottom"> <img src={PhoneImg} height='50%' width='50%' className='img-fluid'/> </div> </div> </MediaQuery> </div> ); export default DownloadApp; <file_sep>/app/src/reducers/index.js import { combineReducers } from 'redux'; import { sessionReducer } from 'redux-react-session'; import { routerReducer } from 'react-router-redux'; import loginReducer from './login'; export default combineReducers({ router: routerReducer, session: sessionReducer, login: loginReducer }); <file_sep>/app/src/components/footer.js import React from 'react'; import { Col, Footer } from 'mdbreact'; import Logo from '../images/logo/footer_logo.svg'; import MediaQuery from 'react-responsive'; class GFooter extends React.Component { render(){ return( <Footer color="stylish-color-dark" className="font-small pt-4 m-t-0"> <div className="text-center text-md-left"> <MediaQuery query='(min-device-width: 40em)'> <div className="d-flex flex-wrap gtext-left text-md-left mt-3 pb-3"> <Col xs='12' md="3" lg="3" xl="3"> <img src={Logo} /> </Col> <hr className="w-100 clearfix d-md-none"/> <Col xs='12' md="3" lg="3" xl="3"> <p><a href="#!">About</a></p> <p><a href="#!">How it works</a></p> <p><a href="#!">Help</a></p> <p><a href="#!">Media</a></p> <p><a href="#!">Contact Us</a></p> </Col> <hr className="w-100 clearfix d-md-none"/> <Col xs='12' md="3" lg="3" xl="3"> <p><a href="#!">Cashless parking solution</a></p> <p><a href="#!">Car park management</a></p> <p><a href="#!">Hotel car parks</a></p> <p><a href="#!">Rent out your driveway</a></p> <p><a href="#!">Airport parking</a></p> <p><a href="#!">Stadium parking</a></p> <p><a href="#!">Station parking</a></p> <p><a href="#!">City parking</a></p> </Col> <hr className="w-100 clearfix d-md-none"/> <Col xs='12' md="3" lg="3" xl="3"> <h6 className="text-uppercase mb-4">Contact</h6> <p><i className="fa fa-home"></i> New York, NY 10012, US</p> <p><i className="fa fa-envelope"></i> <EMAIL></p> <p><i className="fa fa-phone"></i> + 01 234 567 88</p> <p><i className="fa fa-print"></i> + 01 234 567 89</p> </Col> </div> <hr/> <div className="d-flex gtext-left text-center flex-wrap align-items-center"> <Col xs='12' md="3"> <p className="grey-text">&copy; Copyright <a href="https://www.justpark.com"> JustPark 2017 </a></p> </Col> <Col xs='12' md="2"> <p className="grey-text">Site map</p> </Col> <Col xs='12' md="2"> <p className="grey-text">Cancellation policy</p> </Col> <Col xs='12' md="2"> <p className="grey-text">Terms of use</p> </Col> <Col xs='12' md="3"> <p className="grey-text">Where is ParkatmyHouse?</p> </Col> </div> </MediaQuery> <MediaQuery query='(max-device-width: 40em)'> <div className="d-flex flex-wrap mt-3 pb-3"> <Col xs='12' md="3" lg="3" xl="3"> <img src={Logo} /> </Col> <hr className="w-100 clearfix d-md-none"/> <Col xs='12' md="3" lg="3" xl="3"> <p><a href="#!">How it works</a></p> <p><a href="#!">Help</a></p> <p><a href="#!">jobs</a></p> <p><a href="#!">Blog</a></p> <p><a href="#!">Cancellation Policy</a></p> <p><a href="#!">Contact Us</a></p> <p><a href="#!">Airport parking</a></p> <p><a href="#!">Stadium parking</a></p> <p><a href="#!">Station parking</a></p> <p><a href="#!">City parking</a></p> </Col> </div> <hr/> </MediaQuery> </div> </Footer> ); } } export default GFooter; <file_sep>/app/index.js import React from 'react'; import ReactDOM from 'react-dom'; import promiseMiddleware from 'redux-promise-middleware'; import { Provider } from 'react-redux'; import { routerMiddleware } from 'react-router-redux'; import { createStore, applyMiddleware, compose } from 'redux'; import { sessionService } from 'redux-react-session'; import createSagaMiddleware from 'redux-saga'; import createHistory from 'history/createBrowserHistory'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Routes from './src/routes'; import reducers from './src/reducers'; import sagas from './src/sagas'; import styles from './index.css'; const history = createHistory(); const middleware = routerMiddleware(history); const sagaMiddleware = createSagaMiddleware({}); const store = createStore( reducers, undefined, compose(applyMiddleware(sagaMiddleware, promiseMiddleware(), middleware)) ); // "to initialise application with existing browser session..." sessionService.initSessionService(store, { refreshOnCheckAuth: true, redirectPath: '/login', driver: 'COOKIES' }); sagaMiddleware.run(sagas); ReactDOM.render( <Provider store={store}> <MuiThemeProvider> <Routes history={history} /> </MuiThemeProvider> </Provider>, document.getElementById('app') ) <file_sep>/app/src/containers/home.js import React from 'react'; import ReactDom from 'react-dom'; import Header from '../components/header'; import SearchParking from '../components/searchparking'; import MultiCarouselPage from '../components/easypark'; import RentParking from '../components/rentpark'; import CarParking from '../components/carpark'; import Review from '../components/review'; import DownloadApp from '../components/downloadapp'; import GFooter from '../components/footer'; const Home = () => ( <div className="h-100"> <Header /> <SearchParking /> <MultiCarouselPage /> <DownloadApp/> <RentParking/> <Review/> <CarParking/> <GFooter/> </div> ); export default Home; <file_sep>/app/src/styles/login.js export default { button : { backgroundColor:"#F50057", borderRadius:'.4em', height:'60px', color: '#fff' }, fbButton : { height: '40px', width: '200px', borderRadius: '1em', background:'#4262a5', color:'#fff', }, gglButton: { height: '40px', width: '200px', borderRadius: '1em', background:'#dd4b39', color:'#fff', }, footerbtn: { height: '40px', width: '150px', borderRadius:'1em', backgroundColor: '#880E4F', color:'#fff', }, cardheader: { fontWeight: 'bold', }, divider: { marginTop: '1em', }, }; <file_sep>/app/src/components/dropDown.js import React from 'react'; import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'mdbreact'; class DropDown extends React.Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.select = this.select.bind(this); this.state = { value: 'Space', dropdownOpen: false, }; } toggle() { this.setState({ dropdownOpen: !this.state.dropdownOpen, }); } select(event) { this.setState({ dropdownOpen: !this.state.dropdownOpen, value: event.target.innerText }); } render() { return ( <Dropdown isOpen = { this.state.dropdownOpen } toggle = { this.toggle } size = "lg"> <DropdownToggle caret className="w-100 drop-toggle-btn"> {this.state.value} </DropdownToggle> <DropdownMenu className="w-100"> <DropdownItem header>Space</DropdownItem> <DropdownItem onClick={this.select}>Parking</DropdownItem> <DropdownItem onClick={this.select}>Warehouse</DropdownItem> </DropdownMenu> </Dropdown> ); } } export default DropDown; <file_sep>/app/src/actions/login.js import { sessionService } from 'redux-react-session'; import { SOCIAL_LOGIN_SUCCESS, LOGOUT_SUCCESS } from './types'; export const socialLoginSuccess = (provider, userData) => { sessionService.saveUser(userData.profile); sessionService.saveSession(userData.token); return { type: SOCIAL_LOGIN_SUCCESS, provider: provider, user: userData, }; } export const logout = () => { sessionService.deleteSession(); return { type: LOGOUT_SUCCESS, }; } <file_sep>/app/src/components/header.js import React, { PropTypes } from 'react'; import ReactDom from 'react-dom'; import { connect } from 'react-redux'; import { Navbar, NavbarBrand, NavbarNav, NavbarToggler, Collapse, NavItem, NavLink, Button } from 'mdbreact'; import Logo from '../images/logo/logo.svg'; import { logout } from '../actions'; class Header extends React.Component { constructor(props) { super(props); this.state = { collapse: false, isWideEnough: false, }; this.navCollapse = this.navCollapse.bind(this); } navCollapse() { this.setState({ collapse: !this.state.collapse, }); } render() { return ( <Navbar className='gheader' fixed="top" light expand="md"> <NavbarBrand> <img src={Logo} /> </NavbarBrand> { !this.state.isWideEnough && <NavbarToggler onClick = { this.navCollapse } />} <Collapse isOpen = {this.state.collapse} navbar> <NavbarNav right> { !this.props.authenticated && <NavItem> <NavLink to="/login">Login</NavLink> </NavItem> } { this.props.authenticated && <NavItem> <span>{this.props.user.firstName} &nbsp; {this.props.user.lastName}</span> </NavItem> } { this.props.authenticated && <NavItem> <Button color="primary" onClick={this.props.logout}>Log Out</Button> </NavItem> } <NavItem> <NavLink to="/signup">Signup</NavLink> </NavItem> </NavbarNav> </Collapse> </Navbar> ); } } const mapStateToProps = (state) => ( { authenticated: state.session.authenticated, user: state.session.user, } ); const mapDispatchToProps = (dispatch) => ( { logout: (event) => { dispatch(logout()); } } ); export default connect(mapStateToProps,mapDispatchToProps)(Header); <file_sep>/app/src/containers/login.js import React from 'react'; import ReactDom from 'react-dom'; import { Link } from 'react-router-dom'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card'; import Paper from 'material-ui/Paper'; import Divider from 'material-ui/Divider'; import Subheader from 'material-ui/Subheader'; import TextField from 'material-ui/TextField'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import SocialLogin from '../components/sociallogin'; import Styles from '../styles/login'; import { socialLoginSuccess } from '../actions'; const Login = (props) => ( <div className="login-container"> <div className="login-card"> <Card expanded={true}> <div className="login-modal"> <CardHeader title= "Please log in to your account" style={Styles.cardheader}/> </div> <div className="text-center marginTop1"> <SocialLogin style={Styles.fbButton} provider='facebook' appId='' onLoginSuccess={props.facebookLoginSuccess} onLoginFailure={props.facebookLoginFailure} > Login with Facebook </SocialLogin> </div> <div className="text-center marginTop5"> <SocialLogin style={Styles.gglButton} provider='google' appId='645958086585-r1oo5mqjilkm7lkqt9vkgmfv5na2365h.apps.googleusercontent.com' onLoginSuccess={props.googleLoginSuccess} onLoginFailure={props.googleLoginFailure} > Login with Google </SocialLogin> </div> <Divider style={Styles.divider}></Divider> <div className="login-graviton"> <TextField name="text1" hintText="Email Address or Username" fullWidth={true}></TextField> <TextField name="text2" hintText="Password" fullWidth={true}></TextField> <div className="text-center"> <button style={Styles.footerbtn}>Log In</button> </div> </div> <Divider style={Styles.divider}></Divider> <div className="row-graviton login-footer-color"> <CardText>Forgotten your password?</CardText> <CardText>Don&#39;t have an account? <Link to='/signup'><i>SignUp</i></Link> Now</CardText> </div> </Card> </div> </div> ); const mapDispatchToProps = (dispatch) => ({ facebookLoginSuccess: (user) => { dispatch(socialLoginSuccess('facebook',user)); dispatch(push('/')); }, facebookLoginFailure: (error) => { dispatch(push('/loginFailure')); }, googleLoginSuccess: (user) => { dispatch(socialLoginSuccess('google',user)); dispatch(push('/')); }, googleLoginFailure: (error) => { dispatch(push('/loginFailure')); }, }); export default connect(null, mapDispatchToProps)(Login); <file_sep>/app/src/containers/signUp.js import React from 'react'; import ReactDom from 'react-dom'; import { Link } from 'react-router-dom'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card'; import Paper from 'material-ui/Paper'; import Divider from 'material-ui/Divider'; import Subheader from 'material-ui/Subheader'; import TextField from 'material-ui/TextField'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import SocialLogin from '../components/sociallogin'; import Styles from '../styles/signUp'; const SignUp = (props) => ( <div className="login-container"> <div className="login-card"> <Card expanded={true}> <div className="login-modal"> <CardHeader title= "Register for an account" style={Styles.cardheader}/> </div> <div className="text-center marginTop1"> <SocialLogin style={Styles.fbButton} provider='facebook' appId='' onLoginSuccess={props.facebookLoginSuccess} onLoginFailure={props.facebookLoginFailure} > Login with Facebook </SocialLogin> </div> <div className="text-center marginTop5"> <SocialLogin style={Styles.gglButton} provider='google' appId='645958086585-9nulhpg8e3qlj8aq6a6fit839tbmv5mr.apps.googleusercontent.com' onLoginSuccess={props.googleLoginSuccess} onLoginFailure={props.googleLoginFailure} > Login with Google </SocialLogin> </div> <Divider style={Styles.divider}></Divider> <div className="row-graviton login-footer-color"> <CardText>Takes only a few seconds</CardText> </div> <div className="login-graviton"> <TextField name="text1" hintText="Email Address or Username" fullWidth={true}></TextField> <TextField name="text2" hintText="<PASSWORD>" fullWidth={true}></TextField> <div className="text-center marginBottom1 marginTop5"> <button style={Styles.footerbtn}>Sign Up</button> </div> </div> </Card> </div> </div> ); const mapDispatchToProps = (dispatch) => ({ facebookSignUpSuccess: (user) => { dispatch(push('/signupSuccess')); }, facebooSignUpFailure: (error) => { dispatch(push('/signupFailure')); }, googleSignUpSuccess: (user) => { dispatch(push('/signupSuccess')); }, googleSignUpFailure: (error) => { dispatch(push('/signupFailure')); }, }); export default connect(null, mapDispatchToProps)(SignUp); <file_sep>/app/src/sagas/index.js import { all, call, fork, put, take } from 'redux-saga/effects'; export default function* sagas() { yield all([ ]) };
8396142625011a12b828c45cd246c87ffc35b1a0
[ "JavaScript" ]
14
JavaScript
anjanasarath/graviton-ui-web
62be58b8b70164de23609614c062acb4516b8776
a7ac5fa7099a6c9834ec4960b2f4dab89a8db97b
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Servelets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.sql.*; import com.mysql.jdbc.Driver; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Randy */ @WebServlet(name = "Empleados", urlPatterns = {"/Empleados"}) public class Empleados extends HttpServlet { Connection con = null; Statement st = null; ResultSet rs = null; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { // try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/pronovato_jsp_2020?user=root&password="); st = con.createStatement(); String sql = ("SELECT * FROM empleados"); String where = " WHERE 1 = 1"; String nombre = request.getParameter("nombre"); if (nombre != null) { //nombre= nombre.replaceAll("'", "\\\\'"); nombre=this.mysql_real_scape_string(nombre); //where = where + " and nombre = '" + nombre + "';"; where = where + " and nombre =?"; } sql = sql + where; //rs = st.executeQuery(sql); PreparedStatement preparar = con.prepareStatement(sql); if (nombre != null) { preparar.setString(1, nombre); } rs=preparar.executeQuery(); while (rs.next()) { out.print("</tr>"); out.print("<th scope=\"row\">" + rs.getString(1) + "</th>" + "<td>" + rs.getString(2) + "</td>" + "<td>" + rs.getString(3) + "</td>" + "<td>" + rs.getString(4) + "</td>"); out.print("<td>"); out.print("<a href=\"editar_empleados.jsp?id=" + rs.getString(1) + "&nombre=" + rs.getString(2) + "&direccion=" + rs.getString(3) + "&telefono=" + rs.getString(4) + "\"" + "data-toggle=\"tooltip\" data-placement=\"top\" title=\"Editar usuario\">" + "<i class=\"fa fa-pencil\" aria-hidden=\"true\"></i>"); out.print("</a>"); out.print("<a href=\"eliminar_empleados.jsp?id=" + rs.getString(1) + "\" " + "data-toggle=\"tooltip\" data-placement=\"top\" title=\"Eliminar usuario\">" + "<i class=\"fa fa-trash-o ml-2\" aria-hidden=\"true\"></i>"); out.print("</a>"); out.print("</td>"); out.print("</tr>"); } } catch (Exception e) { out.println("error en Mysql " + e.getMessage()); } // } finally { try { con.close(); } catch (SQLException ex) { Logger.getLogger(Empleados.class.getName()).log(Level.SEVERE, null, ex); } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> public String mysql_real_scape_string(String texto){ texto=texto.replaceAll("\\\\", "\\\\\\\\'"); texto=texto.replaceAll("\\n", "\\\\n'"); texto=texto.replaceAll("\\r", "\\\\r'"); texto=texto.replaceAll("\\t", "\\\\t"); texto=texto.replaceAll("'", "\\\\'"); return texto; } } <file_sep>-- phpMyAdmin SQL Dump -- version 4.8.4 -- https://www.phpmyadmin.net/ -- -- Servidor: localhost -- Tiempo de generación: 15-11-2019 a las 00:42:59 -- Versión del servidor: 10.2.22-MariaDB-1:10.2.22+maria~bionic -- Versión de PHP: 7.3.9-1+ubuntu18.04.1+deb.sury.org+1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `jsp` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `user` -- CREATE TABLE `user` ( `id` int(11) NOT NULL, `user` varchar(50) NOT NULL, `password` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Volcado de datos para la tabla `user` -- INSERT INTO `user` (`id`, `user`, `password`) VALUES (1, 'admin', '<PASSWORD>'), (2, 'eugenio', '<PASSWORD>'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `user` -- ALTER TABLE `user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; 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>-- phpMyAdmin SQL Dump -- version 4.8.4 -- https://www.phpmyadmin.net/ -- -- Servidor: localhost -- Tiempo de generación: 11-11-2019 a las 15:26:25 -- Versión del servidor: 10.2.22-MariaDB-1:10.2.22+maria~bionic -- Versión de PHP: 7.3.9-1+ubuntu18.04.1+deb.sury.org+1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `jsp` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `empledos` -- CREATE TABLE `empledos` ( `id` int(11) NOT NULL, `nombre` varchar(100) NOT NULL, `direccion` varchar(100) NOT NULL, `telefono` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Volcado de datos para la tabla `empledos` -- INSERT INTO `empledos` (`id`, `nombre`, `direccion`, `telefono`) VALUES (1, 'eugenio', 'Mexco', '7122245454'), (2, 'Juana', 'Bolivia', '56788445121'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `empledos` -- ALTER TABLE `empledos` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `empledos` -- ALTER TABLE `empledos` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; 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 */;
1bdad44f08c45fa95d652d5c01648309f2c56e82
[ "Java", "SQL" ]
3
Java
zhimbaya/pronovato-jsp-2020
904d146e720a3a51cf7937dfaaf96a71f618e7dc
24a3c7f808bc4d36e3b05fda8c2f503df57b5db9
refs/heads/master
<file_sep>class CreateAuditions < ActiveRecord::Migration def change create_table :auditions do |t| t.string :title, null: false t.string :monologue, null: false t.timestamps end end end <file_sep>get '/' do redirect '/' end<file_sep>get '/' do @auditions = Audition.all erb :'index' end get '/auditions/new' do erb :'new' end post '/auditions/new' do @audition = Audition.new(params[:audition]) if @audition.save redirect "/" end end get '/auditions/:id' do @audition = Audition.find(params[:id]) erb :'show' end get '/auditions/:id/edit' do @audition = Audition.find(params[:id]) erb :'/edit' end put '/auditions/:id' do audition = Audition.find(params[:id]) audition.update_attributes(params[:audition]) redirect "auditions/#{audition.id}" end delete '/auditions/:id' do audition = Audition.find(params[:id]) audition.destroy redirect '/' end
87798e2d4990af6f4748d4a94764adc7fea83e07
[ "Ruby" ]
3
Ruby
nyc-bobolinks-2015/ian_crud
bbfb8ab8c4a43b68d1c39d55be85285c1fbd5067
a9fd33fd4859e33ce6bfe05a77166d650d1eb75b
refs/heads/master
<file_sep>require_relative('../db/sql_runner.rb') require_relative('./film.rb') class Customer attr_reader :id attr_accessor :name, :funds def initialize(options) @id = options['id'].to_i if options['id'] @name = options['name'] @funds = options['funds'] end #CREATE one instance def save() sql = "INSERT INTO customers (name, funds) VALUES ($1, $2) RETURNING id" values = [@name, @funds] customer = SqlRunner.run(sql, values)[0] @id = customer['id'].to_i() end #DELETE ALL - class method def self.delete_all() sql = "DELETE FROM customers" SqlRunner.run(sql) end #FIND / READ - class method def self.all() sql = "SELECT * FROM customers" customers_array = SqlRunner.run(sql) customers = customers_array.map { |customer_hash| Customer.new(customer_hash)} return customers end #UPDATE one instance def update() sql = "UPDATE customers SET (name, funds) = ($1, $2) WHERE id = $3" values = [@name, @funds, @id] SqlRunner.run(sql, values) end #DELETE one instance def delete_one() sql = "DELETE FROM customers WHERE id = $1" values = [@id] SqlRunner.run(sql, values) end #returning all films for one customer def films() sql = "SELECT films.* FROM films INNER JOIN tickets ON films.id = tickets.film_id WHERE tickets.customer_id = $1" values = [@id] films_array = SqlRunner.run(sql, values) films = films_array.map { |film_hash| Film.new(film_hash)} return films end #decreasing customer funds when buying tickets def decrease_funds(film) new_funds = @funds.to_i() - film.price.to_i() return new_funds end def buy_ticket(film) @funds = decrease_funds(film) sql = "UPDATE customers SET (name, funds) = ($1, $2) WHERE id = $3" values = [@name, @funds, @id] SqlRunner.run(sql, values) end #check how many tickets bought per customer def tickets_bought() tickets_array = films() number_of_tickets = tickets_array.count return "#{@name} has bought #{number_of_tickets} tickets." end end <file_sep>require('pry') require_relative('./models/customer.rb') require_relative('./models/film.rb') require_relative('./models/ticket.rb') Ticket.delete_all() Customer.delete_all() Film.delete_all() customer1 = Customer.new({ 'name' => '<NAME>', 'funds' => '35' }) customer1.save() customer2 = Customer.new({ 'name' => '<NAME>', 'funds' => '20' }) customer2.save() customer3 = Customer.new({ 'name' => '<NAME>', 'funds' => '42' }) customer3.save() customer4 = Customer.new({ 'name' => '<NAME>', 'funds' => '61' }) customer4.save() film1 = Film.new({ 'title' => 'Pulp Fiction', 'price' => '4' }) film1.save() film2 = Film.new({ 'title' => 'Suspiria', 'price' => '5' }) film2.save() film3 = Film.new({ 'title' => 'Cloud Atlas', 'price' => '6' }) film3.save() ticket1 = Ticket.new({ 'customer_id' => customer1.id, 'film_id' => film1.id }) ticket1.save() ticket2 = Ticket.new({ 'customer_id' => customer2.id, 'film_id' => film2.id }) ticket2.save() ticket3 = Ticket.new({ 'customer_id' => customer3.id, 'film_id' => film2.id }) ticket3.save() ticket4 = Ticket.new({ 'customer_id' => customer4.id, 'film_id' => film3.id }) ticket4.save() ticket5 = Ticket.new({ 'customer_id' => customer1.id, 'film_id' => film3.id }) ticket5.save() ticket6 = Ticket.new({ 'customer_id' => customer2.id, 'film_id' => film1.id }) ticket6.save() # customer2.name = '<NAME>' # customer2.update() # customer1.delete_one() # film1.title = 'Reservoir Dogs' # film1.update() # film2.delete_one() customer1.buy_ticket(film1) customer2.buy_ticket(film2) customer3.buy_ticket(film2) customer4.buy_ticket(film3) customer1.buy_ticket(film3) customer2.buy_ticket(film1) customers = Customer.all() films = Film.all() tickets = Ticket.all() binding.pry nil
be3819d52e2a3c6790a33d34c7b94a54fa9546c0
[ "Ruby" ]
2
Ruby
just-ally/Week3_weekend_cinema_homework
09ca6a1fa5ecb210b6c96cbfda0b0b62255b826b
56925be10886b5ca7fe3bdc0794e9875b5ef4bea
refs/heads/master
<repo_name>liuzhihangs/security-demo<file_sep>/src/main/java/cn/ipaynow/security/demo/demo/filter/JwtLoginFilter.java package cn.ipaynow.security.demo.demo.filter; import cn.ipaynow.security.demo.demo.bean.DbUser; import com.fasterxml.jackson.databind.ObjectMapper; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.User; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.Date; /** * @author liuzhihang * @date 2019-06-03 19:32 */ public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter { private AuthenticationManager authenticationManager; public JwtLoginFilter(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Override public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException { try { //获取前台过来的user信息, 解析用户凭证 DbUser dbUser = new ObjectMapper().readValue(req.getInputStream(), DbUser.class); return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(dbUser.getUserName(), dbUser.getPassword(), new ArrayList<>())); } catch (IOException e) { throw new RuntimeException(e); } } /** * 登陆成功后 生成token * * * @param req * @param res * @param chain * @param auth */ @Override protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) { String token = Jwts.builder() .setSubject(((User) auth.getPrincipal()).getUsername()) .setIssuedAt(new Date()) //设置有效期7天 .setExpiration(localDateTimeToDate(LocalDateTime.now().plusDays(7))) .signWith(SignatureAlgorithm.HS512, "jwtSecurity") .compact(); //将生成token返回给前台 res.addHeader("Authorization", "Bearer " + token); } public static Date localDateTimeToDate(LocalDateTime localDateTime) { ZoneId zone = ZoneId.systemDefault(); Instant instant = localDateTime.atZone(zone).toInstant(); return Date.from(instant); } } <file_sep>/src/main/java/cn/ipaynow/security/demo/demo/service/WebSecurityConfig.java package cn.ipaynow.security.demo.demo.service; import cn.ipaynow.security.demo.demo.filter.JwtPerTokenFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import javax.annotation.Resource; /** * @author liuzhihang * @date 2019-06-03 14:25 */ @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailServiceImpl userDetailServiceImpl; @Resource(name = "logoutSuccessHandlerImpl") private LogoutSuccessHandler logoutSuccessHandler; @Resource(name = "authenticationEntryPointImpl") private AuthenticationEntryPoint authenticationEntryPoint; @Resource(name = "authenticationSuccessHandlerImpl") private AuthenticationSuccessHandler authenticationSuccessHandler; @Resource(name = "authenticationFailureHandlerImpl") private AuthenticationFailureHandler authenticationFailureHandler; @Resource(name = "accessDeniedHandlerImpl") private AccessDeniedHandler accessDeniedHandler; @Resource private JwtPerTokenFilter jwtPerTokenFilter; /** * 配置用户信息 * * @param auth * @throws Exception */ @Autowired public void configureUserInfo(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailServiceImpl); } @Override protected void configure(HttpSecurity http) throws Exception { /** * 表单登录:使用默认的表单登录页面和登录端点/login进行登录 * 退出登录:使用默认的退出登录端点/logout退出登录 * 记住我:使用默认的“记住我”功能,把记住用户已登录的Token保存在内存里,记住30分钟 * 权限:除了/toHome和/toUser之外的其它请求都要求用户已登录 * 注意:Controller中也对URL配置了权限,如果WebSecurityConfig中和Controller中都对某文化URL配置了权限,则取较小的权限 */ http // 使用JWT, 关闭session .csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and().httpBasic().authenticationEntryPoint(authenticationEntryPoint) // 登录的权限, 成功返回信息, 失败返回信息 .and() .formLogin().permitAll() .loginProcessingUrl("/login") .successHandler(authenticationSuccessHandler) .failureHandler(authenticationFailureHandler) // 登出的权限以及成功后的处理器 .and() .logout().permitAll().logoutSuccessHandler(logoutSuccessHandler) // 配置url 权限 antMatchers: 匹配url 权限 .and() .authorizeRequests() .antMatchers("/login", "/toHome", "/toUser").permitAll() .antMatchers("/toAdmin").hasRole("ADMIN") .antMatchers("/toEmployee").access("hasRole('ADMIN') or hasRole('EMPLOYEE')") // 其他需要登录才能访问 .anyRequest().authenticated() // 访问无权限 location 时 .and() .exceptionHandling().accessDeniedHandler(accessDeniedHandler) // 记住我 .and() .rememberMe().rememberMeParameter("remember-me").userDetailsService(userDetailServiceImpl).tokenValiditySeconds(300) // 自定义过滤 .and() .addFilterBefore(jwtPerTokenFilter, UsernamePasswordAuthenticationFilter.class).headers().cacheControl(); // .addFilter(new JwtLoginFilter(authenticationManager())).addFilter(new JwtAuthenticationFilter(authenticationManager())); } /** * 密码加密器 */ @Bean public PasswordEncoder passwordEncoder() { /** * BCryptPasswordEncoder:相同的密码明文每次生成的密文都不同,安全性更高 */ return new BCryptPasswordEncoder(); } } <file_sep>/src/main/java/cn/ipaynow/security/demo/demo/bean/DbUser.java package cn.ipaynow.security.demo.demo.bean; import lombok.Data; import java.io.Serializable; /** * @author liuzhihang * @date 2019-06-04 10:04 */ @Data public class DbUser implements Serializable { private String userName; private String password; private String role; } <file_sep>/src/main/java/cn/ipaynow/security/demo/demo/handle/AccessDeniedHandlerImpl.java package cn.ipaynow.security.demo.demo.handle; import cn.ipaynow.security.demo.demo.bean.RespBean; import com.alibaba.fastjson.JSON; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 当用户访问无权限页面时, 返回信息 * * @author liuzhihang * @date 2019-06-04 14:03 */ @Component public class AccessDeniedHandlerImpl implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(JSON.toJSONString(new RespBean("0003", "用户无权限访问 "))); } } <file_sep>/src/main/java/cn/ipaynow/security/demo/demo/controller/PageController.java package cn.ipaynow.security.demo.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * @author liuzhihang * @date 2019-06-04 10:19 */ @Controller public class PageController { @GetMapping("/toAdmin") @ResponseBody public String toAdmin() { System.out.println("PageController.toAdmin|收到请求"); return "收到 toAdmin 请求"; } @GetMapping("/toEmployee") @ResponseBody public String toEmployee() { System.out.println("PageController.toEmployee|收到请求"); return "收到 toEmployee 请求"; } @GetMapping("/toUser") @ResponseBody public String toUser() { System.out.println("PageController.toUser|收到请求"); return "toUser 请求成功"; } @RequestMapping("/toAbout") @ResponseBody public String toAbout() { System.out.println("PageController.toAbout|收到请求"); return "about 成功"; } @RequestMapping("/toHome") @ResponseBody public String toHome() { System.out.println("PageController.toHome|收到请求"); return "home 成功"; } } <file_sep>/src/main/java/cn/ipaynow/security/demo/demo/handle/LogoutSuccessHandlerImpl.java package cn.ipaynow.security.demo.demo.handle; import cn.ipaynow.security.demo.demo.bean.RespBean; import com.alibaba.fastjson.JSON; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author liuzhihang * @date 2019-06-04 14:40 */ @Component public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler { @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(JSON.toJSONString(new RespBean("0000", "用户登出成功"))); } } <file_sep>/src/main/java/cn/ipaynow/security/demo/demo/handle/AuthenticationFailureHandlerImpl.java package cn.ipaynow.security.demo.demo.handle; import cn.ipaynow.security.demo.demo.bean.RespBean; import com.alibaba.fastjson.JSON; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 用户登录认证失败返回的信息 * * @author liuzhihang * @date 2019-06-04 13:57 */ @Component public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(JSON.toJSONString(new RespBean("0002", "登录失败"))); } }
089b096f501cb1dfa76afc743c5932c2dcc3a6b5
[ "Java" ]
7
Java
liuzhihangs/security-demo
998fa2bab869ccaf1f995c6b3c89088769e078e1
82349dd20d487d74f07a61702fea10d668bbda4c
refs/heads/master
<repo_name>TheNilusss/Test<file_sep>/src/main/java/com/Studium/CutomerService/Controller/CustomerController.java package com.Studium.CutomerService.Controller; import com.Studium.CutomerService.entity.Customer; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class CustomerController { @GetMapping("/Hello") public Customer hallo() { Customer l_customer = new Customer("Nils","Heinisch"); return l_customer; } /*@Autowired private RestTemplate restTemplate; */ @GetMapping("/gatsby") public ResponseEntity<Customer> hallo2() { RestTemplate restTemplate = new RestTemplate(); String fooResourceUrl = "http://localhost:8080/Hello"; ResponseEntity<Customer> response = restTemplate.getForEntity(fooResourceUrl, Customer.class); System.out.println(response); return response; } } <file_sep>/README.md //Erstelle Benutzer curl -X "POST" "http://localhost:8081/createCustomer?firstName=Max&lastName=Mustermann //Zeige Produkte curl -X "GET" "http://localhost:8082/getProducts //Erstelle einen Warenkorb curl -X "POST" "http://localhost:8083/createCart?customerName=Max //Füge Artikel dem Warenkorb hinzu curl -X "POST" "http://localhost:8083/addToCart?customerName=Max&productName=Kaffee <file_sep>/settings.gradle rootProject.name = 'CutomerService'
763a69fb7c801da58a2649306081e0a076769903
[ "Markdown", "Java", "Gradle" ]
3
Java
TheNilusss/Test
490a80d73d2edc8110a25f029705691aae09f9be
6809d1388ab241818c7021779464c18c5eb98d78
refs/heads/master
<repo_name>JesseShawCodes/stegato<file_sep>/README.md # STEGATO Stegato was created as an application to rate all of your music. After registering your account, you will be able to search and rate all music that is in the iTunes database. When your rating is submitted, that album is added to your music dashboard. Click [here](http://stegato.netlify.com/) to use the application! Search for an artist ![Search for an artist](/src/images/IMG_5489.PNG) Rate the project ![Rate the Project](/src/images/IMG_5490.PNG) Submit it to your dashboard and the Stegato database ![Submit to Dashboard](/src/images/IMG_5491.PNG) After rating an artist’s project, you can see on the leaderboard where your project ranks within the Stegato community leaderboard. This application is powered by iTunes and last.fm API’s. This application was designed as a capstone project while studying at Thinkful. ## Features - React JS - Redux - enzyme - Node JS - Express - Passport HTTP - Passport JWT - bcrypt - jsonwebtoken - Mocha - Chai - MongoDB/mongoose - mLab - TravisCI - Heroku - jQuery ## API Documentation Stegato utilizes the last.fm and iTunes api. The last.fm api is used to correct any spelling errors from the user. For example, if a user inputs "davidbowie", the last.fm api corrects this input to "<NAME>." From there, all albums by the artist searched for by the user is returned from the last.fm API.<file_sep>/src/search/containers/root.js import React from 'react'; import { Provider, connect } from 'react-redux'; import configureStore from '../store'; import AsyncApp from './AsyncApp'; const store = configureStore(); export const SearchRoot = (props) => { return ( <Provider store={store}> <AsyncApp user={props.user} /> </Provider> ); } const mapStateToProps = state => ({ hasAuthToken: state.auth.authToken !== null, loggedIn: state.auth.currentUser !== null, user: state.auth.currentUser, }); export default connect(mapStateToProps)(SearchRoot); <file_sep>/src/search/components/albumrow.js import React from 'react'; import './albumrow.css'; import Rating from './rating' export default function AlbumRow(props) { var ratings = <Rating Artist={props.artist} Album={props.album} Genre={props.genre} Artwork={props.imagelink} buyOnItunes={props.buyOnItunes} collectionId={props.collectionId} user={props.user} successMessage={props.successFunction} loginMessage={props.loginFunction} releaseDate={props.releaseDate}/> return ( <div className="grid-item"> <div className="flip-container" > <div className="flipper"> <div className="front"> <img className="card-img-top" src={props.imagelink} alt="album cover"/> </div> <div className="back"> <div className="card-block"> <h5 className="text-bold">{props.artist}</h5> <h5 className="text-bold">{props.album}</h5> <p className="text-bold">{props.genre}</p> {ratings} <section className="buttons"> <a href={props.buyOnItunes} target="_blank" alt="Buy on Itunes" role="presentation"><button className="itunes-link"><i className="fa fa-apple" aria-hidden="true" title="Click to buy on Itunes" alt="Buy on Itunes" role="presentation"></i></button></a> </section> </div> </div> </div> </div> </div> ); }; AlbumRow.defaultProps = { artist: 'Artist', album: 'Album', genre: 'Genre', imagelink: "http://is2.mzstatic.com/image/thumb/Music/v4/ae/f9/97/aef9970e-7031-6f03-45d2-a12c0d81383e/source/100x100bb.jpg", buyOnItunes: "http://www.itunes.com" }; <file_sep>/src/splash.test.js import React from 'react'; import { shallow } from 'enzyme'; import Splash from './splash'; describe('<Splash />', () => { it('Renders without crashing', () => { shallow(<Splash />); }); }); <file_sep>/src/search/actions.test.js import {RECEIVE_MUSIC_FROM_API, SEARCH_ITUNES_REQUEST, SEARCH_MUSIC_ERROR, searchMusicRequest, searchMusicSuccess, searchMusicError} from './actions' describe('searchMusicRequest', () => { it('Should return the action', () => { const searchTerm = 'Deftones'; const action = searchMusicRequest(searchTerm); expect(action.type).toEqual(SEARCH_ITUNES_REQUEST); }); }); describe('searchMusicSuccess', () => { it('Should return the action', () => { const searchTerm = 'Deftones'; const music = searchTerm; const error = undefined; const action = searchMusicSuccess(searchTerm); expect(action.type).toEqual(RECEIVE_MUSIC_FROM_API); }); }); describe('searchMusicError', () => { it('Should return the action', () => { const searchTerm = 'Deftones'; const music = searchTerm; const error = undefined; const action = searchMusicError(searchTerm); expect(action.type).toEqual(SEARCH_MUSIC_ERROR); }); }); <file_sep>/src/auth/logout/logoutpage.js import React from 'react'; import './logout.css'; export default function Logoutpage() { return ( <section className="login-form-section"> <h2>You are now logged out</h2> </section> ); } <file_sep>/src/search/containers/AsyncApp.test.js import React from 'react'; import { shallow } from 'enzyme'; import { AsyncApp } from './AsyncApp'; describe('<AsyncApp />', () => { it('Renders without crashing', () => { shallow(<AsyncApp />); }); }); <file_sep>/src/header.js import React from 'react'; import './header.css'; import { connect } from 'react-redux'; import { Redirect } from 'react-router-dom'; import { clearAuthToken } from './auth/localstorage'; import logo from './images/stegato_logo.png'; class Heading extends React.Component { logOut() { clearAuthToken(); if (this.props.hasAuthToken === false) { return <Redirect to="/logout" />; } return false; } render() { let logOutButton; let dashboardButton; let loginButton; let registerButton; let listItems; if (this.props.loggedIn) { logOutButton = ( <a href="/logout" onClick={() => this.logOut()}>Logout</a> ); dashboardButton = ( <a href="/dashboard">Dashboard</a> ); listItems = ( <ul> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/leaderboard">Leaderboard</a></li> <li><a href="/search">Search</a></li> <li>{dashboardButton}</li> <li>{logOutButton}</li> </ul> ); } else { loginButton = ( <a href="/login">Login</a> ); registerButton = ( <a href="/register">Register</a> ); listItems = ( <ul> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/leaderboard">Leaderboard</a></li> <li><a href="/search">Search</a></li> <li>{loginButton}</li> <li>{registerButton}</li> </ul> ); } return ( <header> <div className="container"> <a href="/"> <img src={logo} alt="Stegato Logo" className="logo" /> </a> <nav> {listItems} </nav> </div> </header> ); } } const mapStateToProps = state => ({ loggedIn: state.auth.currentUser !== null, name: state.auth.currentUser, }); export default connect(mapStateToProps)(Heading); <file_sep>/src/footer/footer.js import React from 'react'; import './footer.css'; import logo from '../images/stegatto_logo2.png' export default function Footer() { return ( <footer> <div className="footer-content-1"> <div className="row"> <div className="col-lg-8 mx-auto text-center"> <h2 className="section-heading">Questions about Stegato?</h2> <hr className="primary"></hr> <p className="contactp">If you have any questions regarding this project, feel free to contact <NAME> at any of the points of contact below:</p> </div> </div> <div className="contactpoints"> <div className="point-of-contact"> <i className="fa fa-phone fa-3x sr-contact"></i> <p className="point-of-contact-link"> <a href="tel:410-703-6125" >410-703-6125</a> </p> </div> <div className="point-of-contact"> <i className="fa fa-envelope-o fa-3x sr-contact"></i> <p className="point-of-contact-link"> <a href="mailto:<EMAIL>"><EMAIL></a> </p> </div> <div className="point-of-contact"> <i className="fa fa-github fa-3x sr-contact"></i> <p className="point-of-contact-link"> <a href="https://github.com/JesseShawCodes" target="_blank" rel="noopener noreferrer">GitHub</a> </p> </div> </div> <section className="footer-logo"> <a href="/"> <img src={logo} alt="Stegatto Round Logo" className="round-logo"></img> </a> </section> <section className="footer-menu"> <ul> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/search">Search</a></li> </ul> </section> </div> </footer> ); }<file_sep>/src/search/containers/AsyncApp.js import React from 'react'; import { connect } from 'react-redux'; import Spinner from 'react-spinkit'; import './searchresults.css'; import $ from 'jquery'; import { NotificationContainer, NotificationManager } from 'react-notifications'; // Style Sheet import 'react-notifications/lib/notifications.css'; // Add material-ui import Typography from '@material-ui/core/Typography'; import ExpansionPanel from '@material-ui/core/ExpansionPanel'; import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary'; import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails'; import Albumrow from '../components/albumrow'; import { searchItunes } from '../actions'; export class AsyncApp extends React.Component { search(e) { const key = '48a68fa743a6e709380166a2342c0c27'; const url = 'https://ws.audioscrobbler.com/2.0/'; const self = this; e.preventDefault(); if (this.input.value.trim() === '') { return; } const settings = { artist: `${this.input.value}`, api_key: key, method: 'artist.getCorrection', format: 'json', autocorrect: 1, }; $.getJSON( url, settings, result => self.props.dispatch( searchItunes(result.corrections.correction.artist.name), ), ); } successMessage() { NotificationManager.success('', 'Your rating has been received and your Dashboard has been updated!', 5000); } loginMessage() { NotificationManager.error('Please navigate to the top of the page to login or register.', 'You must be a Stegato user if you want to rate music.', 5000); } renderResults() { if (this.props.loading) { return <Spinner fadeIn="none" />; } if (this.props.error) { return <strong className="error-message">{this.props.error}</strong>; } if (this.props.music === undefined) { return <h1>There is a problem reading results from the API</h1>; } const music = []; for (let i = 0; i < this.props.music.length; i += 1) { music[i] = (<Albumrow key={i} artist={this.props.music[i].artistName} album={this.props.music[i].collectionName} genre={this.props.music[i].primaryGenreName} imagelink={this.props.music[i].artworkUrl100} buyOnItunes={this.props.music[i].collectionViewUrl} collectionId={this.props.music[i].collectionId} releaseDate={this.props.music[i].releaseDate} user={this.props.user} successFunction={this.successMessage} loginFunction={this.loginMessage} /> ); } return ( <div className="search-results-rendered"> {music} </div> ); } render() { // const { classes } = props; return ( <div className="search-section"> <NotificationContainer /> <ExpansionPanel> <ExpansionPanelSummary expandIcon="+"> <Typography>Update from September 11, 2018</Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> Please note. If you are viewing this page from https://stegato.netlify.com/search, you may receive an error when searching for an artist. Please make sure you are viewing this page from http://stegato.netlify.com/search (not https). The iTunes API is currently returning an error when a search is requested from a secure site. We are working on addressing this issue. </Typography> </ExpansionPanelDetails> </ExpansionPanel> <form className="musicsearch" onSubmit={e => this.search(e)}> <label htmlFor="artist" className="artist-search-label"> Artist <input type="search" ref={input => this.input = input} /> </label> <button className="search-button" type="submit">Search</button> </form> {this.renderResults()} </div> ); } } const mapStateToProps = state => ({ music: state.music, loading: state.loading, error: state.error, }); export default connect(mapStateToProps)(AsyncApp); <file_sep>/src/app.js import React from 'react'; import { connect } from 'react-redux'; import './index.css'; import { BrowserRouter as Router, Route, withRouter } from 'react-router-dom'; import Heading from './header'; import Landingpage from './landingpage'; import Logoutpage from './auth/logout/logoutpage'; import SearchRoot from './search/containers/root'; import Footer from './footer/footer'; import Registerroot from './auth/register/root'; import Loginroot from './auth/login/root'; import Dashboardroot from './dashboard/root'; import Howto from './how to/how-to'; import LeaderboardRoot from './leaderboard/root'; import { refreshAuthToken } from './auth/actions/auth'; export class App extends React.Component { componentWillReceiveProps(nextProps) { if (nextProps.loggedIn && !this.props.loggedIn) { // When we are logged in, refresh the auth token periodically this.startPeriodicRefresh(); } else if (!nextProps.loggedIn && this.props.loggedIn) { // Stop refreshing when we log out this.stopPeriodicRefresh(); } } componentWillUnmount() { this.stopPeriodicRefresh(); } startPeriodicRefresh() { this.refreshInterval = setInterval( () => this.props.dispatch(refreshAuthToken()), 60 * 60 * 1000, // One hour ); } stopPeriodicRefresh() { if (!this.refreshInterval) { return; } clearInterval(this.refreshInterval); } render() { const user = this.props.user; return ( <Router> <main> <Heading hasAuthToken={this.props.hasAuthToken} /> <Route exact path="/" component={Landingpage} /> <Route exact path="/about" component={Howto} /> <Route exact path="/login/" component={Loginroot} /> <Route exact path="/register/" component={Registerroot} /> <Route exact path="/search/" component={SearchRoot} user={user} /> <Route exact path="/logout/" component={Logoutpage} /> <Route exact path="/dashboard/" component={Dashboardroot} /> <Route exact path="/leaderboard/" component={LeaderboardRoot} /> <Footer /> </main> </Router> ); } } const mapStateToProps = state => ({ hasAuthToken: state.auth.authToken !== null, loggedIn: state.auth.currentUser !== null, user: state.auth.currentUser, }); // Deal with update blocking - https://reacttraining.com/react-router/web/guides/dealing-with-update-blocking export default withRouter(connect(mapStateToProps)(App)); <file_sep>/src/dashboard/root.js import React, { Component } from 'react' import { Dashboardpage } from './dashboard'; import {connect} from 'react-redux'; import requiresLogin from '../auth/requires-login'; // import configureStore from '../store' // const store = configureStore() export class Dashboardroot extends Component { render() { return ( <Dashboardpage username={this.props.username} /> ) } } const mapStateToProps = state => { const {currentUser} = state.auth; return { username: state.auth.currentUser.username, name: `${currentUser.firstName} ${currentUser.lastName}`, protectedData: state.protectedData.data }; }; export default requiresLogin()(connect(mapStateToProps)(Dashboardroot)); <file_sep>/src/leaderboard/root.js import React, { Component } from 'react' import { Dashboardpage } from './dashboard'; export default class LeaderboardRoot extends Component { render() { return ( <Dashboardpage username={this.props.username} /> ) } } <file_sep>/src/leaderboard/dashboardalbums.js import React from 'react'; import './dashboardalbums.css'; import 'react-notifications/lib/notifications.css'; export default class Dashboardalbums extends React.Component { render() { return ( <div className="grid-item"> <div className="flip-container" > <div className="flipper"> <div className="front"> <img className="card-img-top" src={this.props.imagelink} alt="album cover"/> </div> <div className="back"> <div className="card-block"> <div className="delete-button"> </div> <p className="text-bold">{this.props.artist}</p> <p className="text-bold">{this.props.album}</p> <p className="text-bold">Rating: {this.props.rating}</p> <p className="text-bold">{this.props.genre}</p> <section className="buttons"> <a href={this.props.buyOnItunes} target="_blank" alt="Buy on Itunes" role="presentation"><button className="itunes-link"><i className="fa fa-apple" aria-hidden="true" title="Click to buy on Itunes" alt="Buy on Itunes" role="presentation"></i></button></a> </section> </div> </div> </div> </div> </div> ) } }; Dashboardalbums.defaultProps = { artist: 'Artist', album: 'Album', genre: 'Genre', imagelink: "http://is2.mzstatic.com/image/thumb/Music/v4/ae/f9/97/aef9970e-7031-6f03-45d2-a12c0d81383e/source/100x100bb.jpg", buyOnItunes: "http://www.itunes.com" }; <file_sep>/src/search/actions.js import fetch from 'cross-fetch'; export const RECEIVE_MUSIC_FROM_API = 'RECEIVE_MUSIC_FROM_API'; export const SEARCH_ITUNES_REQUEST = 'SEARCH_ITUNES_REQUEST'; export const SEARCH_MUSIC_ERROR = 'SEARCH_MUSIC_ERROR'; export const searchMusicRequest = () => ({ type: SEARCH_ITUNES_REQUEST, }); export const searchMusicSuccess = music => ({ type: RECEIVE_MUSIC_FROM_API, music, }); export const searchMusicError = error => ({ type: SEARCH_MUSIC_ERROR, error, }); // Itunes API Links // var itunesUrl = "https://itunes.apple.com/search?term="; // var albumUrl = "https://itunes.apple.com/lookup?id="; function searchItunesDatabase(name) { const artist = name; const searchTerm = artist.split(' ').join('+'); return fetch(`http://itunes.apple.com/search?term=${searchTerm}&entity=album`, { method: 'GET', // *GET, POST, PUT, DELETE, etc. }) .then(function(res) { if (!res.ok) { return Promise.reject(res.statusText); } return res.json() }) .then(function(data) { data.results.map(music => music) return data.results }) } function search(name) { return new Promise((resolve) => { resolve(searchItunesDatabase(name)); }); } export const searchItunes = name => dispatch => { dispatch(searchMusicRequest()); search(name) .then( function(data) { dispatch(searchMusicSuccess(data)) } ) .catch(error => dispatch(searchMusicError(error))); }; <file_sep>/src/leaderboard/dashboard.js import React from 'react'; import Dashboardalbums from './dashboardalbums'; import './dashboard.css'; import fetch from 'cross-fetch'; import {NotificationContainer, NotificationManager} from 'react-notifications'; import 'react-notifications/lib/notifications.css'; export class Dashboardpage extends React.Component { constructor(props) { super(props); this.state = { cards: [], reloading: false } this.updateDashboard = this.updateDashboard.bind(this); this.updateDashboardTest = this.updateDashboardTest.bind(this); this.fetchMusicData = this.fetchMusicData.bind(this); } updateDashboardTest() { setTimeout( function() { this.setState({reloading: true}) }.bind(this), 3000 ) } fetchMusicData() { fetch(`https://stegato-api.herokuapp.com/music-data/get-data/leaderboard`) .then(results => { return results.json() }) .then(data => { let results = [] for (var i = 0; i < data.length; i++) { results[i] = <Dashboardalbums key={i} artist={data[i].artist} album={data[i].album} genre={data[i].genre} imagelink={data[i].artwork} buyOnItunes={data[i].itunesLink} rating={data[i].rating} collectionId={data[i].collectionId} user={data[i].user} mongoId={data[i]._id} updateDashboard={this.updateDashboardTest} /> } this.setState({ cards: results, reloading: false }) }) } updateDashboard() { this.fetchMusicData(); } createNotification = (type) => { return () => { switch (type) { case 'info': NotificationManager.info('Info message'); break; case 'success': NotificationManager.success('Success message', 'Title here'); break; case 'warning': NotificationManager.warning('Warning message', 'Close after 3000ms', 3000); break; case 'error': NotificationManager.error('Error message', 'Click me!', 5000, () => { console.log('Error'); }); break; default: //do Nothing } }; }; componentDidMount() { this.fetchMusicData() } render() { let message = this.state.cards return ( <div className="dashboard-items"> {message} <NotificationContainer /> </div> ); } } <file_sep>/src/landingpage.js import React from 'react'; import Splash from './splash'; export default function Landingpage() { return ( <div id="main"> <Splash /> </div> ); } <file_sep>/src/search/components/rating.js import React from 'react'; import './rating.css' export default class Rating extends React.Component { constructor(props) { super(props) this.state = { rating: undefined, ratingsStyle: <section className="rating"> <span className="five-star" onClick={this.fiveStars} value={5}>☆</span> <span className="four-star" onClick={this.fourStars} value={4}>☆</span> <span className="three-star" onClick={this.threeStars} value={3}>☆</span> <span className="two-star" onClick={this.twoStars} value={2}>☆</span> <span className="one-star" onClick={this.oneStars} value={1}>☆</span> </section> } this.fiveStars = this.fiveStars.bind(this) this.fourStars = this.fourStars.bind(this) this.threeStars = this.threeStars.bind(this) this.twoStars = this.twoStars.bind(this) this.oneStars = this.oneStars.bind(this) this.submitRating = this.submitRating.bind(this) } fiveStars() { this.setState({ rating: 5 }) } fourStars() { this.setState({ rating: 4, }) } threeStars() { this.setState({ rating: 3 }) } twoStars() { this.setState({ rating: 2 }) } oneStars() { this.setState({ rating: 1 }) } submitRating() { if (this.props.user === undefined || this.props.user === null) { this.props.loginMessage() } else { var submission = { artist: this.props.Artist, album: this.props.Album, genre: this.props.Genre, rating: this.state.rating, artwork: this.props.Artwork, itunesLink: this.props.buyOnItunes, user: this.props.user.username, collectionid: this.props.collectionId, releaseDate: this.props.releaseDate } fetch(`https://stegato-api.herokuapp.com/music-data/${submission.user}`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ 'Artist': `${submission.artist}`, 'album': `${submission.album}`, 'Genre': `${submission.genre}`, 'Rating': `${submission.rating}`, 'artwork': `${submission.artwork}`, 'BuyOnItunes': `${submission.itunesLink}`, 'user': `${submission.user}`, "collectionid": `${submission.collectionid}`, "releaseDate": `${submission.releaseDate}` }) }).then( this.props.successMessage() ) .then( this.setState({rating: undefined}) ) } } reRender() { if (this.state.rating !== undefined) { let submit = <section className="rating-submited"> <div className="rating-pending"> {this.state.rating} </div> <div className="submit-rating"> <button type="button" className="submit-rating-button" onClick={this.submitRating} >Submit </button> </div> </section> return submit } } render() { let ratings = <section className="rating"> <span className="five-star" onClick={this.fiveStars} value={5}>☆</span> <span className="four-star" onClick={this.fourStars} value={4}>☆</span> <span className="three-star" onClick={this.threeStars} value={3}>☆</span> <span className="two-star" onClick={this.twoStars} value={2}>☆</span> <span className="one-star" onClick={this.oneStars} value={1}>☆</span> </section> return ( <section className="rating-add"> {ratings} {this.reRender()} </section> ); } }
6dcba5de8039cf1b54426ecd77ef5b60d71c6433
[ "Markdown", "JavaScript" ]
18
Markdown
JesseShawCodes/stegato
d0e60470fc85a76e5905de6958933fefa1ddd3e1
293ffc105cbc15e955e912cd1466270c658468fd
refs/heads/master
<file_sep><?php namespace Code\Sistema; use Silex\Application as ApplicationSilex; use Code\Sistema\Service\ProdutoService; use Code\Sistema\Service\CategoriaSevice; use Code\Sistema\Service\TagSevice; use Code\Sistema\Entity\Produto; use Code\Sistema\Entity\Categoria; use Code\Sistema\Entity\Tag; use Code\Sistema\Validator\NumericValidador; use Code\Sistema\Validator\IsBlankValidador; class Application extends ApplicationSilex { public function __construct(array $values = array()) { parent::__construct($values); $app = $this; $app['produtoService'] = function () use($app) { $produtoService = new ProdutoService($app['EntityManager'], new Produto()); $produtoService->setArrayValidators([ 'categoria' => new IsBlankValidador(), 'valor' => new NumericValidador(), 'nome' => new IsBlankValidador(), 'tags' => new IsBlankValidador(), 'descricao' => new IsBlankValidador() ] ); return $produtoService; }; $app['categoriaService'] = function () use($app) { $categoriaService = new CategoriaSevice($app['EntityManager'], new Categoria()); $categoriaService->setValidators('nome', new IsBlankValidador()); return $categoriaService; }; $app['tagService'] = function () use($app) { $tagService = new TagSevice($app['EntityManager'], new Tag()); $tagService->setValidators('nome', new IsBlankValidador()); return $tagService; }; $app->get('/', function () use ($app) { return $app['twig']->render('index.twig', []); })->bind('inicio'); $app->mount("/produtos", new Controller\ProdutoController()); $app->mount("/categorias", new Controller\CategoriaController()); $app->mount("/tags", new Controller\TagController()); $app->mount("/api/produtos", new Controller\ProdutoAPIController()); $app->mount("/api/tags", new Controller\TagAPIController()); $app->mount("/api/categorias", new Controller\CategoriaAPIController()); } } <file_sep><?php namespace Code\Sistema\Validator; use Code\Sistema\Interfaces\ValidadorInterface; class NumericValidador implements ValidadorInterface{ private $message; public function isValid($data) { if (!is_numeric($data)) { $this->message = "O valor informado '{$data}' nao e numerico"; return false; } $this->message = ""; return true; } public function getMessage() { return $this->message; } } <file_sep><?php namespace Code\Sistema\Service; use Doctrine\ORM\EntityManager; use Code\Sistema\Entity\Categoria; use Code\Sistema\Service\AbstractService; class CategoriaSevice extends AbstractService { public function __construct(EntityManager $em, Categoria $categoria) { parent::__construct($em); $this->object = $categoria; $this->entity = "Code\Sistema\Entity\Categoria"; } } <file_sep><?php namespace Code\Sistema\Validator; use Code\Sistema\Interfaces\ValidadorInterface; class IsBlankValidador implements ValidadorInterface { private $menssage; public function isValid($data) { if ($data === "" or $data === null) { $this->menssage = "Este campo nao pode estar vazio"; return false; } $this->menssage = ""; return true; } public function getMessage() { return $this->menssage; } } <file_sep><?php namespace Code\Sistema\Controller; use Silex\ControllerProviderInterface; use Silex\Application; use Symfony\Component\HttpFoundation\Request; class CategoriaController implements ControllerProviderInterface { private $registros_por_pagina = 5; public function connect(Application $app) { $controller = $app['controllers_factory']; $controller->get('/', function () use ($app) { $result = $app['categoriaService']->findPagination(0, $this->registros_por_pagina); return $app['twig']->render('categoria/categoria.twig', ['categorias' => $result, 'page_atual' => 1, 'numero_paginas' => ceil($app['categoriaService']->getRows() / $this->registros_por_pagina)]); })->bind('categorias_listar'); $controller->get('/page/{page}', function ($page) use ($app) { if ($page < 1 or $page > ceil($app['categoriaService']->getRows() / $this->registros_por_pagina)) { $page = 1; } $result = $app['categoriaService']->findPagination((($page - 1) * $this->registros_por_pagina), $this->registros_por_pagina); return $app['twig']->render('categoria/categoria.twig', ['categorias' => $result, 'page_atual' => $page, 'numero_paginas' => ceil($app['categoriaService']->getRows() / $this->registros_por_pagina)]); })->bind('categorias_listar_pagination'); $controller->match('/novo', function (Request $request) use ($app) { $form = $app['form.factory']->createBuilder(new \Code\Sistema\Form\CategoriaForm()) ->getForm(); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); $serviceManager = $app['categoriaService']; $result = $serviceManager->insert($data); return $app['twig']->render('categoria/categoria_novo.twig', ["success" => $result, "form" => $form->createView(), "Message" => $serviceManager->getMessage()]); } return $app['twig']->render('categoria/categoria_novo.twig', ["Message" => array(), "form" => $form->createView()]); })->bind('categoria_novo'); $controller->match('/edit/{id}', function ($id, Request $request) use ($app) { $form = $app['form.factory']->createBuilder(new \Code\Sistema\Form\CategoriaForm()) ->getForm(); if ($this->isPost($request)) { $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); $data["id"] = $id; $app['categoriaService']->update($data); return $app->redirect("/categorias"); } return $app['twig']->render('categoria/categoria_edit.twig', ["form" => $form->createView()]); } $result = $app['categoriaService']->find($id); $form->setData($result->toArray()); return $app['twig']->render('categoria/categoria_edit.twig', ["form" => $form->createView()]); })->bind('categoria_edit'); $controller->get('/delete/{id}', function ($id) use ($app) { $app['categoriaService']->delete($id); return $app->redirect("/categorias"); })->bind('categorias_delete'); return $controller; } private function isPost($request) { if ('POST' == $request->getMethod()) { return true; } return false; } } <file_sep><?php namespace Code\Sistema\Service; use Doctrine\ORM\EntityManager; use Code\Sistema\Entity\Produto; use Code\Sistema\Service\AbstractService; class ProdutoService extends AbstractService { public function __construct(EntityManager $em, Produto $produto) { parent::__construct($em); $this->object = $produto; $this->entity = "Code\Sistema\Entity\Produto"; } public function posValidation() { $this->object->eraseTags(); } public static function uploadImage(array $files = array()) { $types = ["bmp", "jpeg", "png"]; //Extensoes validas if (empty($files["tmp_name"])) { return false; } foreach ($types as $type) { if (strstr($files["type"], $type)) { $imagemPath = "/imgs/produtos/produto_" . time() . "." . $type; $completePath = __DIR__ . "/../../../../public"; if (move_uploaded_file($files["tmp_name"], $completePath . $imagemPath)) { return $imagemPath; } return false; } } return false; } publiC static function removeImage($path) { $completePath = __DIR__ . "/../../../../public"; if (unlink($completePath . $path)) { return true; } return false; } public function ajustaData(array $data = array()) { if (!empty($data["categoria"])) { $data["categoria"] = $this->em->getReference("Code\Sistema\Entity\Categoria", $data["categoria"]); } if (empty($data["tags"])) { return $data; } if (strstr($data["tags"], ',')) { $IDs = explode(",", $data["tags"]); foreach ($IDs as $value) { $tags[] = $this->em->getReference("Code\Sistema\Entity\Tag", $value); } $data["tags"] = $tags; return $data; } $data["tag"] = $this->em->getReference("Code\Sistema\Entity\Tag", $data["tags"]); unset($data["tags"]); return $data; } } <file_sep><?php namespace Code\Sistema\Controller; use Silex\Application; use Silex\ControllerProviderInterface; use Symfony\Component\HttpFoundation\Request; class TagAPIController implements ControllerProviderInterface { public function connect(Application $app) { $controller = $app['controllers_factory']; $controller->get('/', function () use ($app) { $result = $app['tagService']->findAllToArray(); return $app->json($result); }); $controller->get('/{id}', function ($id) use ($app) { $result = $app['tagService']->findToArray($id); return $app->json($result); }); $controller->post('/', function (Request $request) use ($app) { $serviceManager = $app['tagService']; $result = $serviceManager->insert($request->request->all()); return $app->json(["success" => $result, "Message" => $serviceManager->getMessage()]); }); $controller->put('/', function (Request $request) use ($app) { $serviceManager = $app['tagService']; $result = $serviceManager->update($request->request->all()); return $app->json(["success" => $result, "Message" => $serviceManager->getMessage()]); }); $controller->delete('/{id}', function ($id) use ($app) { $serviceManager = $app['tagService']; $result = $serviceManager->delete($id); return $app->json(["success" => $result, "Message" => $serviceManager->getMessage()]); }); return $controller; } } <file_sep><?php namespace Code\Sistema\Service; use Doctrine\ORM\EntityManager; use Code\Sistema\Entity\Tag; use Code\Sistema\Service\AbstractService; class TagSevice extends AbstractService { public function __construct(EntityManager $em, Tag $tag) { parent::__construct($em); $this->object = $tag; $this->entity = "Code\Sistema\Entity\Tag"; } public function getTagsAvailable($tags) { $string = "0"; foreach ($tags as $tag) { $string .= ",{$tag->getId()}"; } $repo = $this->em->getRepository($this->entity); return $repo->getTagsAvailable($string); } } <file_sep><?php namespace Code\Sistema\Service; use Doctrine\ORM\EntityManager; use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException; abstract class AbstractService { protected $em; protected $message = array(); protected $validators = array(); protected $object; protected $entity; public function __construct(EntityManager $em) { $this->em = $em; } public function checkValues(array $data = array()) { $return = true; foreach ($data as $metodo => $valor) { if(!$this->checkValidator($metodo, $valor)){ $return = false; } } return $return; } public function checkValidator($metodo, $valor) { foreach ($this->validators as $key => $validator) { if ($metodo != $key) { continue; } if (!$validator->isValid($valor)) { $this->message[] = strtoupper($key) . " : " . $validator->getMessage(); return false; } } return true; } public function ajustaData(array $data = array()) { return $data; } private function popular(array $data = array()) { $data_checked = $this->ajustaData($data); if (!$this->checkValues($data_checked)) { return false; } $this->posValidation(); foreach ($data_checked as $metodo => $valor) { $metodo = 'set' . ucfirst($metodo); if (!method_exists($this->object, $metodo)) { $this->setMessage("Nao foi possivel converte-lo, verifique os atributos enviados"); return false; } $this->object->$metodo($valor); } return $this->object; } public function insert(array $data = array()) { if ($this->popular($data)) { $this->em->persist($this->object); $this->em->flush(); return true; } return false; } public function posValidation() { } public function update(array $data = array()) { if (!isset($data["id"])) { $this->setMessage("Parametro :id nao encontrado"); return false; } $this->object = $this->em->getReference($this->entity, $data["id"]); if (!$this->popular($data)) { return false; } $this->em->persist($this->object); $this->em->flush(); return true; } public function delete($id) { $this->object = $this->em->getReference($this->entity, $id); $this->em->remove($this->object); try { $this->em->flush(); return true; } catch (ForeignKeyConstraintViolationException $ex) { $this->setMessage($ex->getMessage()); return false; } } public function findAll() { $repo = $this->em->getRepository($this->entity); return $repo->findAll(); } protected function toArray($objects) { if(!isset($objects[0])){ return array(); } $methods = get_class_methods($objects[0]); $prop = array(); for ($i=0;$i < sizeof($methods); $i++){ if(substr($methods[$i],0,3) == 'get'){ $prop[$methods[$i]] = str_replace('get', '', $methods[$i]); continue; } } foreach ($objects as $tag) { $data = array(); foreach ($prop as $key => $value) { $object = $tag->$key(); if(is_object($object)){ $data[$value] = $this->toArray([0=>$object]); continue; } if(is_array($object)){ $data[$value] = $this->toArray($object); continue; } $data[$value] = $tag->$key(); } $return[] = $data; } return $return; } public function findAllToArray() { $repo = $this->em->getRepository($this->entity); $objects = $repo->findAll(); return $this->toArray($objects); } public function findToArray($id) { $repo = $this->em->getRepository($this->entity); $object = $repo->find($id); return $this->toArray([0=>$object]); } public function findPagination($firstResult, $maxResults) { $repo = $this->em->getRepository($this->entity); return $repo->findPagination($firstResult, $maxResults); } public function getRows() { $repo = $this->em->getRepository($this->entity); return $repo->getRows(); } public function find($id) { $repo = $this->em->getRepository($this->entity); return $repo->find($id); } function getMessage() { return $this->message; } function setMessage($message) { $this->message[] = $message; return $this; } function setValidators($indice, $validator) { $this->validators[$indice] = $validator; return $this; } function setArrayValidators(array $validators) { $this->validators = $validators; return $this; } } <file_sep><?php namespace Code\Sistema\Controller; use Silex\ControllerProviderInterface; use Silex\Application; use Symfony\Component\HttpFoundation\Request; class ProdutoController implements ControllerProviderInterface { private $registros_por_pagina = 5; public function connect(Application $app) { $controller = $app['controllers_factory']; $controller->get('/', function () use ($app) { $result = $app['produtoService']->findPagination(0, $this->registros_por_pagina); return $app['twig']->render('produto/produtos.twig', ['produtos' => $result, 'page_atual'=>1,'numero_paginas'=>ceil($app['produtoService']->getRows()/$this->registros_por_pagina)]); })->bind('produtos_listar'); $controller->get('/page/{page}', function ($page) use ($app) { if($page < 1 or $page > ceil($app['produtoService']->getRows()/$this->registros_por_pagina) ){ $page = 1; } $result = $app['produtoService']->findPagination((($page-1)*$this->registros_por_pagina), $this->registros_por_pagina); return $app['twig']->render('produto/produtos.twig', ['produtos' => $result, 'page_atual'=>$page, 'numero_paginas'=>ceil($app['produtoService']->getRows()/$this->registros_por_pagina)]); })->bind('produtos_listar_pagination'); $controller->get('/novo', function () use ($app) { return $app['twig']->render('produto/produto_novo.twig', [ "Message"=>array(), "categorias"=>$app['categoriaService']->findall(), "tags"=> $app['tagService']->findall() ]); })->bind('produto_novo'); $controller->post('/novo', function (Request $request) use ($app) { $serviceManager = $app['produtoService']; $result = $serviceManager->insert($request->request->all()); return $app['twig']->render('produto/produto_novo.twig', ["success" => $result, "Message" => $serviceManager->getMessage(),"categorias"=>$app['categoriaService']->findall(),"tags"=> $app['tagService']->findall()]); })->bind('produto_novo_post'); $controller->get('/edit/{id}', function ($id) use ($app) { $result = $app['produtoService']->find($id); return $app['twig']->render('produto/produto_edit.twig', ["produto" => $result,"Message" => [],"categorias"=>$app['categoriaService']->findall(),"tags_selecionadas"=> $result->getTags(), "tags_disponiveis"=>$app['tagService']->getTagsAvailable($result->getTags())]); })->bind('produto_edit'); $controller->post('/edit', function (Request $request) use ($app) { $serviceManager = $app['produtoService']; $serviceManager->update($request->request->all()); $result = $serviceManager->find($request->get("id")); return $app['twig']->render('produto/produto_edit.twig', ["produto" => $result,"Message" => $serviceManager->getMessage(),"categorias"=>$app['categoriaService']->findall(),"tags_selecionadas"=> $result->getTags(), "tags_disponiveis"=>$app['tagService']->getTagsAvailable($result->getTags())]); })->bind('produto_edit_post'); $controller->get('/delete/{id}', function ($id) use ($app) { $app['produtoService']->delete($id); return $app->redirect("/produtos"); })->bind('produtos_delete'); return $controller; } } <file_sep><?php namespace Code\Sistema\Interfaces; interface ValidadorInterface { public function isValid($data); public function getMessage(); } <file_sep><?php namespace Code\Sistema\Entity; use Doctrine\ORM\EntityRepository; class TagRepository extends EntityRepository { public function findPagination($firstResult,$maxResults) { return $this->createQueryBuilder('c') ->setFirstResult($firstResult) ->setMaxResults($maxResults) ->getQuery() ->getResult(); } public function getRows() { return $this->createQueryBuilder('c') ->select('Count(c)') ->getQuery() ->getSingleScalarResult(); } public function getTagsAvailable($ids) { return $this->createQueryBuilder('c') ->where("c.id not in ({$ids})") ->getQuery() ->getResult(); } } <file_sep><?php namespace Code\Sistema\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\Length; class CategoriaForm extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { return $builder->add('nome', "text", array( 'constraints' => array(new NotBlank(), new Length(array('max' => 10))), ) ) ->add('cadastrar', 'submit', array('label' => 'Confirmar')); } public function getName() { return 'CategoriaForm'; } } <file_sep><?php namespace Code\Sistema\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use Code\Sistema\Service\ProdutoService; /** * @ORM\Entity(repositoryClass="Code\Sistema\Entity\ProdutoRepository") * @ORM\HasLifecycleCallbacks * @ORM\Table(name="produto") */ class Produto { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue */ private $id; /** * @ORM\Column(type="string", length=255) */ private $nome; /** * @ORM\Column(type="string", length=255) */ private $descricao; /** * @ORM\Column(type="decimal", precision=15, scale=2) */ private $valor; /** * @ORM\ManyToOne(targetEntity="Categoria") * @ORM\JoinColumn(name="categoria_id", referencedColumnName="id", onDelete="SET NULL") */ private $categoria; /** * @ORM\ManyToMany(targetEntity="Tag") * @ORM\JoinTable(name="produtos_tags", * joinColumns={@ORM\JoinColumn(name="produto_id", referencedColumnName="id", onDelete="CASCADE")}, * inverseJoinColumns={@ORM\JoinColumn(name="tag_id", referencedColumnName="id", onDelete="CASCADE")} * ) * */ private $tags; /** * @ORM\Column(type="string", length=255) */ private $image; public function __construct($nome = "", $descricao = "", $valor = "", $id = "") { $this->tags = new ArrayCollection(); $this->nome = $nome; $this->descricao = $descricao; $this->valor = $valor; $this->id = $id; } /** * @ORM\PrePersist * @ORM\preUpdate */ public function uploadImage() { $temp = $this->image; if (!isset($_FILES["image"])) { return false; } $result = ProdutoService::uploadImage($_FILES["image"]); if ($result) { $this->image = $result; if (!empty($temp)) { ProdutoService::removeImage($temp); } } } function getId() { return $this->id; } function getNome() { return $this->nome; } function getDescricao() { return $this->descricao; } function getValor() { return $this->valor; } function setId($id) { $this->id = $id; return $this; } function setNome($nome) { $this->nome = $nome; return $this; } function setDescricao($descricao) { $this->descricao = $descricao; return $this; } function setValor($valor) { $this->valor = $valor; return $this; } function getCategoria() { return $this->categoria; } function setCategoria($categoria) { $this->categoria = $categoria; return $this; } function getTags() { return $this->tags->toArray(); } public function eraseTags() { $this->tags = new ArrayCollection(); } function setTag(Tag $tag) { $this->tags->add($tag); return $this; } function setTags(array $tags = array()) { foreach ($tags as $tag) { $this->tags->add($tag); } return $this; } function getImage() { return $this->image; } }
8000578d9bdfb884829a710952893f4ed872f584
[ "PHP" ]
14
PHP
thiagovictor/SilexAndDoctrine
6d4d3cc301d846410bf3d2ac29a6443f78ff81df
9c6d6c706d061a7ec655cae7060f263d79a8ff09
refs/heads/master
<file_sep>package com.stackextend.lombokhelloworld.lombok; import lombok.ToString; @ToString public class ToStringHelloWorld { private String firstAttribute; private void doSomething() { this.toString(); } } <file_sep># First Step to Project Lombok Annotations Find Article here [https://www.stackextend.com/java/first-step-lombok-annotations/](https://www.stackextend.com/java/first-step-lombok-annotations). Enjoy :) <file_sep>package com.stackextend.lombokhelloworld.lombok; import lombok.extern.slf4j.Slf4j; @Slf4j public class Slf4jHelloWorld { public void doSomething() { log.info("This is a message from Lombok @Slf4j"); } }
d39d5f0524f178397c5f2994878bbd5f1676b924
[ "Markdown", "Java" ]
3
Java
mouadelfakir/project-lombok-helloworld
c83753ddc7a303b869cf5f3e9ded23aacb1c1fe9
72253a5b809394560d4afcd7b24e255cdf150a62
refs/heads/master
<repo_name>Shuvarov-MD/js-lesson-project-2<file_sep>/point-6/script.js 'use strict'; const div = document.querySelector('#div'); class Greeding { constructor() { this.timesOfDay = ['Доброе утро', 'Добрый день', 'Добрый вечер', 'Доброй ночи'], this.dayOfTheWeek = ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'], this.dateToday = new Date(), this.dateNewYear = new Date('1 January 2021'); } getTimesOfDay() { return (this.dateToday.getHours() >= 6 && this.dateToday.getHours() < 12) ? this.timesOfDay[0] : (this.dateToday.getHours() >= 12 && this.dateToday.getHours() < 18) ? this.timesOfDay[1] : (this.dateToday.getHours() >= 18 && this.dateToday.getHours() < 23) ? this.timesOfDay[2] : this.timesOfDay[3]; } getDayOfTheWeek() { return this.dayOfTheWeek[this.dateToday.getDay()]; } getAmountOfDays() { const amountOfDays = Math.ceil((this.dateNewYear - this.dateToday) / 86400000); return (amountOfDays % 10 === 1 && amountOfDays % 10 !== 11) ? amountOfDays + ' день' : (amountOfDays % 10 === 2 || amountOfDays % 10 === 3 || amountOfDays % 10 === 4) ? amountOfDays + ' дня' : amountOfDays + ' дней'; } } const greeding = new Greeding(); div.innerHTML = `<p>${greeding.getTimesOfDay()}</p> <p>Сегодня: ${greeding.getDayOfTheWeek()}</p> <p>Текущее время: ${greeding.dateToday.toLocaleTimeString('en-US')}</p> <p>До нового года осталось ${greeding.getAmountOfDays()}</p>`;
5b231212f2c982a3729868c11b13209ad990ee2b
[ "JavaScript" ]
1
JavaScript
Shuvarov-MD/js-lesson-project-2
fbd14a9593f27a36ea0181aa281c2ade9867a2ff
57cdc1a46d565fcf700a7b2d02476e055e70bd40
refs/heads/main
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Audio; public class UI_Scripts_AudioManager : MonoBehaviour { public AudioMixer audioMixer; public Slider MasterVolumeSlider; public Slider BackgroundSlider; public Slider SoundEffectSlider; void Start() { MasterVolumeSlider.value = PlayerPrefs.GetFloat("MasterVolume"); BackgroundSlider.value = PlayerPrefs.GetFloat("Background"); SoundEffectSlider.value = PlayerPrefs.GetFloat("SoundEffect"); } void Update() { PlayerPrefs.SetFloat("MasterVolume", MasterVolumeSlider.value); PlayerPrefs.SetFloat("Background", BackgroundSlider.value); PlayerPrefs.SetFloat("SoundEffect", SoundEffectSlider.value); } public void SetMasterVolume(float volume) { audioMixer.SetFloat("MasterVolume", volume); } public void SetMusicVolume(float volume) { audioMixer.SetFloat("Background", volume); } public void SetSoundEffectVolume(float volume) { audioMixer.SetFloat("SoundEffect", volume); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class UI_Scripts_Start : MonoBehaviour { public Button back; public Button next; public Button backStart; public GameObject Character; public GameObject Team; void Start() { back.onClick.AddListener(() => { SceneManager.LoadScene(0); }); next.onClick.AddListener(() => { Next(); }); backStart.onClick.AddListener(() => { StartBack(); }); } void Next() { Character.SetActive(false); Team.SetActive(true); } void StartBack() { Team.SetActive(false); Character.SetActive(true); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class UI_Scripts_Join : MonoBehaviour { public Button back; public Button startJoin; void Start() { back.onClick.AddListener(() => { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 2); }); startJoin.onClick.AddListener(() => { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); }); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class UI_Scripts_Host : MonoBehaviour { public Toggle Map1; public Toggle Map2; public Toggle RandomMaps; private int maps; public Button back; public Button next; public Button backHost; public Button startHost; public GameObject Map; public GameObject Host; void Start() { maps = 0; back.onClick.AddListener(() => { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1); }); next.onClick.AddListener(() => { HostNext(); }); backHost.onClick.AddListener(() => { HostBack(); }); startHost.onClick.AddListener(() => { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 2); }); } void Update() { if (Map1.isOn == true) { maps = 1; } if (Map2.isOn == true) { maps = 2; } if (RandomMaps.isOn == true) { random(); } } void random() { maps = Random.Range(1, 3); } void HostNext() { Map.SetActive(false); Host.SetActive(true); } void HostBack() { Host.SetActive(false); Map.SetActive(true); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class LightCheckScript : MonoBehaviour { public RenderTexture sourceTexture; float LightLevel; public int Light; public Text LightLevelDet; // Update is called once per frame void Update() { RenderTexture tmp = RenderTexture.GetTemporary( sourceTexture.width, sourceTexture.height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear); Graphics.Blit(sourceTexture, tmp); RenderTexture previous = RenderTexture.active; RenderTexture.active = tmp; Texture2D myTexture2D = new Texture2D(sourceTexture.width, sourceTexture.height); myTexture2D.ReadPixels(new Rect(0, 0, tmp.width, tmp.height), 0, 0); myTexture2D.Apply(); RenderTexture.active = previous; RenderTexture.ReleaseTemporary(tmp); Color32[] colors = myTexture2D.GetPixels32(); LightLevel = 0; for (int i = 0; i < colors.Length; i++) { LightLevel += (0.2126f * colors[i].r) + (0.7152f * colors[i].g) + (0.0722f * colors[i].b); } //LightLevel -= 256737; LightLevel = LightLevel / colors.Length; Light = Mathf.RoundToInt(LightLevel); LightLevelDet.text = Light.ToString(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class UI_Scripts_Menu : MonoBehaviour { public GameObject Menu; public GameObject Server; public GameObject Options; public GameObject Rule; public GameObject BackButton; public Button play; public Button option; public Button help; public Button exit; public Button back; public Button host; public Button join; void GamePlay() { Menu.SetActive(false); Server.SetActive(true); BackButton.SetActive(true); } void GameOption() { Menu.SetActive(false); Options.SetActive(true); BackButton.SetActive(true); } void GameHelp() { Menu.SetActive(false); Rule.SetActive(true); BackButton.SetActive(true); } void GameExit() { Application.Quit(); } void BackMenu() { Server.SetActive(false); Options.SetActive(false); Rule.SetActive(false); BackButton.SetActive(false); Menu.SetActive(true); } void Start() { play.onClick.AddListener(() => { GamePlay(); }); option.onClick.AddListener(() => { GameOption(); }); help.onClick.AddListener(() => { GameHelp(); }); exit.onClick.AddListener(() => { GameExit(); }); back.onClick.AddListener(() => { BackMenu(); }); host.onClick.AddListener(() => { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); }); join.onClick.AddListener(() => { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 2); }); } }
6c63fd4161374b10295b2319a267522a491d2e7c
[ "C#" ]
6
C#
Cooper-Sam/Project-Hunters-and-Hiders
57480e4b003ecd6b07c9482ea25d6b0baa617b9d
3a9c10dcab2c6dcc3163502161641417ea57a389
refs/heads/main
<file_sep># Common include some coomon C++ files
e7095ff2621a36400c46531d39ef06bcfb6f978f
[ "Markdown" ]
1
Markdown
QtEngineer/Common
29ba7eac6bc96b76622b547ded084cef2770f722
525332aee5006670368d79857e8a273fc60bcd7f
refs/heads/master
<repo_name>dlulko/python_programs<file_sep>/Checklist.py print("Enter activities to complete. If none remain enter: No More") max_entries = 10 while max_entries <= 10: max_entries = max_entries + 1 activity = input("Enter Activity: ") print("Is" ,activity, "finished? ") answer = input("Yes or No ") if answer == "Yes": print("Good Job") else: if answer == "No": print("Keep Working") else: print("Invalid Answer")
2fc504a81c7893d676c6b325ab5c3ce4ce8bbce9
[ "Python" ]
1
Python
dlulko/python_programs
b378656ae91938ea52d3894a8a2abddf06ddd727
750ec9cf7ce076d742e8c60f8fd08a11502d764a
refs/heads/master
<file_sep>let fs = require("fs-extra"), ini = require("ini"), pathSep = require("path").sep, httpProxy = require('http-proxy'); let cloudMap = { test1: { }, test2: { UrlSource: 3 }, qa: { UrlSource: 4, ManualUrl: "http://cep.eu.veri.ericssoncvc.com" }, }; cloudPorts = { test1: 8088, test2: 8089, qa: 8090 }; function updateFrameworkInis(cloud) { let spaTempDirRoot = [process.env['USERPROFILE'], ".spa"].join(pathSep), appNames = fs.readdirSync(spaTempDirRoot); appNames.forEach(function(appName) { let absAppPath = spaTempDirRoot + pathSep + appName, fwIni = absAppPath + pathSep + "Framework.ini", fwIniBak = fwIni + ".bak", featuresXmlPath = absAppPath + pathSep + "features.xml"; try { let f = fs.readFileSync(fwIni, 'utf-8'), iniConfig = ini.parse(f); iniConfig.Cloud = {}; if ('UrlSource' in cloud) { iniConfig.Cloud.UrlSource = cloud.UrlSource; } if ('ManualUrl' in cloud) { iniConfig.Cloud.ManualUrl = ini.safe(cloud.ManualUrl); } if (!fs.existsSync(fwIniBak)) { fs.copySync(fwIni, fwIniBak); console.log("Wrote backup to " + fwIniBak); } fs.writeFileSync(fwIni, ini.stringify(iniConfig)); console.log("Wrote", cloudId, "to", "%TEMP%/Spa/" + appName + "/Framework.ini"); } catch(e) { } if (fs.existsSync(featuresXmlPath)) { fs.unlinkSync(featuresXmlPath); console.log("Removed features.xml"); } }); } let cloudId, hasValidCloud = (process.argv.length >= 2) && (process.argv[2] in cloudMap); if (!hasValidCloud) { cloudId = "test1"; } else { cloudId = process.argv[2] } updateFrameworkInis(cloudMap[cloudId]);
1c8adf2fa274e14cfbb35b3397ac1aea1a7413d0
[ "JavaScript" ]
1
JavaScript
shorinji/set-cloud
ecae142ef7ab900ff86660eedc0fccab3ea7864a
b27bc75254466de7efab750990ad0ded431458a6
refs/heads/master
<repo_name>staciaarifin/BNCC-Academy<file_sep>/app/src/main/java/com/example/bnccapplication/NameClass.kt package com.example.bnccapplication class NameClass { }<file_sep>/app/src/main/java/com/example/bnccapplication/MainActivity.kt package com.example.bnccapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val name = "abc" println(name) } private fun showName(s: String) { val name = s } }
617c91d2c18a3e8e19ee4aa1518cb2a1c2e019eb
[ "Kotlin" ]
2
Kotlin
staciaarifin/BNCC-Academy
d8d34f399a5a01b12f66e52aeeb1f81e35f50f84
fd1e635d0177ad7816eb38564351fde807d61d86
refs/heads/master
<file_sep>package at.linguathek.spelling; import android.annotation.SuppressLint; import android.content.ClipData; import android.content.res.Resources; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.DragEvent; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import at.linguathek.spelling.Data.Statement; import at.linguathek.spelling.Data.Task; import static android.view.View.GONE; public class SpellingActivity extends AppCompatActivity { TextView letter1, letter2, letter3, letter4, letter5, letter6, letter7, letter8, answer1, answer2, answer3, answer4, answer5, answer6, answer7, answer8; String TAG; String rightA1, rightA2, rightA3, rightA4, rightA5, rightA6, rightA7, rightA8; int quizCount; String[] answerString1 = {"A", "B", "C", "D", "E", "F", "G", "H"}; String[] answerString2 = {"A", "B", "C", "D", "E"}; String[] answerString3 = {"A", "B", "C", "D", "E", "F"}; String[] quizArray = {}; Task spellingQuizTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_spelling); letter1 = findViewById(R.id.letter1TV); letter2 = findViewById(R.id.letter2TV); letter3 = findViewById(R.id.letter3TV); letter4 = findViewById(R.id.letter4TV); letter5 = findViewById(R.id.letter5TV); letter6 = findViewById(R.id.letter6TV); letter7 = findViewById(R.id.letter7TV); letter8 = findViewById(R.id.letter8TV); answer1 = findViewById(R.id.answer1TV); answer2 = findViewById(R.id.answer2TV); answer3 = findViewById(R.id.answer3TV); answer4 = findViewById(R.id.answer4TV); answer5 = findViewById(R.id.answer5TV); answer6 = findViewById(R.id.answer6TV); answer7 = findViewById(R.id.answer7TV); answer8 = findViewById(R.id.answer8TV); letter1.setOnDragListener(new ChoiceDragListener()); letter2.setOnDragListener(new ChoiceDragListener()); letter3.setOnDragListener(new ChoiceDragListener()); letter4.setOnDragListener(new ChoiceDragListener()); letter5.setOnDragListener(new ChoiceDragListener()); letter6.setOnDragListener(new ChoiceDragListener()); letter7.setOnDragListener(new ChoiceDragListener()); letter8.setOnDragListener(new ChoiceDragListener()); answer1.setOnDragListener(new ChoiceDragListener()); answer2.setOnDragListener(new ChoiceDragListener()); answer3.setOnDragListener(new ChoiceDragListener()); answer4.setOnDragListener(new ChoiceDragListener()); answer5.setOnDragListener(new ChoiceDragListener()); answer6.setOnDragListener(new ChoiceDragListener()); answer7.setOnDragListener(new ChoiceDragListener()); answer8.setOnDragListener(new ChoiceDragListener()); letter1.setOnTouchListener(new ChoiceTouchListener()); letter2.setOnTouchListener(new ChoiceTouchListener()); letter3.setOnTouchListener(new ChoiceTouchListener()); letter4.setOnTouchListener(new ChoiceTouchListener()); letter5.setOnTouchListener(new ChoiceTouchListener()); letter6.setOnTouchListener(new ChoiceTouchListener()); letter7.setOnTouchListener(new ChoiceTouchListener()); letter8.setOnTouchListener(new ChoiceTouchListener()); answer1.setOnTouchListener(new ChoiceTouchListener()); answer2.setOnTouchListener(new ChoiceTouchListener()); answer3.setOnTouchListener(new ChoiceTouchListener()); answer4.setOnTouchListener(new ChoiceTouchListener()); answer5.setOnTouchListener(new ChoiceTouchListener()); answer6.setOnTouchListener(new ChoiceTouchListener()); answer7.setOnTouchListener(new ChoiceTouchListener()); answer8.setOnTouchListener(new ChoiceTouchListener()); loadData(); resetGame(); newGame(); } private final class ChoiceTouchListener implements View.OnTouchListener { @SuppressLint("NewApi") @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { ClipData data = ClipData.newPlainText("", ""); View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); view.startDrag(data, shadowBuilder, view, 0); return true; } else { return false; } } } @SuppressLint("NewApi") private class ChoiceDragListener implements View.OnDragListener { @Override public boolean onDrag(View v, DragEvent event) { switch (event.getAction()) { case DragEvent.ACTION_DRAG_STARTED: break; case DragEvent.ACTION_DRAG_ENTERED: break; case DragEvent.ACTION_DRAG_EXITED: break; case DragEvent.ACTION_DROP: //handle the dragged view being dropped over a drop view View view = (View) event.getLocalState(); //view dragged item is being dropped on TextView dropTarget = (TextView) v; //view being dragged and dropped TextView dropped = (TextView) view; String temp = dropped.getText().toString(); dropped.setText(dropTarget.getText().toString()); dropTarget.setText(temp); //Toast.makeText(SpellingActivity.this, "Changed", Toast.LENGTH_SHORT).show(); checkAnswer(); //Toast.makeText(getApplicationContext(), dropTarget.getText().toString() + "is not " + dropped.getText().toString(), Toast.LENGTH_LONG).show(); break; case DragEvent.ACTION_DRAG_ENDED: break; default: break; } return true; } } private void checkAnswer() { //Toast.makeText(this, "checking Answer", Toast.LENGTH_SHORT).show(); if (((answer1.getVisibility() == GONE) || (answer1.getText().toString().equals(rightA1))) && ((answer2.getVisibility() == GONE) || (answer2.getText().toString().equals(rightA2))) && ((answer3.getVisibility() == GONE) || (answer3.getText().toString().equals(rightA3))) && ((answer4.getVisibility() == GONE) || (answer4.getText().toString().equals(rightA4))) && ((answer5.getVisibility() == GONE) || (answer6.getText().toString().equals(rightA5))) && ((answer6.getVisibility() == GONE) || (answer6.getText().toString().equals(rightA6))) && ((answer7.getVisibility() == GONE) || (answer7.getText().toString().equals(rightA7))) && ((answer8.getVisibility() == GONE) || (answer8.getText().toString().equals(rightA8)))) { Toast.makeText(this, "Hooray!!", Toast.LENGTH_SHORT).show(); resetGame(); newGame(); } else { Toast.makeText(this, "Nope", Toast.LENGTH_SHORT).show(); } } private void newGame() { /*Random rand = new Random(); int n = rand.nextInt(3) + 1; Toast.makeText(this, "number " + n, Toast.LENGTH_SHORT).show(); switch (n) { case 1: quizArray = answerString1; break; case 2: quizArray = answerString2; break; case 3: quizArray = answerString3; break; } List<String> myArray = new ArrayList<>(Arrays.asList(quizArray)); Collections.shuffle(myArray); */ Random random = new Random(); int randomNum = random.nextInt(spellingQuizTask.getStatements().size()); Statement spellingQuiz = spellingQuizTask.getStatements().get(randomNum); List<String> rightAnswersArray = new ArrayList<>(); rightAnswersArray.addAll(Arrays.asList(spellingQuiz.getRightAnswers())); try { rightA1 = rightAnswersArray.get(0); } catch (Exception e) { } try { rightA2 = rightAnswersArray.get(1); } catch (Exception e) { } try { rightA3 = rightAnswersArray.get(2); } catch (Exception e) { } try { rightA4 = rightAnswersArray.get(3); } catch (Exception e) { } try { rightA5 = rightAnswersArray.get(4); } catch (Exception e) { } try { rightA6 = rightAnswersArray.get(5); } catch (Exception e) { } try { rightA7 = rightAnswersArray.get(6); } catch (Exception e) { } try { rightA8 = rightAnswersArray.get(7); } catch (Exception e) { } Toast.makeText(this, "huhhu" + rightA1 + rightA2 + rightA3 + rightA4 + rightA5 + rightA6 + rightA7 + rightA8, Toast.LENGTH_SHORT).show(); try { letter1.setText((rightAnswersArray.get(0))); } catch (Exception e) { letter1.setVisibility(GONE); answer1.setVisibility(GONE); } try { letter2.setText((rightAnswersArray.get(1))); } catch (Exception e) { letter2.setVisibility(GONE); answer2.setVisibility(GONE); } try { letter3.setText((rightAnswersArray.get(2))); } catch (Exception e) { letter3.setVisibility(GONE); answer3.setVisibility(GONE); } try { letter4.setText((rightAnswersArray.get(3))); } catch (Exception e) { letter4.setVisibility(GONE); answer4.setVisibility(GONE); } try { letter5.setText((rightAnswersArray.get(4))); } catch (Exception e) { letter5.setVisibility(GONE); answer5.setVisibility(GONE); } try { letter6.setText((rightAnswersArray.get(5))); } catch (Exception e) { letter6.setVisibility(GONE); answer6.setVisibility(GONE); } try { letter7.setText((rightAnswersArray.get(6))); } catch (Exception e) { letter7.setVisibility(GONE); answer7.setVisibility(GONE); } try { letter8.setText((rightAnswersArray.get(7))); } catch (Exception e) { letter8.setVisibility(GONE); answer8.setVisibility(GONE); } } private void resetGame() { answer1.setVisibility(View.VISIBLE); answer1.setText("_"); answer2.setVisibility(View.VISIBLE); answer2.setText("_"); answer3.setVisibility(View.VISIBLE); answer3.setText("_"); answer4.setVisibility(View.VISIBLE); answer4.setText("_"); answer5.setVisibility(View.VISIBLE); answer5.setText("_"); answer6.setVisibility(View.VISIBLE); answer6.setText("_"); answer7.setVisibility(View.VISIBLE); answer7.setText("_"); answer8.setVisibility(View.VISIBLE); answer8.setText("_"); letter1.setVisibility(View.VISIBLE); letter2.setVisibility(View.VISIBLE); letter3.setVisibility(View.VISIBLE); letter4.setVisibility(View.VISIBLE); letter5.setVisibility(View.VISIBLE); letter6.setVisibility(View.VISIBLE); letter7.setVisibility(View.VISIBLE); letter8.setVisibility(View.VISIBLE); } private void loadData() { Resources res = getResources(); StringBuilder builder = new StringBuilder(); try (BufferedReader br = new BufferedReader(new InputStreamReader(res.openRawResource(R.raw.spelling)))) { String line; while ((line = br.readLine()) != null) { builder.append(line); } } catch (IOException ioe) { Log.e("TAG", "Fehler beim Lesen der JSON Datei: " + ioe.getMessage()); } spellingQuizTask = parseJson(builder.toString()); List<Statement> filteredStatements = new ArrayList<>(); for (Statement s : spellingQuizTask.getStatements()) { filteredStatements.add(s); } spellingQuizTask.setStatements(filteredStatements); Log.e("TAG", "" + spellingQuizTask); } private Task parseJson(String s) { Gson gson = new Gson(); Task quizTaskFromExternal = gson.fromJson(s, Task.class); return quizTaskFromExternal; } } <file_sep>package at.linguathek.spelling.Data; import java.io.Serializable; public class Statement implements Serializable { String question; String rightAnswer; String[] rightAnswers; String[] wrongAnswers; StatementType type = StatementType.QUESTION_MULTI_WRONG; private int soundId; public enum StatementType {QUESTION_MULTI_WRONG, WORD, LISTEN} public Statement() { } public String getQuestion() { return question; } public String getRightAnswer() { return rightAnswer; } public Statement(String question) { this.question = question; } public void setRightAnswer(String rightAnswer) { this.rightAnswer = rightAnswer; } public void setQuestion(String question) { this.question = question; } public StatementType getType() { return type; } public void setType(StatementType type) { this.type = type; } public String[] getWrongAnswers() { return wrongAnswers; } public void setWrongAnswers(String[] wrongAnswers) { this.wrongAnswers = wrongAnswers; } public int getSoundId() { return soundId; } public void setSoundId(int soundId) { this.soundId = soundId; } public String[] getRightAnswers() { return rightAnswers; } public void setRightAnswers(String[] rightAnswers) { this.rightAnswers = rightAnswers; } }
302fe32586a4c748b866472adb116be5af8445b0
[ "Java" ]
2
Java
flokaroni/spelling
105a298257fb732a4d539b69777819f3d05b1986
16fc8dc18a181b318aca95d8ed006672ea1e3f05
refs/heads/master
<file_sep><?php // Connects to your Database mysql_connect("localhost", "root", "root") or die(mysql_error()); mysql_select_db("jef5ez_winer") or die(mysql_error()); //Checks if there is a login cookie if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directes you to the members page $pass = $_COOKIE['Key_my_site']; $username = $_COOKIE['ID_my_site']; $user_id = $_COOKIE['user_id_my_site']; $check = mysql_query("SELECT * FROM users WHERE ID = '$user_id'")or die(mysql_error()); $login = false; while($info = mysql_fetch_array( $check )) { if ($pass == $info['password']) { $login=true; $power=$info['poweruser']; $name =$info['name']; $email = $info['email']; } else{ header("Location: login.php"); } } } ?> <head> <link rel="stylesheet" type="text/css" href="stylesheets/winer.css" /> <meta charset="utf-8" /> <title>Winer: Are you a Winer?</title> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!--[if lte IE 7]> <script src="js/IE8.js" type="text/javascript"></script> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" media="all" href="css/ie6.css"/> <![endif]--> </head> <body> <header id="banner" class="body"> <h1> <a href="#">Winer: <strong>Are you a Winer?</strong></a> </h1> <nav> <ul> <li><a href="index.php">home</a></li> <li><a href="offerings.php">offerings</a></li> <li class="active"><a href="blog.php">blog</a></li> <?php if($login){?> <li><a href="profile.php">profile</a></li> <li><a href="logout.php">logout</a></li> <?php } else{?> <li><a href="sign_up.php">sign up</a></li> <li><a href="login.php">login</a></li> <?php } ?> <li><a href="contact.php">contact</a></li> </ul> </nav> </header> <div id="container" class = "body"> <section id="content" class="body"> <?php if ($login){ if($power){ echo "You are a power user and can Blog!<br>"; echo "<button type='button' onclick='window.location=\"new_blog.php\"'>Create Blog</button>"; } } echo "<h2>Latest Blogs</h2>"; echo '<ol id="posts-list" class="feed">'; $blogs= mysql_query("SELECT * FROM blogs order by ID desc limit 5")or die(mysql_error()); while($info = mysql_fetch_array( $blogs)) { echo '<li>'; echo '<article class="blog">'; echo "<h3><a href='show_blog.php?id=".$info['ID']."'>".$info['title']."</a></h3> "; echo substr($info["story"], 0, 150)."..."; echo "<p> ".$info['likes']." <a href='like.php?id=".$info['ID']."'>like</a> </p>" ; echo '</article>'; echo '</li>'; } ?> </section> <footer id="contentinfo" class="body"> <address id="about" class="vcard body"> <span class="primary"> <strong><a href="#" class="fn url">Winer: a winer company</a></strong> <span class="role">FWBW</span> </span><!-- /.primary --> <img src="images/avatar.png" alt="Winer Logo" class="photo" /> <span class="bio"> Winer is a website and blog that offers resources and advice to wine enthusiasts and makers. It was founded by <NAME>. </span> </address><!-- /#about --> <p> 2012 <a href="#">Winer</a>. </p> </footer> </div> </body> <file_sep><?php // Connects to your Database ini_set('display_errors', 'On'); error_reporting(E_ALL | E_STRICT); mysql_connect("localhost", "root", "root") or die(mysql_error()); mysql_select_db("jef5ez_winer") or die(mysql_error()); $login = false; //Checks if there is a login cookie if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directes you to the members page $pass = $_COOKIE['Key_my_site']; $username = $_COOKIE['ID_my_site']; $user_id = $_COOKIE['user_id_my_site']; $check = mysql_query("SELECT * FROM users WHERE ID = '$user_id'")or die(mysql_error()); while($info = mysql_fetch_array( $check )) { if ($pass == $info['password']) { $login=true; $power=$info['poweruser']; $name =$info['name']; $email = $info['email']; } else{ header("Location: login.php"); } } } ?> <head> <link rel="stylesheet" type="text/css" href="stylesheets/winer.css" /> <meta charset="utf-8" /> <title>Winer: Are you a Winer?</title> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!--[if lte IE 7]> <script src="js/IE8.js" type="text/javascript"></script> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" media="all" href="css/ie6.css"/> <![endif]--> <script src="gen_validatorv4.js" type="text/javascript"></script> <script type="text/javascript"> <!--// hide from non JavaScript Browsers Rollimage = new Array(); Rollimage[0]= new Image(); Rollimage[0].src = "images/wine.jpg"; Rollimage[1] = new Image(); Rollimage[1].src = "images/wine2.jpg"; function SwapOut(){ document.getElementById("wine").src = Rollimage[1].src; document.getElementById("rolloverText").innerHTML= "<p>What new features would you like to see?</p>"; return true; } function SwapBack(){ document.getElementById("wine").src = Rollimage[0].src; document.getElementById("rolloverText").innerHTML= ""; return true; } // - stop hiding --> </script> </head> <body> <header id="banner" class="body"> <h1> <a href="#">Winer: <strong>Are you a Winer?</strong></a> </h1> <nav> <ul> <li><a href="index.php">home</a></li> <li><a href="offerings.php">offerings</a></li> <li><a href="blog.php">blog</a></li> <?php if($login){?> <li><a href="profile.php">profile</a></li> <li><a href="logout.php">logout</a></li> <?php } else{?> <li><a href="sign_up.php">sign up</a></li> <li><a href="login.php">login</a></li> <?php } ?> <li><a href="contact.php">contact</a></li> </ul> </nav> </header> <div id="container" class = "body"> <section id="content" class="body"> <?php if (isset($_POST['submit'])) { // //This makes sure they did not leave any fields blank if (!$_POST['name'] | !$_POST['email'] | !$_POST['message']) { die('You did not complete all of the required fields'); } // checks if the username is in use $name= mysql_real_escape_string($_POST['name']); $email= mysql_real_escape_string($_POST['email']); $message= mysql_real_escape_string($_POST['message']); $insert = "INSERT INTO sugs (name, `email`,`message`) VALUES ('".$name."', '".$email."', '".$message."')"; $add_member = mysql_query($insert) or die(mysql_error()); echo "Thanks for the suggestion"; } ?> <aside id="featured" class="body"> <figure> <a href="#" onmouseover="SwapOut()" onmouseout="SwapBack()"> <img src="images/wine.jpg" id="wine" width=300 height=200 alt="How are we doing?"> </a> </figure> <h2>Contact Us</h2> <p>Tell us how we are doing! </p> <div id="rolloverText"> </div> </aside> <form id="contactForm" action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> Name: <input type="text" name="name"><br> Email: <input type="email" name="email"><br> Message:<br> <textarea name="message" cols=50 rows=5></textarea><br> <input type="submit" name="submit"> </form> <script type="text/javascript"> <!--//GO AWAY SCRIPTS var frmvalidator = new Validator("contactForm"); frmvalidator.addValidation("name","req","Please enter your First Name"); frmvalidator.addValidation("name","maxlen=50", "Max length for Name is 20"); frmvalidator.addValidation("email","maxlen=50"); frmvalidator.addValidation("email","email"); frmvalidator.addValidation("email","req", "Please enter your email."); frmvalidator.addValidation("message","req", "Please enter your message."); //--> </script> </section> <footer id="contentinfo" class="body"> <address id="about" class="vcard body"> <span class="primary"> <strong><a href="#" class="fn url">Winer: a winer company</a></strong> <span class="role">FWBW</span> </span><!-- /.primary --> <img src="images/avatar.png" alt="Winer Logo" class="photo" /> <span class="bio"> Winer is a website and blog that offers resources and advice to wine enthusiasts and makers. It was founded by <NAME>. </span> </address><!-- /#about --> <p> 2012 <a href="#">Winer</a>. </p> </footer> </div> </body> <file_sep><?php // Connects to your Database mysql_connect("localhost", "root", "root") or die(mysql_error()); mysql_select_db("jef5ez_winer") or die(mysql_error()); //Checks if there is a login cookie if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directes you to the members page $username = $_COOKIE['ID_my_site']; $pass = $_COOKIE['Key_my_site']; $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error()); $login = false; while($info = mysql_fetch_array( $check )) { if ($pass != $info['password']) { } else{ $login=true; header("Location: profile.php"); } } } ?> <head> <link rel="stylesheet" type="text/css" href="stylesheets/winer.css" /> <meta charset="utf-8" /> <title>Winer: Are you a Winer?</title> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!--[if lte IE 7]> <script src="js/IE8.js" type="text/javascript"></script> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" media="all" href="css/ie6.css"/> <![endif]--> </head> <body> <header id="banner" class="body"> <h1> <a href="#">Winer: <strong>Are you a Winer?</strong></a> </h1> <nav> <ul> <li><a href="index.php">home</a></li> <li><a href="offerings.php">offerings</a></li> <li><a href="blog.php">blog</a></li> <?php if($login){?> <li><a href="profile.php">profile</a></li> <li><a href="logout.php">logout</a></li> <?php } else{?> <li><a href="sign_up.php">sign up</a></li> <li><a href="login.php">login</a></li> <?php } ?> <li><a href="contact.php">contact</a></li> </ul> </nav> </header> <div id="container" class = "body"> <section id="content" class="body"> <?php //if the login form is submitted if (isset($_POST['submit'])) { // if form has been submitted // makes sure they filled it in if(!$_POST['username'] | !$_POST['pass']) { die('You did not fill in a required field.'); } // checks it against the database $user= mysql_real_escape_string($_POST['username']); $check = mysql_query("SELECT * FROM users WHERE username = '".$user."'")or die(mysql_error()); //Gives error if user dosen't exist $check2 = mysql_num_rows($check); if ($check2 == 0) { die('That user does not exist in our database. <a href=sign_up.php>Click Here to Register</a>'); } while($info = mysql_fetch_array( $check )) { $_POST['pass'] = stripslashes($_POST['pass']); $info['password'] = stripslashes($info['password']); //$_POST['pass'] = md5($_POST['pass']); $salt = stripslashes($info['salt']); $hash= $salt . sha1($salt.$_POST['pass']); //gives error if the password is wrong if ($hash != $info['password']) { die('Incorrect password, please try again.'); } else { // if login is ok then we add a cookie $_POST['username'] = stripslashes($_POST['username']); $hour = time() + 3600; setcookie(ID_my_site, $_POST['username'], $hour); setcookie(Key_my_site, $hash, $hour); setcookie(user_id_my_site, $info['ID'], $hour); //then redirect them to the members area header("Location: profile.php"); } } } else { // if they are not logged in ?> <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> <table border="0"> <tr> <td colspan=2><h1>Login</h1></td> </tr> <tr> <td>Username:</td> <td> <input type="text" name="username" maxlength="40"> </td> </tr> <tr> <td>Password:</td> <td> <input type="<PASSWORD>" name="pass" maxlength="50"> </td> </tr> <tr> <td colspan="2" align="right"> <input type="submit" name="submit" value="Login"> </td> </tr> </table> </form> <?php } ?> </section> <footer id="contentinfo" class="body"> <address id="about" class="vcard body"> <span class="primary"> <strong><a href="#" class="fn url">Winer: a winer company</a></strong> <span class="role">FWBW</span> </span><!-- /.primary --> <img src="images/avatar.png" alt="Winer Logo" class="photo" /> <span class="bio"> Winer is a website and blog that offers resources and advice to wine enthusiasts and makers. It was founded by <NAME>. </span> </address><!-- /#about --> <p> 2012 <a href="#">Winer</a>. </p> </footer> </div> </body> <file_sep><?php // Connects to your Database mysql_connect("localhost", "root", "root") or die(mysql_error()); mysql_select_db("jef5ez_winer") or die(mysql_error()); //Checks if there is a login cookie if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directes you to the members page $pass = $_COOKIE['Key_my_site']; $username = $_COOKIE['ID_my_site']; $user_id = $_COOKIE['user_id_my_site']; $check = mysql_query("SELECT * FROM users WHERE ID = '$user_id'")or die(mysql_error()); $login = false; while($info = mysql_fetch_array( $check )) { if ($pass == $info['password']) { $login=true; $power=$info['poweruser']; $name =$info['name']; $email = $info['email']; } else{ header("Location: login.php"); } } } ?> <head> <link rel="stylesheet" type="text/css" href="stylesheets/winer.css" /> <meta charset="utf-8" /> <title>Winer: Are you a Winer?</title> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!--[if lte IE 7]> <script src="js/IE8.js" type="text/javascript"></script> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" media="all" href="css/ie6.css"/> <![endif]--> <script type="text/javascript" language="javascript"> <!-- //scripty script var interval = 3000; var random_display = 0; var imageDir = "images/"; var imageNum = 0; imageArray = new Array(); imageArray[imageNum++] = new imageItem(imageDir + "fpo-1.jpg"); imageArray[imageNum++] = new imageItem(imageDir + "fpo-2.jpg"); imageArray[imageNum++] = new imageItem(imageDir + "fpo-4.jpg"); imageArray[imageNum++] = new imageItem(imageDir + "pouring-wine.jpg"); imageArray[imageNum++] = new imageItem(imageDir + "tasting-room.jpg"); var totalImages = imageArray.length; function imageItem(image_location) { this.image_item = new Image(); this.image_item.src = image_location; } function get_ImageItemLocation(imageObj) { return(imageObj.image_item.src) } function getNextImage() { imageNum = (imageNum+1) % totalImages; var new_image = get_ImageItemLocation(imageArray[imageNum]); return(new_image); } function getPrevImage() { imageNum = (imageNum-1) % totalImages; var new_image = get_ImageItemLocation(imageArray[imageNum]); return(new_image); } function prevImage(place) { var new_image = getPrevImage(); document.getElementById(place).src = new_image; } function switchImage(place) { var new_image = getNextImage(); document.getElementById(place).src = new_image; var recur_call = "switchImage('"+place+"')"; timerID = setTimeout(recur_call, interval); } var playing = true function startStop() { if(playing){ playing = false clearTimeout(timerID) } else{ playing = true switchImage('slideImg') } } // --> </script> </head> <body onLoad="switchImage('slideImg')"> <header id="banner" class="body"> <h1> <a href="#">Winer: <strong>Are you a Winer?</strong></a> </h1> <nav> <ul> <li class="active"><a href="index.php">home</a></li> <li><a href="offerings.php">offerings</a></li> <li><a href="blog.php">blog</a></li> <?php if($login){?> <li><a href="profile.php">profile</a></li> <li><a href="logout.php">logout</a></li> <?php } else{?> <li><a href="sign_up.php">sign up</a></li> <li><a href="login.php">login</a></li> <?php } ?> <li><a href="contact.php">contact</a></li> </ul> </nav> </header> <div id="container" class = "body"> <aside id="featured" class="body"> <figure> <a title="click to start/pause slideshow" href="#" onClick="startStop()"> <img id="slideImg" src="images/fpo-1.jpg" alt="Slideshow: click to pause/play" width=500 height=300 > </a> </figure> <hgroup> <h2>Featured Article</h2> <h3><a href="blog.html">Come check out our blog!</a></h3> </hgroup> <p> Welcome to Winer! The brand new site for all your wine related needs. Find friends, events, and new wines! </p> </aside> <section id="content" class="body"> <h2> Latest Offerings </h2> <ol id="posts-list" class="feed"> <?php $offerings= mysql_query("SELECT offerings.ID as id, offerings.name as off, users.name as author FROM offerings join users on user_id=users.ID order by offerings.ID desc limit 5")or die(mysql_error()); while($info = mysql_fetch_array( $offerings)) { echo '<li>'; echo '<article class="entry">'; echo '<h2 class="entry-title">'; echo "<a href='show_offering.php?id=".$info["id"]."' rel='bookmark'>".$info["off"]."</a>"; echo '</h2>'; echo '<footer class="post-info">'; echo "<address class='vcard author'> By <a class='url fn' href='profile.php'>".$info["author"]."</a> </address>" ; echo '</footer> </article> </li>'; } ?> </ol> </section> <footer id="contentinfo" class="body"> <address id="about" class="vcard body"> <span class="primary"> <strong><a href="#" class="fn url">Winer: a winer company</a></strong> <span class="role">FWBW</span> </span><!-- /.primary --> <img src="images/avatar.png" alt="Winer Logo" class="photo" /> <span class="bio"> Winer is a website and blog that offers resources and advice to wine enthusiasts and makers. It was founded by <NAME>. </span> </address><!-- /#about --> <p> 2012 <a href="#">Winer</a>. </p> </footer> </div> </body> <file_sep><head> <link rel="stylesheet" type="text/css" href="stylesheets/winer.css" /> <meta charset="utf-8" /> <title>Winer: Are you a Winer?-sign up</title> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!--[if lte IE 7]> <script src="js/IE8.js" type="text/javascript"></script> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" media="all" href="css/ie6.css"/> <![endif]--> </head> <body> <header id="banner" class="body"> <h1> <a href="#">Winer: <strong>Are you a Winer?</strong></a> </h1> <nav> <ul> <li><a href="index.php">home</a></li> <li><a href="offerings.php">offerings</a></li> <li><a href="blog.php">blog</a></li> <li><a href="sign_up.php">sign up</a></li> <li><a href="login.php">login</a></li> <li><a href="contact.php">contact</a></li> </ul> </nav> </header> <div id="container" class = "body"> <section id="content" class="body"> <?php //connects to the database mysql_connect("localhost", "root", "root") or die(mysql_error()); mysql_select_db("jef5ez_winer") or die(mysql_error()); //This code runs if the form has been submitted if (isset($_POST['submit'])) { // //This makes sure they did not leave any fields blank if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] | !$_POST['name'] | !$_POST['email']) { die('You did not complete all of the required fields'); } // checks if the username is in use $name= mysql_real_escape_string($_POST['name']); $email= mysql_real_escape_string($_POST['email']); $user= mysql_real_escape_string($_POST['username']); $check = mysql_query("SELECT username FROM users WHERE username = '$user'") or die(mysql_error()); $check2 = mysql_num_rows($check); //if the name exists it gives an error if ($check2 != 0) { die('Sorry, the username '.$user.' is already in use.'); } // this makes sure both passwords entered match // if ($_POST['pass'] != $_POST['pass2']) { die('Your passwords did not match. '); } // here we encrypt they password and add slashes if needed define('SALT_LENGTH', 9); $salt = substr(sha1(uniqid(rand(), true)), 0, SALT_LENGTH); //$_POST['salt'] = $salt // $_POST['pass'] $hash= $salt . sha1($salt.$_POST['pass']); // now we insert it into the database $insert = "INSERT INTO users (username, name, email, salt, password) VALUES ('".$user."', '".$name."', '".$email."', '".$salt."', '".$hash."')"; $add_member = mysql_query($insert); ?> <h1>Registered</h1> <p>Thank you <?php echo $user; ?>, you have registered - you may now <a href='login.php'>login</a>.</p> <?php } else{ ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table border="0"> <tr><td>Username:</td> <td> <input type="text" name="username" maxlength="60"> </td> </tr> <tr><td> Name:</td> <td> <input type="text" name="name" maxlength="60"> </td> </tr> <tr><td>Email:</td> <td> <input type="email" name="email" maxlength="60"> </td> </tr> <tr><td>Password:</td><td> <input type="<PASSWORD>" name="pass" maxlength="10"> </td></tr> <tr><td>Confirm Password:</td><td> <input type="password" name="pass2" maxlength="10"> </td></tr> <tr><th colspan=2> <input type="submit" name="submit" value="Register"> </th></tr> </table> </form> <?php } ?> </section> <footer id="contentinfo" class="body"> <address id="about" class="vcard body"> <span class="primary"> <strong><a href="#" class="fn url">Winer: a winer company</a></strong> <span class="role">FWBW</span> </span><!-- /.primary --> <img src="images/avatar.png" alt="Winer Logo" class="photo" /> <span class="bio"> Winer is a website and blog that offers resources and advice to wine enthusiasts and makers. It was founded by <NAME>. </span> </address><!-- /#about --> <p> 2012 <a href="#">Winer</a>. </p> </footer> </div> </body> <file_sep><?php // Connects to your Database mysql_connect("localhost", "root", "root") or die(mysql_error()); mysql_select_db("jef5ez_winer") or die(mysql_error()); //Checks if there is a login cookie if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directes you to the members page $pass = $_COOKIE['Key_my_site']; $username = $_COOKIE['ID_my_site']; $user_id = $_COOKIE['user_id_my_site']; $check = mysql_query("SELECT * FROM users WHERE ID = '$user_id'")or die(mysql_error()); $login = false; while($info = mysql_fetch_array( $check )) { if ($pass == $info['password']) { $login=true; $power=$info['poweruser']; $name =$info['name']; $email = $info['email']; } else{ header("Location: login.php"); } } } ?> <head> <link rel="stylesheet" type="text/css" href="stylesheets/winer.css" /> <meta charset="utf-8" /> <title>Winer: Are you a Winer?</title> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!--[if lte IE 7]> <script src="js/IE8.js" type="text/javascript"></script> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" media="all" href="css/ie6.css"/> <![endif]--> <script type="text/javascript"> <!-- function popup(){ pop = window.open('newPost.html', 'newPost', 'location=1'); } //--> </script> </head> <body> <header id="banner" class="body"> <h1> <a href="#">Winer: <strong>Are you a Winer?</strong></a> </h1> <nav> <ul> <li><a href="index.php">home</a></li> <li><a href="offerings.php">offerings</a></li> <li><a href="blog.php">blog</a></li> <?php if($login){?> <li><a href="profile.php">profile</a></li> <li><a href="logout.php">logout</a></li> <?php } else{?> <li><a href="sign_up.php">sign up</a></li> <li><a href="login.php">login</a></li> <?php } ?> <li><a href="contact.php">contact</a></li> </ul> </nav> </header> <div id="container" class = "body"> <section id="content" class="body"> <?php if(isset($_GET['id'])){ $offerings= mysql_query("SELECT offerings.ID as id, offerings.type, offerings.var, offerings.desc, offerings.name as off, users.name as author FROM offerings join users on user_id=users.ID where offerings.ID=".$_GET['id']." limit 1")or die(mysql_error()); while($info = mysql_fetch_array( $offerings)) { echo '<article class="entry">'; echo '<h2 class="entry-title">'; echo "<a href='show_offering.php?id=".$info["id"]."' rel='bookmark'>".$info["off"]."</a>"; echo '</h2>'; echo "<h4>".$info['type'].": ".$info['var']."</h4>"; echo "<p>".$info['desc']."</p>"; echo '<footer class="post-info">'; echo "<address class='vcard author'> By <a class='url fn' href='profile.php'>".$info["author"]."</a> </address>" ; echo '</footer> </article>'; if($info['type']=='Event' && $login){ $attendees = mysql_query("SELECT users.name as attendee FROM attendees join users on user_id=users.ID where offering_id=".$_GET['id'] )or die(mysql_error()); echo "Attending: "; $check = mysql_num_rows($attendees); if($check==0){ echo "No attendees yet"; }else{ while($ppl = mysql_fetch_array($attendees)){ echo $ppl['attendee']." "; } } ?> <br> <a href="attend.php?offering_id=<?php echo $_GET['id']; ?>">Attend</a> <br> <?php } } } else{ echo "No offering specified"; } if($login){ ?> Add a Comment <form id="contactForm" action="comment.php" method="post"> <input type="hidden" name="offering_id" value="<?php echo $_GET['id'] ?>" > <textarea name="comment" cols=50 rows=3></textarea><br> <input type="submit" name="submit"> </form> <?php }?> <h2> Latest Comments</h2> <ol id="posts-list" class="feed"> <?php $comments= mysql_query("SELECT comment, users.name as author FROM comments join users on user_id=users.ID where offering_id=".$_GET['id']." order by comments.ID desc limit 5")or die(mysql_error()); $check = mysql_num_rows($comments); if($check==0){ echo "No comments yet"; }else{ while($info = mysql_fetch_array( $comments)) { echo '<li>'; echo '<article class="entry">'; echo '<p class="post-info">'; echo "<a rel='nofollow'>".$info["comment"]."</a>"; echo '</p>'; echo '<footer class="post-info">'; echo "<address class='vcard author'> By <a class='url fn' href='profile.php'>".$info["author"]."</a> </address>" ; echo '</footer> </article> </li>'; } } ?> </ol> </section> <footer id="contentinfo" class="body"> <address id="about" class="vcard body"> <span class="primary"> <strong><a href="#" class="fn url">Winer: a winer company</a></strong> <span class="role">FWBW</span> </span><!-- /.primary --> <img src="images/avatar.png" alt="Winer Logo" class="photo" /> <span class="bio"> Winer is a website and blog that offers resources and advice to wine enthusiasts and makers. It was founded by <NAME>. </span> </address><!-- /#about --> <p> 2012 <a href="#">Winer</a>. </p> </footer> </div> </body> <file_sep><?php // Connects to your Database ini_set('display_errors', 'On'); error_reporting(E_ALL | E_STRICT); mysql_connect("localhost", "root", "root") or die(mysql_error()); mysql_select_db("jef5ez_winer") or die(mysql_error()); //Checks if there is a login cookie if(isset($_COOKIE['ID_my_site'])){ //if there is, it logs you in and directes you to the members page $pass = $_COOKIE['Key_my_site']; $username = $_COOKIE['ID_my_site']; $user_id = $_COOKIE['user_id_my_site']; $check = mysql_query("SELECT * FROM users WHERE ID = '$user_id'")or die(mysql_error()); $login = false; while($info = mysql_fetch_array( $check )) { if ($pass == $info['password']) { $login=true; $power=$info['poweruser']; $name =$info['name']; $email = $info['email']; } else{ header("Location: login.php"); } } } else{ //if the cookie does not exist, they are taken to the login screen header("Location: login.php"); } if (isset($_POST['submit'])) { // //This makes sure they did not leave any fields blank if (!$_POST['title'] | !$_POST['story']) { die('You did not complete all of the required fields'); } // checks if the username is in use $title= mysql_real_escape_string($_POST['title']); $story= mysql_real_escape_string($_POST['story']); $insert = "INSERT INTO blogs (user_id, `title`,`story`) VALUES ('".$user_id."', '".$title."', '".$story."')"; $add_member = mysql_query($insert) or die(mysql_error()); header("Location: blog.php"); } else{ ?> <head> <link rel="stylesheet" type="text/css" href="stylesheets/winer.css" /> <meta charset="utf-8" /> <title>Winer: Are you a Winer?</title> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!--[if lte IE 7]> <script src="js/IE8.js" type="text/javascript"></script> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" media="all" href="css/ie6.css"/> <![endif]--> </head> <body> <div id="container" class = "body"> <section id="content" class="body"> <h2> Submit an Blog</h2> <form id="blogForm" action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> Blog Title: <input type="text" name="title"> <br> Text: <br> <textarea id="description" name="story" cols=50 rows=5></textarea> <br> <input type="submit" name="submit" > </form> </section> <footer id="contentinfo" class="body"> <address id="about" class="vcard body"> <span class="primary"> <strong><a href="#" class="fn url">Winer: a winer company</a></strong> <span class="role">FWBW</span> </span><!-- /.primary --> <img src="images/avatar.png" alt="Winer Logo" class="photo" /> <span class="bio"> Winer is a website and blog that offers resources and advice to wine enthusiasts and makers. It was founded by <NAME>. </span> </address><!-- /#about --> <p> 2012 <a href="#">Winer</a>. </p> </footer> </div> </body> <?php } ?>
70de2dc4246d1164c4ab4a55cd8c89b38f67db21
[ "PHP" ]
7
PHP
jef5ez/winer
31c8134d3c863dad3d2e0a5c795ce47ada7b1921
60ad4c307bd49de7db02bcb95f081ef24df744eb
refs/heads/master
<repo_name>b2w-atech/bart<file_sep>/src/index.js require('dotenv').config(); const express = require('express'); const app = express(); const axios = require('axios'); app.use(express.json()); app.use(express.urlencoded()); const urlHelpers = require('./utils/url'); const competitors = require('./constants/competitors'); app.get('/freight', (req, res) => { const competitor = req.query.competitor; const competitorStructure = competitors[competitor]; let reqParams = {}; if (competitorStructure.hasQueryParams) { for (field in competitorStructure.fields) { reqParams[competitorStructure.fields[field]] = req.query[field] } } const requestUrl = urlHelpers.getRequestUrl(competitor, competitorStructure, req.query); console.log(requestUrl); console.log(reqParams); axios.get(requestUrl, { headers: competitor.hasReferer ? { referer: 'https://www.magazineluiza.com.br/smartphone-samsung-galaxy-a20-32gb-azul-4g-3gb-ram-64-cam-dupla-cam-selfie-8mp/p/155552900' } : null, params: competitor.hasQueryParams ? reqParams : null } ).then((result) => { res.setHeader('Access-Control-Allow-Origin', '*'); return res.send(result.data); }) .catch((err) => { console.log(err); }); }); const port = process.env.PORT || 3000; app.listen(port, () => { console.log('Ouvindo requisições'); });
5ba34e6df390f54112642c4af2ebc8b734933e56
[ "JavaScript" ]
1
JavaScript
b2w-atech/bart
1a79118c327e9bfbba4167b6313c64cf03b4b975
5a43fadb95cabceaf24dfd8715768bbedc935c98
refs/heads/master
<file_sep>boto3==1.9.124 requests==2.21.0 <file_sep>#!/bin/bash set -e DISABLE_LIST="W0613,C0111,W1202,W1308,C0103,R0801" echo "Linting Lambdas..." pylint --disable=$DISABLE_LIST src echo "Testing Lambdas..." python -m pytest --cov=src test -W ignore::DeprecationWarning if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then pushd src for LAMBDA in $(ls -d */ | cut -f1 -d"/"); do if [[ $(ls $LAMBDA | grep index.py | wc -l) -eq 1 ]]; then pushd $LAMBDA echo "Building Lambda $LAMBDA..." mkdir build pip install -r requirements.txt --target build cp *.py build pushd build zip -r9 ../$LAMBDA.zip . popd rm -rf build echo "Publishing Lambda $LAMBDA..." aws s3 cp $LAMBDA.zip s3://$S3_BUCKET/$LAMBDA.zip --acl private aws lambda update-function-code --function-name $LAMBDA --s3-bucket $S3_BUCKET --s3-key $LAMBDA.zip --publish | grep Version rm -rf $LAMBDA.zip echo "Successfully deployed Lambda $LAMBDA." popd fi done popd else echo "Just a PR, skipping Build & Deploy." fi <file_sep>import logging import os IS_DEBUGGING = str(os.environ.get("DEBUGGING", "no")).strip().lower() == "yes" LOGGER = logging.getLogger() LOGGER.setLevel(logging.DEBUG if IS_DEBUGGING else logging.INFO) LOGGER.debug("Loading lambda...") def hello_world_handler(event, context): LOGGER.debug("Running hello world...") LOGGER.info("Hello World!") LOGGER.info("Successfully ran hello world.") <file_sep>from src.HelloWorld import index def test_hello_world_handler(): assert index.hello_world_handler(None, None) is None <file_sep>astroid==2.2.5 atomicwrites==1.3.0 attrs==19.1.0 aws-sam-translator==1.10.0 aws-xray-sdk==2.4.2 awscli==1.16.126 boto3==1.9.124 botocore==1.12.124 certifi==2019.3.9 cfn-lint==0.17.1 chardet==3.0.4 Click==7.0 colorama==0.3.9 coverage==4.5.3 decorator==4.4.0 docutils==0.14 flexmock==0.10.3 future==0.17.1 idna==2.8 isort==4.3.15 Jinja2==2.10.1 jmespath==0.9.4 jsonpatch==1.23 jsonpickle==1.1 jsonpointer==2.0 jsonschema==2.6.0 lazy-object-proxy==1.3.1 MarkupSafe==1.1.1 mccabe==0.6.1 more-itertools==6.0.0 networkx==2.1 packaging==16.8 pluggy==0.9.0 py==1.8.0 pyasn1==0.4.5 pylint==2.3.1 pyparsing==2.3.1 pytest==4.3.1 pytest-cov==2.6.1 python-coveralls==2.9.1 python-dateutil==2.8.0 PyYAML==4.2b4 requests==2.21.0 rsa==3.4.2 s3transfer==0.2.0 sceptre==2.1.0 six==1.12.0 typed-ast==1.3.1 urllib3==1.24.2 wrapt==1.11.1 <file_sep>#!/bin/bash set -e IGNORE_LIST="W3005" echo "Linting Templates..." cfn-lint -i $IGNORE_LIST -t templates/*.yaml pushd config STACKS=$(ls -d */ | cut -f1 -d"/") popd for STACK in $STACKS; do echo "Launching Stack: $STACK..." sceptre validate $STACK sceptre launch $STACK -y echo "Successfully launched Stack: $STACK." done <file_sep>import logging import os import re import boto3 import requests IS_DEBUGGING = str(os.environ.get("DEBUGGING", "no")).strip().lower() == "yes" LOGGER = logging.getLogger() LOGGER.setLevel(logging.DEBUG if IS_DEBUGGING else logging.INFO) LOGGER.debug("Loading lambda...") AWS_REGION = str(os.environ.get("AWS_REGION", "us-west-2")).strip() AV_API_KEY = str(os.environ.get("ALPHA_VANTAGE_KEY", "demo")).strip() AV_URI = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={}&apikey={}" SNS_TOPIC = str(os.environ.get("SNS_TOPIC", "demo")).strip() SYMBOLS_PARAM = str(os.environ.get("SYMBOLS_PARAM", "/Demo/Symbols")).strip() TICKER_RE = re.compile("^[A-Z]{1,5}$") def get_stock_symbols(): ssm_client = boto3.client("ssm", region_name=AWS_REGION) symbols = [] for symbol in ssm_client.get_parameter(Name=SYMBOLS_PARAM)["Parameter"]["Value"].split(","): symbols.append(symbol.strip().upper()) return symbols def send_results(results, account_id): if results: LOGGER.info("Sending results to SNS Topic: {}...") sns_client = boto3.client("sns") sns_client.publish( TopicArn="arn:aws:sns:{}:{}:{}".format(AWS_REGION, account_id, SNS_TOPIC), Message="\n{}".format("\n".join(results)) ) LOGGER.info("Successfully sent results to SNS Topic: {}.") else: LOGGER.warning("No results to send!") def stock_tracker_handler(event, context): LOGGER.info("Running stock tracker...") if "symbol" in event: stock_symbols = [str(event["symbol"]).strip().upper()] else: stock_symbols = get_stock_symbols() results = [] for stock_symbol in stock_symbols: if TICKER_RE.fullmatch(stock_symbol) is None: err_msg = "Invalid stock ticker: {}!".format(stock_symbol) LOGGER.error(err_msg) raise ValueError(err_msg) LOGGER.debug("Retrieving stock info from Alphavantage for {}...".format(stock_symbol)) final_uri = AV_URI.format(stock_symbol, AV_API_KEY) LOGGER.debug("Calling {}...".format(final_uri)) stock_req = requests.get(final_uri, timeout=5) if not stock_req.ok: LOGGER.error("Alphavantage request failed with status: {}!" .format(stock_req.status_code)) stock_req.raise_for_status() LOGGER.info("Successfully retrieved stock info from Alphavantage for {}." .format(stock_symbol)) LOGGER.debug("Parsing lastest stock info for {}...".format(stock_symbol)) stock_info = stock_req.json()["Global Quote"] if stock_info is None or not bool(stock_info): err_msg = "Alphavantage returned empty response!" LOGGER.error(err_msg) raise ValueError(err_msg) stock_price = float(stock_info["05. price"]) stock_change = float(stock_info["09. change"]) stock_change_symbol = "-" if stock_change < 0 else "+" stock_change_percent = abs(float(stock_info["10. change percent"].rstrip("%"))) LOGGER.debug("Successfully parsed lastest stock info for {}.".format(stock_symbol)) result = "{}: ${:.2f} {}${:.2f} ({}{:.2f}%)".format(stock_symbol, stock_price, stock_change_symbol, abs(stock_change), stock_change_symbol, stock_change_percent) LOGGER.info(result) results.append(result) account_id = context.invoked_function_arn.split(":")[4] send_results(results, account_id) return results <file_sep># Lambda Utils [![Build Status](https://travis-ci.org/developerDemetri/lambda-utils.svg?branch=master)](https://travis-ci.org/developerDemetri/lambda-utils) [![Coverage Status](https://coveralls.io/repos/github/developerDemetri/lambda-utils/badge.svg?branch=master)](https://coveralls.io/github/developerDemetri/lambda-utils?branch=master) [![Known Vulnerabilities](https://snyk.io/test/github/developerDemetri/lambda-utils/badge.svg?targetFile=requirements.txt)](https://snyk.io/test/github/developerDemetri/lambda-utils?targetFile=requirements.txt) Useful little Lambda collection ## Developer Setup 1) Ensure you're running Python 3.7.x ([pyenv](https://github.com/pyenv/pyenv/blob/master/README.md) is suggested for managing Python versions) 2) Run `pip install requirements.txt` to install testing requirements ## Repository Structure Each directory under [`functions`](https://github.com/developerDemetri/lambda-utils/tree/master/functions) is the name of the Lambda Function that it contains. Each Lambda has: 1) `__init__.py`, `index.py`, and other required source code files 2) `test_<lambda_name>.py` file that defines pytests under [`test`](https://github.com/developerDemetri/lambda-utils/tree/master/functions/test) 3) `requirements.txt` that defines dependencies ``` LambdaName ├── __init__.py ├── index.py └── requirements.txt ``` The [`sceptre`](https://github.com/developerDemetri/lambda-utils/tree/master/sceptre) directory contains a [Sceptre](https://sceptre.cloudreach.com/latest/about.html) setup for orchestrating AWS Resources. <file_sep>import copy import boto3 from flexmock import flexmock import requests from requests.exceptions import ReadTimeout from src.SiteMonitor import index SITE_LIST = [ { "id": 1, "name": "mock.io", "is_down": True }, { "id": 2, "name": "mock.com", "is_down": False } ] STAT_LIST = copy.deepcopy(SITE_LIST) STAT_LIST[0]["check_time"] = "2019-03-29T13:05:38.876628" STAT_LIST[0]["response_code"] = 418 STAT_LIST[0]["response_time"] = 0.1 STAT_LIST[1]["check_time"] = "2019-03-29T13:06:12.102297" STAT_LIST[1]["response_code"] = 200 STAT_LIST[1]["response_time"] = 0.5 def test_get_sites(): fake_client = flexmock() fake_client.should_receive("scan").with_args( TableName="demo", ConsistentRead=True ).and_return({"Items": [ {"is_down": {"BOOL": True}, "site_id": {"N": "1"}, "site_name": {"S": "mock.io"}}, {"is_down": {"BOOL": False}, "site_id": {"N": "2"}, "site_name": {"S": "mock.com"}} ]}).once() assert index.get_sites(fake_client) == SITE_LIST def test_save_stats(): fake_client = flexmock() fake_client.should_receive("update_item").with_args( TableName="demo", Key={"site_id": {"N": "1"}}, UpdateExpression="SET is_down = :val", ExpressionAttributeValues={":val": {"BOOL": True}} ).once() fake_client.should_receive("update_item").with_args( TableName="demo", Key={"site_id": {"N": "2"}}, UpdateExpression="SET is_down = :val", ExpressionAttributeValues={":val": {"BOOL": False}} ).once() fake_client.should_receive("put_item").with_args( TableName="demo", Item={ "site_id": {"N": "1"}, "site_name": {"S": "mock.io"}, "timestamp": {"S": "2019-03-29T13:05:38.876628"}, "is_down": {"BOOL": True}, "response_code": {"N": "418"}, "response_time": {"N": "0.1"} } ).once() fake_client.should_receive("put_item").with_args( TableName="demo", Item={ "site_id": {"N": "2"}, "site_name": {"S": "mock.com"}, "timestamp": {"S": "2019-03-29T13:06:12.102297"}, "is_down": {"BOOL": False}, "response_code": {"N": "200"}, "response_time": {"N": "0.5"} } ).once() index.save_stats(fake_client, STAT_LIST) def test_send_alert(): fake_client = flexmock() fake_client.should_receive("publish").with_args( TopicArn="arn:aws:sns:us-west-2:123456789:demo", Subject="Site Monitor Alert: Webite(s) Down", Message="\n".join([ "The following site(s) returned unhealthy responses:", "\tmock.io\t418", "DeveloperDemetri Site Monitor" ]) ).once() flexmock(boto3).should_receive("client").with_args("sns").and_return(fake_client).once() index.send_alert("123456789", [STAT_LIST[0]]) index.send_alert("123456789", []) def test_site_monitor_handler(): mock = flexmock() mock.should_receive("total_seconds").and_return(0.1).and_return(0.5).and_return(0.5).times(3) flexmock(boto3).should_receive("client").with_args("dynamodb").and_return(mock).twice() flexmock(index).should_receive("get_sites").with_args(mock).and_return(SITE_LIST).twice() bad_resp = flexmock(status_code=418, elapsed=mock) good_resp = flexmock(status_code=200, elapsed=mock) flexmock(requests).should_receive("get").with_args("https://mock.io", timeout=index.MAX_TIME)\ .and_return(bad_resp).and_raise(ReadTimeout()).twice() flexmock(requests).should_receive("get").with_args("https://mock.com", timeout=index.MAX_TIME)\ .and_return(good_resp).twice() flexmock(index).should_receive("save_stats").and_return(None).twice() flexmock(index).should_receive("send_alert").and_return(None).twice() fake_context = flexmock( invoked_function_arn="arn:aws:lambda:us-west-2:123456789:function:demo" ) assert index.site_monitor_handler(dict(), fake_context) is None assert index.site_monitor_handler(dict(), fake_context) is None <file_sep>from datetime import datetime import logging import os import boto3 import requests from requests.exceptions import ReadTimeout IS_DEBUGGING = str(os.environ.get("DEBUGGING", "no")).strip().lower() == "yes" LOGGER = logging.getLogger() LOGGER.setLevel(logging.DEBUG if IS_DEBUGGING else logging.INFO) LOGGER.debug("Loading lambda...") AWS_REGION = str(os.environ.get("AWS_REGION", "us-west-2")).strip() MAX_TIME = 3 SITE_DYNAMO_TABLE = str(os.environ.get("SITE_DYNAMO_TABLE", "demo")).strip() STATS_DYNAMO_TABLE = str(os.environ.get("STATS_DYNAMO_TABLE", "demo")).strip() SNS_TOPIC = str(os.environ.get("SNS_TOPIC", "demo")).strip() def get_sites(dynamo_client): LOGGER.info("Retrieving list of sites...") sites = [] for item in dynamo_client.scan(TableName=SITE_DYNAMO_TABLE, ConsistentRead=True)["Items"]: sites.append({ "id": int(item["site_id"]["N"]), "name": str(item["site_name"]["S"]), "is_down": bool(item["is_down"]["BOOL"]) }) LOGGER.debug(str(sites)) LOGGER.info("Successfully retrieved list of {} sites.".format(len(sites))) return sites def save_stats(dynamo_client, sites): LOGGER.info("Saving all Site info in Dynamo...") for site in sites: LOGGER.info("Saving info in Dynamo for {}...".format(site["name"])) dynamo_client.update_item( TableName=SITE_DYNAMO_TABLE, Key={"site_id": {"N": str(site["id"])}}, UpdateExpression="SET is_down = :val", ExpressionAttributeValues={":val": {"BOOL": site["is_down"]}} ) LOGGER.debug("Successfully updated Site table for {}.".format(site["name"])) dynamo_client.put_item( TableName=STATS_DYNAMO_TABLE, Item={ "site_id": {"N": str(site["id"])}, "site_name": {"S": site["name"]}, "timestamp": {"S": site["check_time"]}, "is_down": {"BOOL": site["is_down"]}, "response_code": {"N": str(site["response_code"])}, "response_time": {"N": str(site["response_time"])} } ) LOGGER.debug("Successfully updated Stats table for {}.".format(site["name"])) LOGGER.info("Successfully saved all Site info in Dynamo.") def send_alert(account_id, down_site_list): if down_site_list: LOGGER.debug("Down Site List: {}".format(down_site_list)) sns_client = boto3.client("sns") LOGGER.warning("Alerting for {} site(s) down...".format(len(down_site_list))) message_parts = ["The following site(s) returned unhealthy responses:"] for site_info in down_site_list: message_parts.append("\t{}\t{}".format(site_info["name"], site_info["response_code"])) message_parts.append("DeveloperDemetri Site Monitor") LOGGER.debug("\n".join(message_parts)) sns_client.publish( TopicArn="arn:aws:sns:{}:{}:{}".format(AWS_REGION, account_id, SNS_TOPIC), Subject="Site Monitor Alert: Webite(s) Down", Message="\n".join(message_parts) ) LOGGER.info("Sucessfully alerted for {} site(s) down...".format(len(down_site_list))) else: LOGGER.info("No Sites to alert on :)") def site_monitor_handler(event, context): LOGGER.debug("Running site monitor...") dynamo_client = boto3.client("dynamodb") crashed_sites = [] sites = get_sites(dynamo_client) for site in sites: already_down = site["is_down"] site["check_time"] = datetime.now().isoformat() try: resp = requests.get("https://{}".format(site["name"]), timeout=MAX_TIME) site["is_down"] = bool(resp.status_code != 200) site["response_code"] = int(resp.status_code) site["response_time"] = float(resp.elapsed.total_seconds()) except ReadTimeout as err: LOGGER.warning("Site check {} timed out: {}".format(site["name"], err)) site["is_down"] = True site["response_code"] = 504 site["response_time"] = MAX_TIME LOGGER.debug(str(site)) if site["is_down"] and not already_down: crashed_sites.append(site) account_id = context.invoked_function_arn.split(":")[4] save_stats(dynamo_client, sites) send_alert(account_id, crashed_sites) LOGGER.info("Successfully ran site monitor.") <file_sep>import boto3 from flexmock import flexmock import pytest import requests from requests.exceptions import HTTPError from src.StockTracker import index FAKE_URI = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=GDDY&apikey=demo" EXPECTED_RESULTS = ["GDDY: $75.11 +$0.90 (+1.21%)"] def test_get_symbols(): fake_client = flexmock() fake_client.should_receive("get_parameter").with_args(Name="/Demo/Symbols").and_return({ "Parameter": { "Name": "/Demo/Symbols", "Type": "StringList", "Value": "amzn, msft " } }).once() flexmock(boto3).should_receive("client").with_args( "ssm", region_name="us-west-2" ).and_return(fake_client).once() assert index.get_stock_symbols() == ["AMZN", "MSFT"] def test_send_results(): fake_client = flexmock() fake_client.should_receive("publish").with_args( TopicArn="arn:aws:sns:us-west-2:123456789:demo", Message="\n{}".format("\n".join(EXPECTED_RESULTS)) ).once() flexmock(boto3).should_receive("client").with_args("sns").and_return(fake_client).once() index.send_results(EXPECTED_RESULTS, "123456789") def test_stock_tracker_handler_bad_ticker(): bad_event = {"symbol": "gdd&"} with pytest.raises(ValueError): index.stock_tracker_handler(bad_event, None) def test_stock_tracker_handler_bad_resp(): event = {"symbol": "gddy"} fake_req = flexmock(ok=False, status_code=418) fake_req.should_receive("raise_for_status").and_raise(HTTPError("no bueno")).once() flexmock(requests).should_receive("get").with_args(FAKE_URI, timeout=5).and_return(fake_req).once() with pytest.raises(HTTPError): index.stock_tracker_handler(event, None) def test_stock_tracker_handler_empty_resp(): event = {"symbol": "gddy"} fake_req = flexmock(ok=True, status_code=200) fake_req.should_receive("json").and_return({ "Global Quote": {} }).once() flexmock(requests).should_receive("get").with_args(FAKE_URI, timeout=5).and_return(fake_req).once() with pytest.raises(ValueError): index.stock_tracker_handler(event, None) def test_stock_tracker_handler_with_event(): event = {"symbol": "gddy"} fake_req = flexmock(ok=True, status_code=200) fake_req.should_receive("json").and_return({ "Global Quote": { "01. symbol": "GDDY", "02. open": "74.6200", "03. high": "75.4250", "04. low": "73.9200", "05. price": "75.1100", "06. volume": "1121316", "07. latest trading day": "2019-03-28", "08. previous close": "74.2100", "09. change": "0.9000", "10. change percent": "1.2128%" } }).once() flexmock(requests).should_receive("get").with_args(FAKE_URI, timeout=5).and_return(fake_req).once() flexmock(index).should_receive("send_results").with_args(EXPECTED_RESULTS, "123456789").and_return(None).once() fake_context = flexmock( invoked_function_arn="arn:aws:lambda:us-west-2:123456789:function:demo" ) assert index.stock_tracker_handler(event, fake_context) == EXPECTED_RESULTS
2528e28c223019a3d3edadcd0dbafc50e627ff46
[ "Markdown", "Python", "Text", "Shell" ]
11
Text
developerDemetri/lambda-utils
d2afa4e185f77655bb4b297024107ae94926d952
405ed75c3c2fc56d6ac088712b1aef449fb2ee89
refs/heads/master
<repo_name>svagionitis/random_insert<file_sep>/detail/node.hpp /////////////////////////////////////////////////////////////////// // // // Copyright (c) 2006, Universidad de Alcala // // // // See accompanying LICENSE.TXT // // // /////////////////////////////////////////////////////////////////// /* detail/node.hpp --------------- The class avl_array_node_tree_fields, defined here, contains all the links required by tree nodes. It does _not_ contain the payload value_type (see detail/node_with_data.hpp). Two classes inherit from avl_array_node_tree_fields: avl_array_node (see detail/node_with_data.hpp) avl_array (see avl_array.hpp) */ #ifndef _AVL_ARRAY_NODE_HPP_ #define _AVL_ARRAY_NODE_HPP_ #ifndef _AVL_ARRAY_HPP_ #error "Don't include this file. Include avl_array.hpp instead." #endif namespace mkr // Public namespace { namespace detail // Private nested namespace mkr::detail { ////////////////////////////////////////////////////////////////// /* The type enum_left_right declares L and R. Every tree node stores the pointers to its children in an array of two pointers. L and R (constant values) are often used as index in the array, but in some cases the index is a variable. We can take advantage of symmetry: if children[x] is one side, children[1-x] is the other one. */ typedef enum { L=0, R=1 } enum_left_right; ////////////////////////////////////////////////////////////////// template<class T, class A, // Data of a tree node (payload class W, class P> // not included) class avl_array_node_tree_fields { // Note that the dummy has no T friend class mkr::avl_array<T,A,W,P>; friend class rollback_list<T,A,W,P>; typedef avl_array_node_tree_fields<T,A,W,P> node_t; protected: // Tree links (parent of root and children of leafs are NULL) node_t * m_parent; // parent node node_t * m_children[2]; // [0]:left [1]:right // Circular doubly linked list (equiv. to in-order travel) node_t * m_next; // (last_node.next==dummy) node_t * m_prev; // (first_node.prev==dummy) // Data for balancing, indexing, and stable-sort std::size_t m_height; // levels in subtree, including self std::size_t m_count; // nodes in subtree, including self P m_oldpos; // position (used only in stable_sort) // Alternative sequence view: W m_node_width; // Width of this node W m_total_width; // Width of this subtree // Constructor and initializer, both O(1) avl_array_node_tree_fields (); // Default constructor void init (); // Write default values // Helper functions, all O(1) (no loop, no recursion) std::size_t left_count () const; // Nodes in left subtree std::size_t right_count () const; // Nodes in right subtree std::size_t left_height () const; // Height of left subtree std::size_t right_height () const; // Height of right subtree W left_width () const; // Width of left subtree W right_width () const; // Width of right subtree }; ////////////////////////////////////////////////////////////////// // Initializer, or "reset" method: write default values template<class T,class A,class W,class P> inline void avl_array_node_tree_fields<T,A,W,P>:: init () // Write default values { m_parent = m_children[L] = m_children[R] = NULL; // No relatives m_next = m_prev = this; // Loop list m_height = m_count = 1; // Single element, single level m_node_width = m_total_width = W(1); // Default } // width // Constructor: just call init() template<class T,class A,class W,class P> inline avl_array_node_tree_fields<T,A,W,P>:: avl_array_node_tree_fields () { init (); } // Helper functions: return count/height/width of left/right // subtree. This doesn't require loops or recursion. If the // left/right subtree is empty, return 0; otherwise, return // the count/height/width of its root. Time required is O(1) template<class T,class A,class W,class P> inline std::size_t avl_array_node_tree_fields<T,A,W,P>:: left_count () const { return m_children[L] ? m_children[L]->m_count : 0; } template<class T,class A,class W,class P> inline std::size_t avl_array_node_tree_fields<T,A,W,P>:: right_count () const { return m_children[R] ? m_children[R]->m_count : 0; } template<class T,class A,class W,class P> inline std::size_t avl_array_node_tree_fields<T,A,W,P>:: left_height () const { return m_children[L] ? m_children[L]->m_height : 0; } template<class T,class A,class W,class P> inline std::size_t avl_array_node_tree_fields<T,A,W,P>:: right_height () const { return m_children[R] ? m_children[R]->m_height : 0; } template<class T,class A,class W,class P> inline W avl_array_node_tree_fields<T,A,W,P>:: left_width () const { return m_children[L] ? m_children[L]->m_total_width : W(0); } template<class T,class A,class W,class P> inline W avl_array_node_tree_fields<T,A,W,P>:: right_width () const { return m_children[R] ? m_children[R]->m_total_width : W(0); } ////////////////////////////////////////////////////////////////// } // namespace detail } // namespace mkr #endif <file_sep>/bench_btree_array.cpp #include "btree_array.hpp" #include "bench.hpp" #include <algorithm> template<typename T> class btree_array_wrapper_t { private: btree_array_t<T> nums_; public: std::size_t size() { return nums_.size(); } void insert(std::size_t index, T num) { nums_.insert(index, num); } template<typename Functor> void iterate(Functor functor) { nums_.iterate([=](std::uint64_t * data, std::size_t data_size) { std::for_each(data, data + data_size, [=](std::uint64_t num) { functor(num); }); }); } }; int main(int argc, char * * argv) { bench<btree_array_wrapper_t>(argc, argv); } <file_sep>/Makefile CFLAGS=-O3 -Wall -Wextra -pedantic -Wno-unused-parameter -std=c++11 all: bench_list bench_vector bench_avl_array bench_btree_array bench_list: bench_list.cpp bench.hpp ${CXX} -o bench_list bench_list.cpp ${CFLAGS} bench_vector: bench_vector.cpp bench.hpp ${CXX} -o bench_vector bench_vector.cpp ${CFLAGS} bench_avl_array: bench_avl_array.cpp bench.hpp ${CXX} -o bench_avl_array bench_avl_array.cpp ${CFLAGS} bench_btree_array: bench_btree_array.cpp bench.hpp ${CXX} -o bench_btree_array bench_btree_array.cpp ${CFLAGS} clean: rm -rf bench_vector bench_avl_array bench_btree_array run: run_list run_vector run_avl_array run_btree_array run_list: bench_list perf stat -r3 ./bench_list 10 perf stat -r3 ./bench_list 100 perf stat -r3 ./bench_list 1000 perf stat -r3 ./bench_list 10000 perf stat -r3 ./bench_list 100000 run_vector: bench_vector perf stat -r3 ./bench_vector 10 perf stat -r3 ./bench_vector 100 perf stat -r3 ./bench_vector 1000 perf stat -r3 ./bench_vector 10000 perf stat -r3 ./bench_vector 100000 perf stat -r3 ./bench_vector 1000000 run_avl_array: bench_avl_array perf stat -r3 ./bench_avl_array 10 perf stat -r3 ./bench_avl_array 100 perf stat -r3 ./bench_avl_array 1000 perf stat -r3 ./bench_avl_array 10000 perf stat -r3 ./bench_avl_array 100000 perf stat -r3 ./bench_avl_array 1000000 perf stat -r3 ./bench_avl_array 10000000 run_btree_array: bench_btree_array perf stat -r3 ./bench_btree_array 10 perf stat -r3 ./bench_btree_array 100 perf stat -r3 ./bench_btree_array 1000 perf stat -r3 ./bench_btree_array 10000 perf stat -r3 ./bench_btree_array 100000 perf stat -r3 ./bench_btree_array 1000000 perf stat -r3 ./bench_btree_array 10000000 perf stat -r3 ./bench_btree_array 100000000 <file_sep>/README.md There is a misleading [video](https://www.youtube.com/watch?v=YQs6IC-vgmo) that seems show up on reddit every so often. In it <NAME> extolls the virtues of vectors while denouncing linked lists. He shows that for a given task vectors are much faster than linked lists even though in theory linked lists should do very well. The problem with his approach is that he takes an operation that linked lists are very good at (insert/delete) and then substitutes a different operation to benchmark (linear search + insert/delete). He then goes on to talk about caches and memory use. There is an implication that vector somehow overcomes the superior runtime complexity of list due to its own superior constant factors. This is completely false, both have linear complexity here. If this implication was not meant to be made then why mention that list is really good at insertion and deletion? It's also misleading to talk about caches because you usually dont have to give up cache efficiency to acheive better runtime complexity. Lists trade away constant time indexing to get constant time insert/delete. They then give up cache efficiency for iterator/reference stability. If both of these properties are needed for your problem, then lists may be for you. If not, there are probably better datastructures available. But let's not let vector off the hook so easily, while it may have great constant factors, it's *also* terrible for this problem due to its linear per operation behaviour. To show that runtime complexity and cache efficiency are orthoganal, I have selected a problem similar to what Bjarne used and benchmarked it against 4 different data structures. I use std::vector and std::list from the standard library and also 2 non-standard classes. First I use [avl_array](http://avl-array.sourceforge.net/), which is an avl tree that offers logarithmic insert at an arbitrary index as well stable iterators but poor cache efficiency. Next I use a b+tree class that I wrote which offers logarithmic insertion at an arbitrary index as well as good cache efficiency but can not provide stable iterators. Below is a table showing some of the properties of each data structure. | **cache inefficient** | **cache efficient** | ----------------|:----------------------:|:-------------------:| **linear** | list | vector | **logarithmic** | avl_array | btree_array | The task at hand is this: Insert the numbers 0 - N into random positions in a sequence. Below are the timings in seconds for different values of N. | **list** | **vector** | **avl_array** | **btree_array** | --------------|--------------:|--------------:|----------------:|----------------:| **10** | 0.000941370 | 0.000934011 | 0.000938341 | 0.000940762 | **100** | 0.001084006 | 0.001096881 | 0.001098301 | 0.001182809 | **1000** | 0.001769533 | 0.001056606 | 0.001232885 | 0.000994284 | **10000** | 0.379775849 | 0.009943421 | 0.005019796 | 0.003015072 | **100000** | 51.701910351 | 0.970821829 | 0.060822126 | 0.015336007 | **1000000** | *out of time* | 155.485687811 | 1.271527184 | 0.187348144 | **10000000** | *out of time* | *out of time* | 22.117999131 | 3.400824379 | **100000000** | *out of time* | *out of time* | *out of memory* | 57.620256751 | You can see that avl_array quickly overtakes vector despite its poor cache behaviour and btree_array scales without sacraficing cache efficiency. If you would like to run the benchmarks yourself, clone this repository and type "make run" <file_sep>/bench_vector.cpp #include "bench.hpp" #include <vector> template<typename T> class vector_wrapper_t { private: std::vector<T> nums_; public: std::size_t size() { return nums_.size(); } void insert(std::size_t index, T num) { auto iter = nums_.begin() + index; nums_.insert(iter, num); } template<typename Functor> void iterate(Functor functor) { for (auto num : nums_) functor(num); } }; int main(int argc, char * * argv) { bench<vector_wrapper_t>(argc, argv); } <file_sep>/detail/empty_number.hpp /////////////////////////////////////////////////////////////////// // // // Copyright (c) 2006, Universidad de Alcala // // // // See accompanying LICENSE.TXT // // // /////////////////////////////////////////////////////////////////// /* detail/empty_number.hpp ----------------------- Class intended to be used as default parameter when features like NPSV or stable_sort are not wanted. Compilers should optimize away memory and operations of this class. */ #ifndef _AVL_ARRAY_EMPTY_NUMBER_HPP_ #define _AVL_ARRAY_EMPTY_NUMBER_HPP_ #ifndef _AVL_ARRAY_HPP_ #error "Don't include this file. Include avl_array.hpp instead." #endif namespace mkr // Public namespace { namespace detail // Private nested namespace mkr::detail { ////////////////////////////////////////////////////////////////// class empty_number // Class supporting some numeric operators { // but containing no number at all public: empty_number (int n=0) { } empty_number (std::size_t n) { } empty_number operator+ (const empty_number &) const { return empty_number(); } empty_number operator- (const empty_number &) const { return empty_number(); } empty_number operator+= (const empty_number &) { return empty_number(); } empty_number operator-= (const empty_number &) { return empty_number(); } empty_number & operator++ () { return *this; } empty_number & operator-- () { return *this; } empty_number operator++ (int) { return *this; } empty_number operator-- (int) { return *this; } }; inline bool operator== (const empty_number &, const empty_number &) { return true; } inline bool operator!= (const empty_number &, const empty_number &) { return false; } inline bool operator< (const empty_number &, const empty_number &) { return false; } inline bool operator> (const empty_number &, const empty_number &) { return false; } inline bool operator<= (const empty_number &, const empty_number &) { return true; } inline bool operator>= (const empty_number &, const empty_number &) { return true; } ////////////////////////////////////////////////////////////////// } // namespace detail } // namespace mkr #endif <file_sep>/bench.hpp #pragma once #include <cstdint> #include <cstdlib> #include <iostream> #include <random> template<template<typename> class Seq> void bench(int argc, char * * argv) { std::size_t count = std::atoi(argv[1]); std::mt19937_64 engine; Seq<std::uint64_t> nums; // Insert count integers randomly for (std::size_t i = 0; i != count; ++i) { std::uniform_int_distribution<std::size_t> dist(0, nums.size()); auto index = dist(engine); nums.insert(index, i); } // Run a checksum to verify result // std::uint64_t constexpr prime = (1ULL << 32) - 5; // std::uint64_t a = 1; // std::uint64_t b = 0; // nums.iterate([&](std::uint64_t num) // { // a = (a + num) % prime; // b = (b + a) % prime; // }); // std::uint64_t total = (b << 32) | a; // std::cout << total << "\n"; } <file_sep>/btree_array.hpp #pragma once #include <cassert> #include <iostream> #include <limits> #include <string> #include <type_traits> template< typename T, std::size_t target_branch_size = 512, std::size_t target_leaf_size = 512, std::size_t maximum_size = std::numeric_limits<std::size_t>::max()> class btree_array_t { private: struct node_t { std::size_t size; void * pointer; }; // Compute the logarithm rounded up to the nearest int static std::size_t constexpr log(std::size_t num, std::size_t base, std::size_t result) { return num != 0 ? log(num / base, base, result + 1) : result; } static std::size_t constexpr log(std::size_t num, std::size_t base) { return log(num - 1, base, 0); } static_assert(std::is_pod<T>::value, "T must be a pod"); static std::size_t constexpr maximum_branch_size = target_branch_size / sizeof(node_t); static std::size_t constexpr maximum_leaf_size = target_leaf_size / sizeof(T); static_assert(maximum_branch_size >= 3, "maximum_branch_size must be at least 3"); static std::size_t constexpr minimum_branch_size = (maximum_branch_size + 1) / 2; static std::size_t constexpr minimum_leaf_size = (maximum_leaf_size + 1) / 2; static std::size_t constexpr stack_size = log(maximum_size / minimum_leaf_size, minimum_branch_size); struct branch_t { node_t children[maximum_branch_size]; }; struct leaf_t { T buffer[maximum_leaf_size]; }; struct branch_entry_t { std::size_t size; std::size_t index; branch_t * pointer; }; struct leaf_entry_t { std::size_t size; std::size_t index; leaf_t * pointer; }; node_t root_; std::size_t height_; template<typename Functor> static void iterate(node_t node, std::size_t height, Functor functor) { if (height != 0) { auto branch = static_cast<branch_t *>(node.pointer); auto size = node.size; std::size_t index = 0; while (size != 0) { iterate(branch->children[index], height - 1, functor); size -= branch->children[index].size; ++index; } } else { auto leaf = static_cast<leaf_t *>(node.pointer); functor(leaf->buffer, node.size); } } static std::size_t get_length(branch_t * branch, std::size_t size) { std::size_t index = 0; while (size != 0) { size -= branch->children[index].size; ++index; } return index; } static void delete_node(node_t node, std::size_t height) { if (height != 0) { auto branch = static_cast<branch_t *>(node.pointer); std::size_t index = 0; auto size = node.size; while (size != 0) { delete_node(branch->children[index], height - 1); size -= branch->children[index].size; ++index; } delete branch; } else { auto leaf = static_cast<leaf_t *>(node.pointer); delete leaf; } } template<typename Kind> static void merge( std::size_t index, Kind * orig, std::size_t orig_size, Kind value) { std::char_traits<Kind>::move( orig + index + 1, orig + index, orig_size - index); orig[index] = value; } template<typename Kind> static void split( std::size_t index, std::size_t left_size, std::size_t right_size, Kind * right, Kind * orig, std::size_t orig_size, Kind value) { if (index < left_size) { std::char_traits<Kind>::copy( right, orig + orig_size - right_size, right_size); std::char_traits<Kind>::move( orig + index + 1, orig + index, left_size - 1 - index); orig[index] = value; } else { std::char_traits<Kind>::copy( right, orig + left_size, index - left_size); std::char_traits<Kind>::copy( right + index + 1 - left_size, orig + index, orig_size - index); right[index - left_size] = value; } } leaf_entry_t seek(branch_entry_t * first, branch_entry_t * last, node_t current, std::size_t index) { while (first != last) { auto branch = static_cast<branch_t *>(current.pointer); std::size_t branch_index = 0; while (true) { auto child_size = branch->children[branch_index].size; if (index <= child_size) break; index -= child_size; ++branch_index; } branch_entry_t entry; entry.size = current.size; entry.index = branch_index; entry.pointer = branch; *--last = entry; current = branch->children[branch_index]; } leaf_entry_t entry; entry.size = current.size; entry.index = index; entry.pointer = static_cast<leaf_t *>(current.pointer); return entry; } void update_sizes(branch_entry_t * first, branch_entry_t * last) { while (first != last) { auto & entry = *first++; ++entry.pointer->children[entry.index].size; } ++root_.size; } void insert( branch_entry_t * first, branch_entry_t * last, T value, leaf_entry_t & entry) { auto sum = entry.size + 1; // If we have room for the data in this leaf, we are done if (sum <= maximum_leaf_size) { merge(entry.index, entry.pointer->buffer, entry.size, value); update_sizes(first, last); return; } // No room, split into 2 and insert the first half in the parent auto left_size = sum / 2; auto right_size = sum - left_size; auto right = new leaf_t; split( entry.index, left_size, right_size, right->buffer, entry.pointer->buffer, entry.size, value); insert(first, last, left_size, {right_size, right}); } void insert( branch_entry_t * first, branch_entry_t * last, std::size_t left_size, node_t right_node) { while (first != last) { auto & entry = *first++; auto branch_length = get_length(entry.pointer, entry.size); auto sum = branch_length + 1; entry.pointer->children[entry.index].size = left_size; // If we have room for the child we are done if (sum <= maximum_branch_size) { merge(entry.index + 1, entry.pointer->children, branch_length, right_node); update_sizes(first, last); return; } // No room, split into 2 and insert the first half in the parent auto left_length = sum / 2; auto right_length = sum - left_length; auto right = new branch_t; split( entry.index + 1, left_length, right_length, right->children, entry.pointer->children, branch_length, right_node); std::size_t right_size = 0; for (std::size_t I = 0; I != right_length; ++I) right_size += right->children[I].size; right_node = {right_size, right}; left_size = entry.size + 1 - right_size; } // We have reached the root, grow upward auto branch = new branch_t; branch->children[0].pointer = root_.pointer; branch->children[0].size = left_size; branch->children[1] = right_node; root_.pointer = branch; root_.size = left_size + right_node.size; height_++; } public: btree_array_t() : root_{0, nullptr}, height_{0} {} ~btree_array_t() { delete_node(root_, height_); } void insert(std::size_t index, T value) { if (root_.pointer == nullptr) root_.pointer = new leaf_t; branch_entry_t stack[stack_size]; auto entry = seek(stack, stack + height_, root_, index); insert(stack, stack + height_, value, entry); } template<typename Functor> void iterate(Functor functor) const { iterate(root_, height_, functor); } std::size_t size() const { return root_.size; } }; <file_sep>/bench_avl_array.cpp #include "avl_array.hpp" #include "bench.hpp" template<typename T> class avl_array_wrapper_t { private: mkr::avl_array<T> nums_; public: std::size_t size() { return nums_.size(); } void insert(std::size_t index, T num) { auto iter = nums_.begin() + index; nums_.insert(iter, num); } template<typename Functor> void iterate(Functor functor) { for (auto num : nums_) functor(num); } }; int main(int argc, char * * argv) { bench<avl_array_wrapper_t>(argc, argv); } <file_sep>/bench_list.cpp #include "bench.hpp" #include <list> template<typename T> class list_wrapper_t { private: std::list<T> nums_; public: std::size_t size() { return nums_.size(); } void insert(std::size_t index, T num) { auto iter = std::next(nums_.begin(), index); nums_.insert(iter, num); } template<typename Functor> void iterate(Functor functor) { for (auto num : nums_) functor(num); } }; int main(int argc, char * * argv) { bench<list_wrapper_t>(argc, argv); }
f639b23e812e6665b1c1933b9066e1437822cf56
[ "Markdown", "Makefile", "C++" ]
10
C++
svagionitis/random_insert
6f56b7919006f21a2a686accbbf133320f221220
20a5ede5ef6eb468d63651cd3dd058662f178fc3
refs/heads/master
<file_sep>#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """Unit tests for model.py.""" __author__ = '<EMAIL> (<NAME>)' import copy import domains import logs import model import perms import test_utils import users from google.appengine.api import memcache JSON1 = '{"title": "One", "description": "description1"}' JSON2 = '{"title": "Two", "description": "description2"}' JSON3 = '{"title": "Three", "description": "description3"}' class MapTests(test_utils.BaseTest): """Tests the map model classes and associated access control logic.""" def testVersions(self): """Verifies that creating and setting versions works properly.""" with test_utils.RootLogin(): m = model.Map.Create(JSON1, 'xyz.com') id1 = m.GetCurrent().id id2 = m.PutNewVersion(JSON2) # Verify that versions are returned in reverse chronological order. versions = list(m.GetVersions()) self.assertEquals(id2, versions[0].id) self.assertEquals(id1, versions[1].id) # Verify that GetCurrent() sees the most recent version as expected. current = m.GetCurrent() self.assertEquals(id2, current.id) self.assertEquals(JSON2, current.maproot_json) self.assertEquals('root', current.creator_uid) def testWorldReadable(self): # Verify that the current version is only visible to the public after # setting world_readable to True. with test_utils.RootLogin(): m = model.Map.Create(JSON1, 'xyz.com') with test_utils.Login('outsider'): self.assertRaises(perms.AuthorizationError, m.GetCurrent) with test_utils.RootLogin(): m.SetWorldReadable(True) with test_utils.Login('outsider'): self.assertEquals(JSON1, m.GetCurrent().maproot_json) with test_utils.RootLogin(): m.SetWorldReadable(False) with test_utils.Login('outsider'): self.assertRaises(perms.AuthorizationError, m.GetCurrent) def testRevokePermission(self): """Verifies internal model permission lists are correctly modified.""" user1 = test_utils.SetupUser(test_utils.Login('user1')) user2 = test_utils.SetupUser(test_utils.Login('user2')) with test_utils.RootLogin() as user0: m = test_utils.CreateMap() permissions = {perms.Role.MAP_VIEWER: m.model.viewers, perms.Role.MAP_EDITOR: m.model.editors, perms.Role.MAP_OWNER: m.model.owners} initial_grantees = copy.deepcopy(permissions) for role in permissions: permissions[role] += ['user1', 'user2'] m.AssertAccess(role, user1) m.AssertAccess(role, user2) m.RevokePermission(role, 'user2') self.assertEquals(initial_grantees[role] + ['user1'], permissions[role]) self.assertFalse(m.CheckAccess(role, user2)) m.RevokePermission(role, 'user2') # idempotent, no effect self.assertEquals(initial_grantees[role] + ['user1'], permissions[role]) self.assertFalse(m.CheckAccess(role, user2)) m.RevokePermission(role, 'user1') self.assertEquals(initial_grantees[role], permissions[role]) self.assertFalse(m.CheckAccess(role, user1)) # Should do nothing: only viewer, editor, and owner are revocable. m.AssertAccess(perms.Role.ADMIN, user0) m.RevokePermission(perms.Role.ADMIN, 'root') m.AssertAccess(perms.Role.ADMIN, user0) def testChangePermissionLevel(self): """Verifies that permission level changes appropriately.""" user1 = test_utils.SetupUser(test_utils.Login('user1')) with test_utils.RootLogin(): m = test_utils.CreateMap() permissions = {perms.Role.MAP_VIEWER: m.model.viewers, perms.Role.MAP_EDITOR: m.model.editors, perms.Role.MAP_OWNER: m.model.owners} initial_grantees = copy.deepcopy(permissions) for role in permissions: m.ChangePermissionLevel(role, 'user1') # grant permission self.assertEquals(initial_grantees[role] + ['user1'], permissions[role]) self.assertTrue(m.CheckAccess(role, user1)) m.ChangePermissionLevel(role, 'user1') # idempotent, no effect self.assertEquals(initial_grantees[role] + ['user1'], permissions[role]) self.assertTrue(m.CheckAccess(role, user1)) # Make sure the user doesn't have any of the other permissions. for other_role in permissions: if other_role != role: self.assertFalse('user1' in permissions[other_role]) # Should do nothing: only viewer, editor, owner are valid roles. m.ChangePermissionLevel(perms.Role.ADMIN, 'user1') self.assertFalse(m.CheckAccess(perms.Role.ADMIN, user1)) def testCreate(self): """Verifies that map creation works properly.""" # Verify the default values from Map.Create. m = test_utils.CreateMap() self.assertEquals(['root'], m.model.owners) self.assertEquals([], m.model.editors) self.assertEquals([], m.model.viewers) self.assertEquals(['xyz.com'], m.model.domains) self.assertEquals(m.model.world_readable, False) def testInitialDomainRole(self): """Verifies that map creation sets up initial permissions properly.""" # Verify the default values from Map.Create. perms.Grant('member', perms.Role.MAP_CREATOR, 'xyz.com') domains.Domain.Create('xyz.com', initial_domain_role=perms.Role.MAP_OWNER) m = test_utils.CreateMap() self.assertEquals({'root', 'member'}, set(m.model.owners)) self.assertEquals([], m.model.editors) self.assertEquals([], m.model.viewers) domains.Domain.Create('xyz.com', initial_domain_role=perms.Role.MAP_EDITOR) m = test_utils.CreateMap() self.assertEquals(['root'], m.model.owners) self.assertEquals(['member'], m.model.editors) self.assertEquals([], m.model.viewers) domains.Domain.Create('xyz.com', initial_domain_role=perms.Role.MAP_VIEWER) m = test_utils.CreateMap() self.assertEquals(['root'], m.model.owners) self.assertEquals([], m.model.editors) self.assertEquals(['member'], m.model.viewers) domains.Domain.Create('xyz.com', initial_domain_role=None) m = test_utils.CreateMap() self.assertEquals(['root'], m.model.owners) self.assertEquals([], m.model.editors) self.assertEquals([], m.model.viewers) def testMapCache(self): """Tests caching of current JSON data.""" # Verify the default values from Map.Create. with test_utils.RootLogin(): m = model.Map.Create(JSON1, 'xyz.com', world_readable=True) m.PutNewVersion(JSON2) self.assertEquals(JSON2, m.GetCurrentJson()) self.assertEquals(m.title, 'Two') self.assertEquals(m.description, 'description2') # GetCurrentJson should have filled the cache. self.assertEquals(JSON2, memcache.get('Map,%s,json' % m.id)) # PutVersion should clear the cache. m.PutNewVersion(JSON3) self.assertEquals(None, memcache.get('Map,%s,json' % m.id)) self.assertEquals(JSON3, m.GetCurrentJson()) def testGetAll(self): """Tests Maps.GetAll and Maps.GetViewable.""" with test_utils.RootLogin() as root: m1 = model.Map.Create('{}', 'xyz.com', world_readable=True) m2 = model.Map.Create('{}', 'xyz.com', world_readable=False) def ModelKeys(maps): return {m.model.key() for m in maps} all_maps = ModelKeys([m1, m2]) public_maps = ModelKeys([m1]) self.assertEquals(all_maps, ModelKeys(model.Map.GetViewable(root))) self.assertEquals(all_maps, ModelKeys(model.Map.GetAll())) with test_utils.Login('outsider') as outsider: self.assertRaises(perms.AuthorizationError, model.Map.GetAll) self.assertEquals(public_maps, ModelKeys(model.Map.GetViewable(outsider))) class CatalogEntryTests(test_utils.BaseTest): """Tests the CatalogEntry class.""" def testCreate(self): """Tests creation of a CatalogEntry.""" m = test_utils.CreateMap( '{"title": "Fancy fancy"}', editors=['publisher', 'outsider']) self.CaptureLog() with test_utils.Login('outsider'): # User 'outsider' doesn't have CATALOG_EDITOR. self.assertRaises(perms.AuthorizationError, model.CatalogEntry.Create, 'xyz.com', 'label', m) # Even with CATALOG_EDITOR, CatalogEntry.Create should still fail because # user 'outsider' can't view the map. perms.Grant('outsider', perms.Role.CATALOG_EDITOR, 'xyz.com') with test_utils.Login('publisher'): # Initially, user 'publisher' doesn't have CATALOG_EDITOR. self.assertRaises(perms.AuthorizationError, model.CatalogEntry.Create, 'xyz.com', 'label', m) # After we grant CATALOG_EDITOR, 'publisher' should be able to publish. perms.Grant('publisher', perms.Role.CATALOG_EDITOR, 'xyz.com') mc = model.CatalogEntry.Create('xyz.com', 'label', m, is_listed=True) self.assertEquals('xyz.com', mc.domain) self.assertEquals('label', mc.label) self.assertEquals('Fancy fancy', mc.title) self.assertTrue(mc.is_listed) self.assertEquals(m.id, mc.map_id) self.assertLog(logs.Event.MAP_PUBLISHED, map_id=m.id, domain_name='xyz.com', catalog_entry_key=mc.id) # Creating another entry with the same path_name should succeed. model.CatalogEntry.Create('xyz.com', 'label', m) def testDelete(self): m = test_utils.CreateMap('{"title": "Bleg"}', viewers=['viewer']) with test_utils.RootLogin(): entry = model.CatalogEntry.Create('xyz.com', 'label', m, is_listed=True) domains.Domain.Create('xyz.com') # Validate that CatalogEntry is created successfully. self.assertEquals('Bleg', model.CatalogEntry.Get('xyz.com', 'label').title) # Trying to delete a nonexisting entry should raise an exception. self.assertRaises(ValueError, model.CatalogEntry.Delete, 'xyz.com', 'xyz') # Random users shouldn't be able to delete catalog entries. with test_utils.Login('outsider'): self.assertRaises(perms.AuthorizationError, model.CatalogEntry.Delete, 'xyz.com', 'label') # After we grant the CATALOG_EDITOR role, CatalogEntry.Delete should work. perms.Grant('outsider', perms.Role.CATALOG_EDITOR, 'xyz.com') self.CaptureLog() model.CatalogEntry.Delete('xyz.com', 'label') # Assert that the entry is successfully deleted. self.assertEquals(None, model.CatalogEntry.Get('xyz.com', 'label')) self.assertLog( logs.Event.MAP_UNPUBLISHED, uid='outsider', domain_name='xyz.com', map_id=m.id, catalog_entry_key=entry.model.key().name()) # A CatalogEntry cannot be deleted twice. self.assertRaises(ValueError, model.CatalogEntry.Delete, 'xyz.com', 'label') def testDelete_StickyCatalogEntries(self): # Under the sticky catalog policy, even catalog editors should not be able # to delete catalog entries if they are not the owner. m = test_utils.CreateMap(editors=['publisher', 'coworker']) with test_utils.RootLogin(): domains.Domain.Create('xyz.com', has_sticky_catalog_entries=True) perms.Grant('publisher', perms.Role.CATALOG_EDITOR, 'xyz.com') perms.Grant('coworker', perms.Role.CATALOG_EDITOR, 'xyz.com') with test_utils.Login('publisher'): model.CatalogEntry.Create('xyz.com', 'label', m, is_listed=True) with test_utils.Login('coworker'): self.assertRaises(perms.NotCatalogEntryOwnerError, model.CatalogEntry.Delete, 'xyz.com', 'label') with test_utils.Login('publisher'): model.CatalogEntry.Delete('xyz.com', 'label') def testPut(self): """Tests modification and update of an existing CatalogEntry.""" perms.Grant('publisher', perms.Role.CATALOG_EDITOR, 'xyz.com') with test_utils.Login('publisher'): m = test_utils.CreateMap(JSON1, editors=['publisher']) mc = model.CatalogEntry.Create('xyz.com', 'label', m, is_listed=True) self.assertEquals('One', mc.title) # Update the CatalogEntry to point at a new MapVersion. m.PutNewVersion(JSON2) mc = model.CatalogEntry.Get('xyz.com', 'label') self.assertEquals('One', mc.title) # no change yet mc.is_listed = True mc.SetMapVersion(m) # Random users shouldn't be able to update catalog entries. with test_utils.Login('outsider'): self.assertRaises(perms.AuthorizationError, mc.Put) # After we grant the CATALOG_EDITOR role, CatalogEntry.Put should work. perms.Grant('outsider', perms.Role.CATALOG_EDITOR, 'xyz.com') mc.Put() # The CatalogEntry should now point at the new MapVersion. mc = model.CatalogEntry.Get('xyz.com', 'label') self.assertEquals('Two', mc.title) self.assertEquals(JSON2, mc.maproot_json) self.assertEquals(True, mc.is_listed) def testPut_StickyCatalogEntries(self): # Under the sticky catalog policy, even catalog editors should not be able # to update catalog entries if they are not the owner. with test_utils.RootLogin(): domains.Domain.Create('xyz.com', has_sticky_catalog_entries=True) perms.Grant('publisher', perms.Role.CATALOG_EDITOR, 'xyz.com') perms.Grant('coworker', perms.Role.CATALOG_EDITOR, 'xyz.com') with test_utils.Login('publisher'): m = test_utils.CreateMap(JSON1, editors=['publisher', 'coworker']) mc = model.CatalogEntry.Create('xyz.com', 'label', m, is_listed=True) m.PutNewVersion(JSON2) # Even though coworker has CATALOG_EDITOR, she can't overwrite the entry. with test_utils.Login('coworker'): mc.SetMapVersion(m) self.assertRaises(perms.NotCatalogEntryOwnerError, mc.Put) with test_utils.Login('publisher'): mc.Put() # publisher owns the catalog entry, so this succeeds def testListedMaps(self): """Tests CatalogEntry.GetAll and CatalogEntry.GetListed.""" with test_utils.RootLogin(): m = test_utils.CreateMap() mc = model.CatalogEntry.Create('xyz.com', 'abcd', m, is_listed=False) self.assertEquals(0, len(model.CatalogEntry.GetListed())) self.assertEquals(0, len(model.CatalogEntry.GetListed('xyz.com'))) maps = list(model.CatalogEntry.GetAll()) self.assertEquals(1, len(maps)) self.assertEquals(mc.model.key(), maps[0].model.key()) maps = list(model.CatalogEntry.GetAll('xyz.com')) self.assertEquals(1, len(maps)) self.assertEquals(mc.model.key(), maps[0].model.key()) maps = list(model.CatalogEntry.GetByMapId(m.id)) self.assertEquals(1, len(maps)) self.assertEquals(mc.model.key(), maps[0].model.key()) with test_utils.RootLogin(): model.CatalogEntry.Create('xyz.com', 'abcd', m, is_listed=True) maps = model.CatalogEntry.GetListed() self.assertEquals(1, len(maps)) self.assertEquals(mc.model.key(), maps[0].model.key()) maps = model.CatalogEntry.GetListed('xyz.com') self.assertEquals(1, len(maps)) self.assertEquals(mc.model.key(), maps[0].model.key()) def testMapDelete(self): with test_utils.RootLogin(): m = test_utils.CreateMap( owners=['owner'], editors=['editor'], viewers=['viewer']) model.CatalogEntry.Create('xyz.com', 'label', m, is_listed=True) map_id = m.id # Non-owners should not be able to delete the map. with test_utils.Login('editor'): self.assertRaises(perms.AuthorizationError, model.Map.Get(map_id).Delete) with test_utils.Login('viewer'): self.assertRaises(perms.AuthorizationError, model.Map.Get(map_id).Delete) # Owners should be able to delete the map. self.CaptureLog() with test_utils.Login('owner'): m = model.Map.Get(map_id) m.Delete() self.assertTrue(m.is_deleted) self.assertEquals('owner', m.deleter_uid) self.assertLog(logs.Event.MAP_DELETED, map_id=m.id, uid='owner') # The catalog entry should be gone. self.assertEquals(None, model.CatalogEntry.Get('xyz.com', 'label')) # The map should no longer be retrievable by Get and GetAll. self.assertEquals(None, model.Map.Get(map_id)) self.assertEquals([], list(model.Map.GetViewable(users.GetCurrent()))) # Non-admins (even the owner) should not be able to retrieve deleted maps. self.assertRaises(perms.AuthorizationError, model.Map.GetDeleted, map_id) self.CaptureLog() # Admins should be able to undelete, which makes the map viewable again. with test_utils.RootLogin(): m = model.Map.GetDeleted(map_id) m.Undelete() with test_utils.Login('viewer'): self.assertTrue(model.Map.Get(map_id)) self.assertLog(logs.Event.MAP_UNDELETED, map_id=map_id, uid=perms.ROOT.id) def testMapBlock(self): with test_utils.RootLogin(): m = test_utils.CreateMap( owners=['owner'], editors=['editor'], viewers=['viewer']) model.CatalogEntry.Create('xyz.com', 'label', m, is_listed=True) map_id = m.id # Non-admins should not be able to block the map. with test_utils.Login('owner'): m = model.Map.Get(map_id) self.assertRaises(perms.AuthorizationError, m.SetBlocked, True) # Admins should be able to block the map. self.CaptureLog() with test_utils.RootLogin(): m.SetBlocked(True) self.assertTrue(m.is_blocked) self.assertEquals('root', m.blocker_uid) self.assertLog(logs.Event.MAP_BLOCKED, map_id=m.id, uid='root') # The catalog entry should be gone. self.assertEquals(None, model.CatalogEntry.Get('xyz.com', 'label')) # The map should no longer be accessible to non-owners. with test_utils.Login('editor'): self.assertRaises(perms.AuthorizationError, model.Map.Get, map_id) with test_utils.Login('viewer'): self.assertRaises(perms.AuthorizationError, model.Map.Get, map_id) # The map should be accessible to the owner, but not publishable. perms.Grant('owner', perms.Role.CATALOG_EDITOR, 'xyz.com') with test_utils.Login('owner'): m = model.Map.Get(map_id) self.assertRaises(perms.NotPublishableError, model.CatalogEntry.Create, 'xyz.com', 'foo', m) def testMapUnblock(self): with test_utils.RootLogin(): m = test_utils.CreateMap( owners=['owner'], editors=['editor'], viewers=['viewer']) m.SetBlocked(True) self.assertTrue(model.Map.Get(m.id).is_blocked) self.CaptureLog() m.SetBlocked(False) self.assertLog(logs.Event.MAP_UNBLOCKED, uid='root', map_id=m.id) with test_utils.Login('viewer'): n = model.Map.Get(m.id) self.assertFalse(n.is_blocked) def testMapWipe(self): with test_utils.RootLogin(): m = test_utils.CreateMap( owners=['owner'], editors=['editor'], viewers=['viewer']) model.CatalogEntry.Create('xyz.com', 'label', m, is_listed=True) map_id = m.id # Non-admins should not be able to wipe the map. with test_utils.Login('owner'): self.assertRaises(perms.AuthorizationError, m.Wipe) self.CaptureLog() # Admins should be able to wipe the map. with test_utils.RootLogin(): m.Wipe() self.assertLog(logs.Event.MAP_WIPED, uid=perms.ROOT.id, map_id=map_id) # The catalog entry should be gone. self.assertEquals(None, model.CatalogEntry.Get('xyz.com', 'label')) # The map should be totally gone. self.assertEquals(None, model.Map.Get(map_id)) with test_utils.RootLogin(): self.assertEquals(None, model.Map.GetDeleted(map_id)) if __name__ == '__main__': test_utils.main() <file_sep>#!/usr/bin/python # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """Tests for domains.py.""" __author__ = '<EMAIL> (<NAME>)' import cache import config import domains import logs import perms import test_utils class DomainTest(test_utils.BaseTest): """Tests for the domain model.""" def RemoveDefaultDomain(self): default_model = domains.DomainModel.get_by_key_name( config.Get('default_domain')) default_model.delete() def testInitialDomainRole(self): domain = domains.Domain.Get('nosuchdomain.com') self.assertIsNone(domain) domain = domains.Domain.Get('xyz.com') self.assertEquals( perms.Role.MAP_VIEWER, domain.initial_domain_role) domain.initial_domain_role = perms.Role.MAP_EDITOR with test_utils.RootLogin(): domain.Put() self.assertEquals(perms.Role.MAP_EDITOR, domains.Domain.Get('xyz.com').initial_domain_role) def testDomainCreation(self): self.assertIsNone(domains.Domain.Get('MyDomain.com')) self.CaptureLog() domain = domains.Domain.Create('MyDomain.com') self.assertLog(logs.Event.DOMAIN_CREATED, domain_name='mydomain.com') # domain name should have been normalized self.assertEqual('mydomain.com', domain.name) domain.initial_domain_role = perms.Role.MAP_CREATOR with test_utils.RootLogin(): domain.Put() # domains found in the cache should return new instances, but # with identical values other = domains.Domain.Get('MyDomain.com') self.assertTrue(other is not domain) self.assertEqual(perms.Role.MAP_CREATOR, other.initial_domain_role) # changes to a domain shouldn't be seen until Put() is called domain.default_label = 'fancy-map' other = domains.Domain.Get('MyDomain.com') self.assertNotEqual(domain.default_label, other.default_label) # After a put, the new label should be seen with test_utils.RootLogin(): domain.Put() other = domains.Domain.Get('MyDomain.com') self.assertEqual(domain.default_label, other.default_label) # Verify the most recent values were written through to the datastore cache.Delete(['Domain', domain.name]) other = domains.Domain.Get('MyDomain.com') self.assertEqual(domain.default_label, other.default_label) self.assertEqual( domain.initial_domain_role, other.initial_domain_role) def testNoneDomainRole_Create(self): domains.Domain.Create('foo.bar.org', initial_domain_role=None) domain_model = domains.DomainModel.get_by_key_name('foo.bar.org') self.assertEqual(domains.NO_ROLE, domain_model.initial_domain_role) cache.Delete(['Domain', 'foo.bar.org']) dom2 = domains.Domain.Get('foo.bar.org') self.assertIsNone(dom2.initial_domain_role) def testNoneDomainRole_Set(self): domain = domains.Domain.Create('blah.com') self.assertTrue(domain.initial_domain_role) domain.initial_domain_role = None with test_utils.RootLogin(): domain.Put() domain_model = domains.DomainModel.get_by_key_name('blah.com') self.assertEqual(domains.NO_ROLE, domain_model.initial_domain_role) if __name__ == '__main__': test_utils.main() <file_sep>#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """Model and data object for representing Domains.""" import cache import config import logs import perms from google.appengine.ext import db # Used when initial_domain_role should be None (but AppEngine won't # let us search on that). NO_ROLE = 'NO_ROLE' class UnknownDomainError(Exception): """Returned when asked about to mutate a domain that does not exist.""" def __init__(self, unknown_name): super(UnknownDomainError, self).__init__('No such domain %s' % unknown_name) self.unknown_name = unknown_name class DomainModel(db.Model): """"A domain that has its own catalog of maps, permissions, etc.""" # Value from LabelPolicy, above. has_sticky_catalog_entries = db.BooleanProperty(default=False) # The label of the map to display by default default_label = db.StringProperty() # The domain_role given to new maps created in this domain, and the # role granted to all MAP_CREATORs upon mew map creation initial_domain_role = db.StringProperty() class Domain(object): def __init__(self, domain_model): """Constructor not to be called directly; use Get or New instead.""" for attr in ['has_sticky_catalog_entries', 'default_label', 'initial_domain_role']: setattr(self, attr, getattr(domain_model, attr)) self.name = domain_model.key().name() if self.initial_domain_role == NO_ROLE: self.initial_domain_role = None def _Cache(self): cached = {'has_sticky_catalog_entries': self.has_sticky_catalog_entries, 'default_label': self.default_label, 'initial_domain_role': self.initial_domain_role} cache.Set(['Domain', self.name], cached) @staticmethod def NormalizeDomainName(domain_name): return str(domain_name).lower() @staticmethod def Create(domain_name, has_sticky_catalog_entries=False, default_label='empty', initial_domain_role=perms.Role.MAP_VIEWER, user=None): """Creates and stores a Domain object, overwriting any existing one.""" domain_name = Domain.NormalizeDomainName(domain_name) if not initial_domain_role: initial_domain_role = NO_ROLE domain_model = DomainModel( key_name=domain_name, default_label=default_label, has_sticky_catalog_entries=has_sticky_catalog_entries, initial_domain_role=initial_domain_role) domain_model.put() domain = Domain(domain_model) domain._Cache() # pylint: disable=protected-access logs.RecordEvent(logs.Event.DOMAIN_CREATED, domain_name=domain.name, uid=user.id if user else None) return domain @staticmethod def Get(domain_name): """Gets the domain given its name.""" domain_name = domain_name or config.Get('default_domain') domain_name = Domain.NormalizeDomainName(domain_name) cached = cache.Get(['Domain', domain_name]) if cached: domain_model = DomainModel(key_name=domain_name, **cached) return Domain(domain_model) domain_model = DomainModel.get_by_key_name(domain_name) if not domain_model: return None domain = Domain(domain_model) domain._Cache() # pylint: disable=protected-access return domain def Put(self, user=None): perms.AssertAccess(perms.Role.DOMAIN_ADMIN, self.name, user) domain_model = DomainModel( key_name=self.name, default_label=self.default_label, has_sticky_catalog_entries=self.has_sticky_catalog_entries, initial_domain_role=self.initial_domain_role or NO_ROLE) domain_model.put() self._Cache() <file_sep>#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """An HTTP API for fetching and saving map definitions.""" __author__ = '<EMAIL> (<NAME>)' import json import base_handler import model class MapById(base_handler.BaseHandler): """An HTTP API for fetching and saving map definitions.""" def Get(self, map_id, domain=''): # pylint: disable=unused-argument """Returns the MapRoot JSON for the specified map.""" map_object = model.Map.Get(map_id) if map_object: self.WriteJson({ 'json': json.loads(map_object.GetCurrentJson() or 'null') }) else: self.error(404) self.response.out.write('Map %s not found' % map_id) def Post(self, map_id, domain=''): # pylint: disable=unused-argument """Stores a new version of the MapRoot JSON for the specified map.""" map_object = model.Map.Get(map_id) if map_object: map_object.PutNewVersion(self.request.get('json')) self.response.set_status(201) else: self.error(404) self.response.out.write('Map %s not found' % map_id) class PublishedMaps(base_handler.BaseHandler): """Handler for fetching the JSON of all published maps.""" def Get(self, domain=''): # pylint: disable=unused-argument root = self.request.root_path self.WriteJson([{'url': root + '/%s/%s' % (entry.domain, entry.label), 'maproot': json.loads(entry.maproot_json)} for entry in model.CatalogEntry.GetAll()]) <file_sep>#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """Storage for configuration settings.""" __author__ = '<EMAIL> (<NAME>)' import binascii import json import os import cache from google.appengine.ext import db class Config(db.Model): """A configuration setting. Each configuration setting has a string key and a value that can be anything representable in JSON (string, number, boolean, None, or arbitrarily nested lists or dictionaries thereof). The value is stored internally using JSON. """ value_json = db.TextProperty() # the value, serialized to JSON def Get(key, default=None): """Fetches the configuration value for a given key. Args: key: A string, the name of the configuration item to get. default: An optional default value to return. Returns: The configuration value, or the specified default value if not found. """ def Fetcher(): config = Config.get_by_key_name(key) if config: return json.loads(config.value_json) return default return cache.Get([Config, key], Fetcher) def GetAll(): """Returns a dictionary containing all the configuration values.""" results = {} for config in Config.all(): value = json.loads(config.value_json) cache.Set([Config, config.key().name], value) results[config.key().name()] = value return results def Set(key, value): """Sets a configuration value. Args: key: A string, the name of the configuration item to get. value: Any Python data structure that can be serialized to JSON. """ config = Config(key_name=key, value_json=json.dumps(value)) config.put() cache.Delete([Config, key]) def Delete(key): """Deletes a configuration value.""" Config(key_name=key).delete() cache.Delete([Config, key]) def GetGeneratedKey(key): """Gets a string of 32 hex digits that is randomly generated on first use. The first time this is called, it generates a random string and stores it in a configuration item with the given key; thereafter, the stored string is returned. The result is suitable for use as a cryptographic key (e.g. HMAC key or encryption key): it is generated at runtime, doesn't exist in the source code, and is unique to the application instance. Args: key: A string, the name of the configuration item to use. Returns: A string of 32 hex digits. """ @db.transactional def PutGeneratedKey(): if not Get(key): Set(key, binascii.b2a_hex(os.urandom(16))) value = Get(key) while not value: PutGeneratedKey() value = Get(key) # The retry here handles the rare case in which memcache.get returns None # even after memcache.add. Strange, but we've seen it happen occasionally. # TODO(kpy): Consider factoring out this retry loop if we need it elsewhere. return str(value) # avoid Unicode; it's just hex digits <file_sep>crisismap ========= Create, publish, and share maps by combining layers from anywhere on the web. <file_sep>#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """Tests for api.py.""" __author__ = '<EMAIL> (<NAME>)' import json import model import test_utils class ApiTest(test_utils.BaseTest): """Tests for api class.""" def setUp(self): super(ApiTest, self).setUp() self.map = test_utils.CreateMap( owners=['owner'], editors=['editor'], viewers=['viewer']) def testGetMap(self): """Fetches a map through the API.""" json_dict = {'json': True, 'stuff': [0, 1]} maproot_json = json.dumps(json_dict) with test_utils.Login('editor'): self.map.PutNewVersion(maproot_json) with test_utils.Login('viewer'): response = self.DoGet('/.api/maps/%s' % self.map.id) self.assertEquals({'json': json_dict}, json.loads(response.body)) def testGetInvalidMap(self): """Attempts to fetch a map that doesn't exist.""" self.DoGet('/.api/maps/xyz', 404) def testPostMap(self): """Posts a new version of a map.""" maproot_json = '{"stuff": [0, 1]}' with test_utils.Login('editor'): self.DoPost('/.api/maps/' + self.map.id, 'json=' + maproot_json + '&xsrf_token=XSRF') # Now we refetch the map because the object changed underneath us. with test_utils.Login('viewer'): # Verify that the edited content was saved properly. map_object = model.Map.Get(self.map.id) self.assertEquals(maproot_json, map_object.GetCurrentJson()) def testPublishedMaps(self): map1 = {'title': 'Map 1', 'layers': [{'id': 12, 'type': 'KML', 'source': {'kml': {'url': 'x.com/a.kml'}}}, {'id': 15, 'type': 'GEORSS', 'source': {'georss': {'url': 'y.com/b.xml'}}}]} map2 = {'title': 'Map 2', 'layers': [{'id': 13, 'type': 'KML', 'source': {'kml': {'url': 'a.com/y.kml'}}}, {'id': 17, 'type': 'GEORSS', 'source': {'georss': {'url': 'b.com/x.xml'}}}]} draft = {'title': 'Map 2', 'layers': [{'id': 13, 'type': 'KML', 'source': {'kml': {'url': 'a.com/y.kml'}}}, {'id': 17, 'type': 'GEORSS', 'source': {'georss': {'url': 'b.com/x.xml'}}}]} # Create and publish two maps with test_utils.RootLogin(): m1 = test_utils.CreateMap(json.dumps(map1)) model.CatalogEntry.Create('xyz.com', 'label1', m1) m2 = test_utils.CreateMap(json.dumps(map2)) model.CatalogEntry.Create('xyz.com', 'label2', m2) # Create a draft; should not be returned by api.Maps test_utils.CreateMap(json.dumps(draft)) response = self.DoGet('/.api/maps') self.assertEquals([{'url': '/root/xyz.com/label2', 'maproot': map2}, {'url': '/root/xyz.com/label1', 'maproot': map1}], json.loads(response.body)) if __name__ == '__main__': test_utils.main() <file_sep>#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """Tests for create.py.""" __author__ = '<EMAIL> (<NAME>)' import domains import logs import model import perms import test_utils class CreateTest(test_utils.BaseTest): """Tests for create.py.""" def testCreate(self): perms.Grant('creator', perms.Role.MAP_CREATOR, 'xyz.com') self.CaptureLog() with test_utils.Login('creator'): response = self.DoPost('/xyz.com/.create', 'xsrf_token=XSRF', 302) # Confirm that a map was created. location = response.headers['Location'] map_object = model.Map.Get(location.split('/')[-1]) self.assertTrue('Untitled' in map_object.GetCurrentJson()) self.assertLog(logs.Event.MAP_CREATED, uid='creator', map_id=map_object.id, domain_name='xyz.com') def testCreateWithoutPermission(self): # Without MAP_CREATOR, the user shouldn't be able to create a map. with test_utils.Login('noncreator'): self.DoPost('/xyz.com/.create', 'xsrf_token=XSRF', 403) def testDomainRole(self): # Start with initial_domain_role == None for our domain with test_utils.RootLogin(): domain = domains.Domain.Get('xyz.com') domain.initial_domain_role = None domain.Put() perms.Grant('creator', perms.Role.MAP_CREATOR, 'xyz.com') with test_utils.Login('creator'): response = self.DoPost('/xyz.com/.create', 'xsrf_token=<PASSWORD>', 302) location = response.headers['Location'] # initial_domain_role is unset so domain_role should be None. map_object = model.Map.Get(location.split('/')[-1]) self.assertTrue(map_object is not None) # With no initial_domain_role set, domain_role should be None. self.assertEquals(['xyz.com'], map_object.domains) self.assertEquals(None, map_object.domain_role) # Now set the initial_domain_role for xyz.com. with test_utils.RootLogin(): domain.initial_domain_role = perms.Role.MAP_EDITOR domain.Put() # Create another map. with test_utils.Login('creator'): response = self.DoPost('/.create?domain=xyz.com', 'xsrf_token=<PASSWORD>', 302) location = response.headers['Location'] # Check the map; initial_domain_role is set so domain_role should be set. map_object = model.Map.Get(location.split('/')[-1]) self.assertTrue(map_object is not None) self.assertEquals(['xyz.com'], map_object.domains) self.assertEquals(perms.Role.MAP_EDITOR, map_object.domain_role) if __name__ == '__main__': test_utils.main() <file_sep>#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """Tests for base_handler.py.""" __author__ = '<EMAIL> (<NAME>)' import base_handler import test_utils class BaseHandlerTest(test_utils.BaseTest): """Tests for base_handler.py.""" def testSelectLanguage(self): """Tests the selection of the UI language.""" self.assertEquals('en', base_handler.SelectLanguage(None, None)) # "ja" is a supported language. self.assertEquals('ja', base_handler.SelectLanguage('ja', None)) self.assertEquals('ja', base_handler.SelectLanguage(None, 'ja')) # "zz" is not a supported language. self.assertEquals('en', base_handler.SelectLanguage('zz', None)) # "in" is a deprecated code for Indonesian; the proper code is "id". self.assertEquals('id', base_handler.SelectLanguage('in', None)) # The first parameter takes precedence over the second. self.assertEquals('tr', base_handler.SelectLanguage('tr', 'th')) # Can handle variable number of args, and chooses the first valid one. self.assertEquals('de', base_handler.SelectLanguage( 'xoxo', None, 'de', 'fr')) # Each argument can actually be a comma-separated list of codes. self.assertEquals('de', base_handler.SelectLanguage( 'xoxo,oxox', None, 'yoyo,oyoy,de', 'fr')) def testJsonXssVulnerability(self): """Verifies that ToHtmlSafeJson is safe against XSS.""" self.assertFalse('</script>' in base_handler.ToHtmlSafeJson('x</script>y')) self.assertFalse('<' in base_handler.ToHtmlSafeJson('x<y')) self.assertFalse('>' in base_handler.ToHtmlSafeJson('x>y')) self.assertFalse('&' in base_handler.ToHtmlSafeJson('x&y')) def testSanitizeCallback(self): """Verifies that SanitizeCallback protects against XSS.""" self.assertRaises(base_handler.Error, base_handler.SanitizeCallback, '') self.assertRaises(base_handler.Error, base_handler.SanitizeCallback, '.') self.assertRaises(base_handler.Error, base_handler.SanitizeCallback, 'abc"') self.assertRaises(base_handler.Error, base_handler.SanitizeCallback, "abc'") self.assertRaises(base_handler.Error, base_handler.SanitizeCallback, 'abc;') self.assertRaises(base_handler.Error, base_handler.SanitizeCallback, '<b>') self.assertRaises(base_handler.Error, base_handler.SanitizeCallback, '1') self.assertRaises(base_handler.Error, base_handler.SanitizeCallback, '1abc') self.assertRaises(base_handler.Error, base_handler.SanitizeCallback, 'x.2') self.assertEquals('abc', base_handler.SanitizeCallback('abc')) self.assertEquals('_def', base_handler.SanitizeCallback('_def')) self.assertEquals('FooBar3', base_handler.SanitizeCallback('FooBar3')) self.assertEquals('x.y', base_handler.SanitizeCallback('x.y')) self.assertEquals('x.y._z', base_handler.SanitizeCallback('x.y._z')) if __name__ == '__main__': test_utils.main() <file_sep>#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """Handler for the domain-specific admin page.""" __author__ = '<EMAIL> (<NAME>)' import base_handler import domains import model import perms import users import utils # String used to mean "none of the above" in the HTML NO_PERMISSIONS = 'NO_PERMISSIONS' INITIAL_DOMAIN_ROLE_CHOICES = ( (NO_PERMISSIONS, 'Have no access to the map'), (perms.Role.MAP_VIEWER, 'Can view the map'), (perms.Role.MAP_EDITOR, 'Can view and edit the map'), (perms.Role.MAP_OWNER, 'Can view, edit, and delete the map'), ) DOMAIN_PERMISSION_CHOICES = ( (perms.Role.MAP_CREATOR, 'Can create maps'), (perms.Role.CATALOG_EDITOR, 'Can publish maps'), (perms.Role.DOMAIN_ADMIN, 'Can manage domain'), ) # _MaxRole relies on these being in order from weakest to strongest. DOMAIN_PERMISSIONS = [s for s, _ in reversed(DOMAIN_PERMISSION_CHOICES)] # TODO(rew): This goes away once we migrate the perms data to store only the # strongest permsision per subject def _MaxRole(roles): for role in DOMAIN_PERMISSIONS: if role in roles: return role def SetRolesForDomain(subject_roles, domain_name): """Gives each user exactly the specified set of roles to the given domain. Args: subject_roles: A dictionary mapping subjects (user IDs or domain names) to sets of perms.Role constants. For each subject, all roles in the set will be granted, and all roles not in the set will be revoked. domain_name: A domain name. """ old_subject_roles = perms.GetSubjectsForTarget(domain_name) for subject, new_roles in subject_roles.items(): old_roles = old_subject_roles.get(subject, set()) for role in old_roles - new_roles: perms.Revoke(subject, role, domain_name) for role in new_roles - old_roles: perms.Grant(subject, role, domain_name) class Admin(base_handler.BaseHandler): """Handler for the overall admin and domain-specific admin pages.""" def Get(self, user, domain=''): """Routes to a general admin, domain admin, or map admin page.""" if self.request.get('map'): map_id = self.request.get('map').split('/')[-1] return self.redirect(str(self.request.root_path + '/.admin/%s' % map_id)) if domain: self.GetDomainAdmin(user, domain) else: self.GetGeneralAdmin() # "user" is currently unused, but we must have a user (tacitly used in # AssertAccess) and we cannot rename the arg. def GetDomainAdmin(self, user, domain): # pylint:disable=unused-argument """Displays the administration page for the given domain.""" domain_name = domain perms.AssertAccess(perms.Role.DOMAIN_ADMIN, domain_name) domain = domains.Domain.Get(domain_name) if not domain: raise base_handler.Error(404, 'Unknown domain %r.' % domain_name) subject_roles = perms.GetSubjectsForTarget(domain_name) user_roles = [(users.Get(subj), _MaxRole(r)) for (subj, r) in subject_roles.items() if perms.IsUserId(subj)] user_roles.sort(key=lambda (u, r): u.email) labels = sorted(e.label for e in model.CatalogEntry.GetAll(domain_name)) self.response.out.write(self.RenderTemplate('admin_domain.html', { 'domain': domain, 'user_roles': user_roles, 'labels': labels, 'domain_role': _MaxRole(subject_roles.get(domain_name, set())), 'user_permission_choices': DOMAIN_PERMISSION_CHOICES, 'initial_domain_role_choices': INITIAL_DOMAIN_ROLE_CHOICES, 'show_welcome': self.request.get('welcome', '') })) def GetGeneralAdmin(self): """Renders the general admin page.""" perms.AssertAccess(perms.Role.ADMIN) self.response.out.write(self.RenderTemplate('admin.html', {})) # TODO(kpy): Also show a list of existing domains on this page? def Post(self, user, domain): """Landing for posts from the domain administration page.""" which = self.request.POST.pop('form') target = self.request.path if which != 'create-domain': perms.AssertAccess(perms.Role.DOMAIN_ADMIN, domain, user) if not domains.Domain.Get(domain): raise base_handler.Error(404, 'Unknown domain %r.' % domain) if which == 'domain-settings': self.UpdateDomainSettings(self.request.POST, domain) elif which == 'create-domain': self.CreateDomain(domain, user) target += '?welcome=1' else: # user or domain permissions inputs = dict(self.request.POST) self.AddNewUserIfPresent(inputs, domain) self.UpdateDomainRole(inputs, domain) SetRolesForDomain(self.FindNewPerms(inputs), domain) self.redirect(target) def UpdateDomainSettings(self, inputs, domain_name): domain = domains.Domain.Get(domain_name) domain.default_label = inputs.get('default_label', 'empty') domain.has_sticky_catalog_entries = 'has_sticky_catalog_entries' in inputs domain.initial_domain_role = inputs.get( 'initial_domain_role', perms.Role.MAP_VIEWER) if domain.initial_domain_role == NO_PERMISSIONS: domain.initial_domain_role = None domain.Put() def AddNewUserIfPresent(self, inputs, domain): """Grants domain roles to a new user.""" new_email = inputs.pop('new_user').strip() new_role = inputs.pop('new_user.permission') if not new_email or not new_role: return if not utils.IsValidEmail(new_email): raise base_handler.Error(400, 'Invalid e-mail address: %r.' % new_email) user = users.GetForEmail(new_email) perms.Grant(user.id, new_role, domain) def UpdateDomainRole(self, inputs, domain_name): # TODO(rew): Simplify this once perms have been migrated to one # role per (subject, target). new_role = inputs.pop('domain_role') new_role = set() if new_role == NO_PERMISSIONS else {new_role} SetRolesForDomain({domain_name: new_role}, domain_name) def FindNewPerms(self, inputs): """Looks at inputs and determines the new permissions for all users. Args: inputs: a dictionary of the form inputs Returns: A dictionary keyed by user/domain. Values are sets of the roles that the key should have. """ new_perms = {} for key in inputs: if '.' in key: uid, input_name = key.rsplit('.', 1) if input_name == 'permission' and uid + '.delete' not in inputs: new_perms[uid] = {inputs[key]} elif input_name == 'delete': new_perms[uid] = set() return new_perms def CreateDomain(self, domain_name, user): def GrantPerms(): perms.Grant(user.id, perms.Role.DOMAIN_ADMIN, domain_name) perms.Grant(user.id, perms.Role.CATALOG_EDITOR, domain_name) perms.Grant(user.id, perms.Role.MAP_CREATOR, domain_name) def TestPerms(): return perms.CheckAccess(perms.Role.DOMAIN_ADMIN, domain_name, user) domain = domains.Domain.Get(domain_name) if domain: raise base_handler.Error(403, 'Domain %r already exists.' % domain_name) utils.SetAndTest(GrantPerms, TestPerms) domains.Domain.Create(domain_name) class AdminMap(base_handler.BaseHandler): """Administration page for a map.""" def Get(self, map_id): """Renders the admin page.""" perms.AssertAccess(perms.Role.ADMIN) map_object = model.Map.Get(map_id) or model.Map.GetDeleted(map_id) if not map_object: raise base_handler.Error(404, 'Map %r not found.' % map_id) self.response.out.write(self.RenderTemplate('admin_map.html', { 'map': map_object })) def Post(self, map_id): """Handles a POST (block/unblock, delete/undelete, or wipe).""" perms.AssertAccess(perms.Role.ADMIN) map_object = model.Map.Get(map_id) or model.Map.GetDeleted(map_id) if not map_object: raise base_handler.Error(404, 'Map %r not found.' % map_id) if self.request.get('block'): map_object.SetBlocked(True) if self.request.get('unblock'): map_object.SetBlocked(False) if self.request.get('delete'): map_object.Delete() if self.request.get('undelete'): map_object.Undelete() if self.request.get('wipe'): map_object.Wipe() self.redirect(map_id) <file_sep>#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """Unit tests for cache.py.""" __author__ = '<EMAIL> (<NAME>)' import cache import test_utils class CacheTests(test_utils.BaseTest): """Tests the memcache utility routines.""" def testToCacheKey(self): """Tests that cache keys are properly serialized and escaped.""" self.assertEquals('foo', cache.ToCacheKey(['foo'])) self.assertEquals('foo,bar', cache.ToCacheKey(['foo', 'bar'])) self.assertEquals('foo\\,,bar', cache.ToCacheKey(['foo,', 'bar'])) self.assertEquals('f\\\\\\\\oo\\,\\,,\\\\b\\,ar', cache.ToCacheKey(['f\\\\oo,,', '\\b,ar'])) if __name__ == '__main__': test_utils.main() <file_sep>#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """A base class providing common functionality for request handlers.""" __author__ = '<EMAIL> (<NAME>)' import hmac import httplib import inspect import json import logging import os import re import time import webapp2 import config import domains import perms import users import utils # pylint: disable=g-import-not-at-top try: import languages except ImportError: languages = utils.Struct(ALL_LANGUAGES=['en']) from google.appengine.ext.webapp import template # A mapping from deprecated ISO language codes to valid ones. CANONICAL_LANGS = {'he': 'iw', 'in': 'id', 'mo': 'ro', 'jw': 'jv', 'ji': 'yi'} def NormalizeLang(lang): """Normalizes a language code to conventional BCP 47 form, e.g. "en-CA".""" language, region = (lang.strip().replace('_', '-').split('-') + [''])[:2] language, region = language.lower(), region.upper() return CANONICAL_LANGS.get(language, language) + (region and '-' + region) DEFAULT_LANGUAGE = 'en' ALL_LANGUAGES = map(NormalizeLang, languages.ALL_LANGUAGES) def SelectSupportedLanguage(language_codes): """Selects a supported language based on a list of preferred languages. Checks through the user-supplied list of languages, and picks the first one that we support. If none are supported, returns None. Args: language_codes: A string, a comma-separated list of BCP 47 language codes. Returns: The BCP 47 language code of a supported UI language or None. """ for lang in map(NormalizeLang, language_codes.split(',')): if lang in ALL_LANGUAGES: return lang first = lang.split('-')[0] if first in ALL_LANGUAGES: return first return None def SelectLanguage(*langs): """Determines the UI language to use. This function expects a variable-length parameter list, each of which is either a language code or a comma-separated list of language codes. After flattening the list, this returns the first valid language encountered, so the caller should supply the language parameters in order of decreasing priority. Args: *langs: A variable length list of language codes, or comma-separated lists of language codes (some or all may be None). Returns: A language code indicating the UI language to use. Defaults to DEFAULT_LANGUAGE if all parameters are invalid codes or None. """ for lang in langs: if lang: supported_lang = SelectSupportedLanguage(lang) if supported_lang: return supported_lang # All arguments were None or invalid. return DEFAULT_LANGUAGE def ToHtmlSafeJson(data, **kwargs): """Serializes a JSON data structure to JSON that is safe for use in HTML.""" return json.dumps(data, **kwargs).replace( '&', '\\u0026').replace('<', '\\u003c').replace('>', '\\u003e') def GenerateXsrfToken(uid, timestamp=None): """Generates a timestamped XSRF-prevention token scoped to the given uid.""" timestamp = str(timestamp or int(time.time())) hmac_key = config.GetGeneratedKey('xsrf_key') return timestamp + ':' + hmac.new(hmac_key, timestamp + ':' + uid).hexdigest() def ValidateXsrfToken(uid, token): """Returns True if an XSRF token is valid for uid and at most 4 hours old.""" timestamp = token.split(':')[0] return (timestamp and time.time() < int(timestamp) + 4*3600 and token == GenerateXsrfToken(uid, timestamp)) def SanitizeCallback(callback): """Checks and returns a safe JSONP callback name, or raises an error. Args: callback: A JavaScript callback function name. Returns: The callback name, only if it is a valid JavaScript identifier optionally preceded by other identifiers with dots (e.g. "object1.child2.name3"). Raises: Error: If the callback name was invalid. """ if re.match(r'^([a-zA-Z_]\w*\.)*[a-zA-Z_]\w*$', callback): return callback raise Error(httplib.BAD_REQUEST, 'Invalid callback name.') class Error(Exception): """An error that carries an HTTP status and a message to show the user.""" def __init__(self, status, message): Exception.__init__(self, message) self.status = status class BaseHandler(webapp2.RequestHandler): """Base class for request handlers. Subclasses should define methods named 'Get' and/or 'Post'. - If the method has a required (or optional) argument named 'domain', then a domain is required (or permitted) in the path or in a 'domain' query parameter (see main.OptionalDomainRoute), and the domain will be passed in as that argument. - If the method has a required (or optional) argument named 'user', then user sign-in is required (or optional) for that handler, and the User object will be passed in as that argument. - Other arguments to the method should appear in <angle_brackets> in the corresponding route's path pattern (see the routing table in main.py). """ # These are used in RenderTemplate, so ensure they always exist. xsrf_token = '' xsrf_tag = '' def HandleRequest(self, **kwargs): """A wrapper around the Get or Post method defined in the handler class.""" try: method = getattr(self, self.request.method.capitalize(), None) if not method: raise Error(405, '%s method not allowed.' % self.request.method) root_path = config.Get('root_path') or '' user = users.GetCurrent() # Require/allow domain name and user sign-in based on whether the method # takes arguments named 'domain' and 'user'. args, _, _, defaults = inspect.getargspec(method) required_args = args[:len(args) - len(defaults or [])] if 'domain' in kwargs and 'domain' not in args: raise Error(404, 'Not found.') if 'domain' in required_args and 'domain' not in kwargs: raise Error(400, 'Domain not specified.') if 'user' in args: kwargs['user'] = user if 'user' in required_args and not user: return self.redirect(users.GetLoginUrl(self.request.url)) # Prepare an XSRF token if the user is signed in. if user: self.xsrf_token = GenerateXsrfToken(user.id) self.xsrf_tag = ('<input type="hidden" name="xsrf_token" value="%s">' % self.xsrf_token) # Require a valid XSRF token for all authenticated POST requests. if user and method.__name__ == 'Post': xsrf_token = self.request.get('xsrf_token', '') if not ValidateXsrfToken(user.id, xsrf_token): logging.warn('Bad xsrf_token %r for uid %r', xsrf_token, user.id) # The window might have been idle for a day; go somewhere reasonable. return self.redirect(root_path + '/.maps') # Fill in some useful request variables. self.request.lang = SelectLanguage( self.request.get('hl'), self.request.headers.get('accept-language')) self.request.root_path = root_path # Call the handler, making nice pages for errors derived from Error. method(**kwargs) except perms.AuthorizationError as exception: self.response.set_status(403, message=exception.message) self.response.out.write(self.RenderTemplate('unauthorized.html', { 'exception': exception, 'login_url': users.GetLoginUrl(self.request.url) })) except perms.NotPublishableError as exception: self.response.set_status(403, message=exception.message) self.response.out.write(self.RenderTemplate('error.html', { 'exception': exception })) except perms.NotCatalogEntryOwnerError as exception: # TODO(kpy): Either add a template for this type of error, or use an # error representation that can be handled by one common error template. self.response.set_status(403, message=exception.message) self.response.out.write(self.RenderTemplate('error.html', { 'exception': utils.Struct( message='That publication label is owned ' 'by someone else; you can\'t replace or delete it.') })) except Error as exception: self.response.set_status(exception.status, message=exception.message) self.response.out.write(self.RenderTemplate('error.html', { 'exception': exception })) get = HandleRequest post = HandleRequest def RenderTemplate(self, template_name, context): """Renders a template from the templates/ directory. Args: template_name: A string, the filename of the template to render. context: An optional dictionary of template variables. A few variables are automatically added to this context: - {{root}} is the root_path of the app - {{user}} is the signed-in user - {{login_url}} is a URL to a sign-in page - {{logout_url}} is a URL that signs the user out - {{navbar}} contains variables used by the navigation sidebar Returns: A string, the rendered template. """ path = os.path.join(os.path.dirname(__file__), 'templates', template_name) root = config.Get('root_path') or '' user = users.GetCurrent() context = dict(context, root=root, user=user, xsrf_tag=self.xsrf_tag, login_url=users.GetLoginUrl(self.request.url), logout_url=users.GetLogoutUrl(root + '/.maps'), navbar=self._GetNavbarContext(user)) return template.render(path, context) def WriteJson(self, data): """Writes out a JSON or JSONP serialization of the given data.""" callback = self.request.get('callback', '') output = ToHtmlSafeJson(data) if callback: # emit a JavaScript expression with a callback function self.response.headers['Content-Type'] = 'application/javascript' self.response.out.write(SanitizeCallback(callback) + '(' + output + ')') else: # just emit the JSON literal self.response.headers['Content-Type'] = 'application/json' self.response.out.write(output) def _GetNavbarContext(self, user): get_domains = lambda role: sorted(perms.GetAccessibleDomains(user, role)) return user and { 'admin_domains': get_domains(perms.Role.DOMAIN_ADMIN), 'catalog_domains': get_domains(perms.Role.CATALOG_EDITOR), 'creator_domains': get_domains(perms.Role.MAP_CREATOR), 'domain_exists': domains.Domain.Get(user.email_domain), 'is_admin': perms.CheckAccess(perms.Role.ADMIN) } or {} <file_sep>#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """Utilites common to multiple tests.""" __author__ = '<EMAIL> (<NAME>)' import base64 import datetime import os import time import unittest import urllib import urlparse import webapp2 import webob import base_handler import config import domains import logs import model import mox import perms import users from google.appengine.api import taskqueue from google.appengine.ext import testbed # mox.IgnoreArg() is such a horrible way to spell "I don't care". mox.ANY = mox.IgnoreArg() # For tests, assume the app resides under this URL. ROOT_URL = 'http://app.com/root' ROOT_PATH = urlparse.urlsplit(ROOT_URL).path DEFAULT_DOMAIN = 'xyz.com' def DispatchRequest(request): response = webapp2.Response() # Can't import app at the top of this file because testbed isn't ready yet. import app # pylint: disable=g-import-not-at-top app.app.router.dispatch(request, response) return response def SetupRequest(path, lang='en'): """Sets up a webapp2.Request object for testing.""" request = webapp2.Request(webob.Request.blank(ROOT_URL + path).environ) request.root_path = ROOT_PATH request.lang = lang return request class LoginContext(object): """A context manager that sets and restores the user login for testing.""" def __init__(self, uid, ga_domain, email): self.login_info = uid, ga_domain, email self.user = users.User(id=uid, ga_domain=ga_domain, email=email) def __enter__(self): self.original = users._GetLoginInfo users._GetLoginInfo = lambda: self.login_info return self.user def __exit__(self, etype, evalue, etb): users._GetLoginInfo = self.original def Login(uid): """Context manager: signs in a non-Google-Apps user.""" return LoginContext(uid, '', uid + '@gmail.test') def DomainLogin(uid, domain): """Context manager: signs in a Google Apps user.""" return LoginContext(uid, domain, uid + '@' + domain) def RootLogin(): """Context manager: signs in as user 'root', which always has ADMIN access.""" return LoginContext(perms.ROOT.id, '', '<EMAIL>') def SetupUser(context): """Ensures that the User for a login context exists in the datastore.""" with context: return users.GetCurrent() # implicitly updates the datastore def SetupHandler(url, handler, post_data=None): """Sets up a RequestHandler object for testing.""" request = webapp2.Request(webob.Request.blank(url).environ) response = webapp2.Response() if post_data is not None: request.method = 'POST' request.body = post_data request.headers['Content-Type'] = 'application/x-www-form-urlencoded' handler.initialize(request, response) return handler def DatetimeWithUtcnow(now): """Creates a replacement for datetime.datetime with a stub for utcnow().""" # datetime.datetime is a built-in type, so we can't reassign its 'utcnow' # member; we have to subclass datetime.datetime instead. The App Engine # SDK randomly uses both utcnow() and now(), so we have to patch both. :/ return type('datetime.datetime', (datetime.datetime,), {'utcnow': staticmethod(lambda: now), 'now': staticmethod(lambda: now), # The line below makes utcfromtimestamp return datetime.datetime # instances instead of test_utils.datetime.datetime instances. 'utcfromtimestamp': datetime.datetime.utcfromtimestamp}) def CreateMap(maproot_json='{"title": "Foo"}', domain=DEFAULT_DOMAIN, **kwargs): with RootLogin(): return model.Map.Create(maproot_json, domain, **kwargs) class BaseTest(unittest.TestCase): """Base Tests for appengine classes.""" def setUp(self): self.mox = mox.Mox() self.testbed = testbed.Testbed() self.testbed.activate() root = os.path.dirname(__file__) or '.' self.testbed.init_datastore_v3_stub(require_indexes=True, root_path=root) self.testbed.init_memcache_stub() self.testbed.init_taskqueue_stub(root_path=root) self.testbed.init_urlfetch_stub() self.testbed.init_user_stub() self.original_datetime = datetime.datetime os.environ.pop('USER_EMAIL', None) os.environ.pop('USER_ID', None) os.environ.pop('USER_IS_ADMIN', None) os.environ.pop('USER_ORGANIZATION', None) config.Set('root_path', ROOT_PATH) config.Set('default_domain', DEFAULT_DOMAIN) domains.Domain.Create(DEFAULT_DOMAIN) self.mox.stubs.Set( base_handler, 'GenerateXsrfToken', lambda uid, timestamp=None: 'XSRF') self.mox.stubs.Set( base_handler, 'ValidateXsrfToken', lambda uid, token: token == 'XSRF') def tearDown(self): self.mox.UnsetStubs() self.testbed.deactivate() def DoGet(self, path, status=None): """Dispatches a GET request according to the routes in app.py. Args: path: The part of the URL path after (not including) the root URL. status: If given, expect that the GET will give this HTTP status code. Otherwise, expect that the GET will give a non-error code (200-399). Returns: The HTTP response from the handler as a webapp2.Response object. """ response = DispatchRequest(SetupRequest(path)) if status: self.assertEquals(status, response.status_int) else: self.assertGreaterEqual(response.status_int, 200) self.assertLess(response.status_int, 400) return response def DoPost(self, path, data, status=None): """Dispatches a POST request according to the routes in app.py. Args: path: The part of the URL path after (not including) the root URL. data: The POST data as a string, dictionary, or list of pairs. status: If given, expect that the POST will return this HTTP status code. Otherwise, expect that the POST will return a non-error code (< 400). Returns: The HTTP response from the handler as a webapp2.Response object. """ request = SetupRequest(path) request.method = 'POST' if isinstance(data, dict): request.body = urllib.urlencode(data) else: request.body = str(data) request.headers['Content-Type'] = 'application/x-www-form-urlencoded' response = DispatchRequest(request) if status: self.assertEquals(status, response.status_int) else: self.assertLess(response.status_int, 400) return response def PopTasks(self, queue_name): """Removes all the tasks from a given queue, returning a list of dicts.""" stub = self.testbed.get_stub('taskqueue') tasks = stub.GetTasks(queue_name) stub.FlushQueue(queue_name) return tasks def GetTaskBody(self, task): """Gets the content of the POST data for a task as a string.""" return base64.b64decode(task['body']) def GetTaskParams(self, task): """Gets the POST parameters for a task as a list of (key, value) pairs.""" return urlparse.parse_qsl(self.GetTaskBody(task)) def ExecuteTask(self, task): """Executes a task from popTasks, using a given handler.""" self.assertEquals(ROOT_PATH, task['url'][:len(ROOT_PATH)]) path = task['url'][len(ROOT_PATH):] if task['method'] == 'POST': return self.DoPost(path, self.GetTaskBody(task)) return self.DoGet(path) def SetForTest(self, parent, child_name, new_child): """Sets an attribute of an object, just for the duration of the test.""" self.mox.stubs.Set(parent, child_name, new_child) def SetTime(self, timestamp): """Sets a fake value for the current time, for the duration of the test.""" self.SetForTest(time, 'time', lambda: timestamp) now = self.original_datetime.utcfromtimestamp(timestamp) self.SetForTest(datetime, 'datetime', DatetimeWithUtcnow(now)) # Task.__determine_eta_posix uses the original time.time as a default # argument value, so we have to monkey-patch it to make it use our fake. determine_eta_posix = taskqueue.Task._Task__determine_eta_posix def FakeDetermineEtaPosix(eta=None, countdown=None, current_time=time.time): return determine_eta_posix(eta, countdown, current_time) self.SetForTest(taskqueue.Task, '_Task__determine_eta_posix', staticmethod(FakeDetermineEtaPosix)) return now def assertBetween(self, low, high, actual): """Checks that a value is within a desired range.""" self.assertGreaterEqual(actual, low) self.assertLessEqual(actual, high) def assertEqualsUrlWithUnorderedParams(self, expected, actual): """Checks for an expected URL, ignoring the order of query params.""" e_scheme, e_host, e_path, e_query, e_frag = urlparse.urlsplit(expected) a_scheme, a_host, a_path, a_query, a_frag = urlparse.urlsplit(actual) self.assertEquals( (e_scheme, e_host, e_path, sorted(urlparse.parse_qsl(e_query)), e_frag), (a_scheme, a_host, a_path, sorted(urlparse.parse_qsl(a_query)), a_frag)) def MockRecordEvent(self, event, **kwargs): self.logs.append(dict(event=event, **kwargs)) def CaptureLog(self): self.mox.stubs.Set(logs, 'RecordEvent', self.MockRecordEvent) self.logs = [] def assertLog(self, event, **kwargs): expected_items = dict(event=event, **kwargs).items() matches = [log_dict for log_dict in self.logs if set(log_dict.items()).issuperset(expected_items)] self.assertTrue(matches, 'No matching logs found.') self.assertEqual(1, len(matches), 'Multiple matching logs found.') return matches[0] def main(): unittest.main() <file_sep>#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """Utilities used throughout crisismap.""" from HTMLParser import HTMLParseError from HTMLParser import HTMLParser import re import time class Struct(object): """A simple bag of attributes.""" def __init__(self, **kwargs): self.__dict__.update(kwargs) def __iter__(self): return iter(self.__dict__) def __setattr__(self, name, value): raise TypeError('%r has read-only attributes' % self) @classmethod def FromModel(cls, model): """Populates a new Struct from an ndb.Model (doesn't take a db.Model).""" # ._properties is actually a public API; it's just named with "_" in order # to avoid collision with property names (see http://goo.gl/xAcU4). properties = model._properties # pylint: disable=protected-access return cls(id=model.key.id(), **dict((name, getattr(model, name)) for name in properties)) def StructFromModel(model): """Copies the properties of the given db.Model into a Struct. Note that we use Property.get_value_for_datastore to prevent fetching of referenced objects into the Struct. The other effect of using get_value_for_datastore is that all date/time methods return datetime.datetime values. Args: model: A db.Model entity, or None. Returns: A Struct containing the properties of the given db.Model, with additional 'key', 'name', and 'id' properties for the entity's key(), key().name(), and key().id(). Returns None if 'model' is None. """ if model: return Struct(key=model.key(), id=model.key().id(), name=model.key().name(), **dict((name, prop.get_value_for_datastore(model)) for (name, prop) in model.properties().iteritems())) def ResultIterator(query): """Returns a generator that yields Struct objects.""" for result in query: yield StructFromModel(result) def SetAndTest(set_func, test_func, sleep_delta=0.05, num_tries=20): """Calls set_func, then waits until test_func passes before returning. Sometimes we need to be able to see changes to the datastore immediately and are willing to accept a small latency for that. This function calls set_func (which presumably makes a small change to the datastore), then calls test_func in a while not test_func(): sleep() loop until either test_func passes or the maximum number of tries has been reached. Args: set_func: a function that sets some state in an AppEngine Entity test_func: a function that returns true when the change made by set_func is now visible sleep_delta: (defaults to 0.05) the number of seconds to sleep between calls to test_func, or None to not sleep. num_tries: (defaults to 20) the number of times to try test_func before giving up Returns: True if test_func eventually returned true; False otherwise. """ set_func() for _ in range(num_tries): if test_func(): return True if sleep_delta: time.sleep(sleep_delta) return False def IsValidEmail(email): return re.match(r'^[^@]+@([\w-]+\.)+[\w-]+$', email) class HtmlStripper(HTMLParser): """Helper class for StripHtmlTags.""" def __init__(self): HTMLParser.__init__(self) self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def handle_entityref(self, name): self.fed.append('&%s;' % name) def handle_charref(self, name): self.fed.append('&#%s;' % name) def GetData(self): return ''.join(self.fed) def StripHtmlTags(value): """Returns the given HTML with all tags stripped.""" s = HtmlStripper() try: s.feed(value) s.close() except HTMLParseError: return value else: return s.GetData() <file_sep>goog.require('cm'); goog.provide('cm.css'); /** @const */ cm.css.ABOUT_TEXT = goog.getCssName('cm-about-text'); /** @const */ cm.css.ABOVE_ATTRIBUTION = goog.getCssName('cm-above-attribution'); /** @const */ cm.css.ACTIVE_DRAGGABLE_LAYER = goog.getCssName('cm-active-draggable-layer'); /** @const */ cm.css.ARRANGER = goog.getCssName('cm-arranger'); /** @const */ cm.css.ARRANGER_INNER = goog.getCssName('cm-arranger-inner'); /** @const */ cm.css.BOX_SIZE_LABEL = goog.getCssName('cm-box-size-label'); /** @const */ cm.css.BUILD_INFO = goog.getCssName('cm-build-info'); /** @const */ cm.css.BUTTON = goog.getCssName('cm-button'); /** @const */ cm.css.BUTTON_AREA = goog.getCssName('cm-button-area'); /** @const */ cm.css.CHECKBOX_CONTAINER = goog.getCssName('cm-checkbox-container'); /** @const */ cm.css.CHECKBOX_FOLDER_DECORATION = goog.getCssName('cm-checkbox-folder-decoration'); /** @const */ cm.css.CHEVRON_DOWN = goog.getCssName('cm-chevron-down'); /** @const */ cm.css.CHEVRON_UP = goog.getCssName('cm-chevron-up'); /** @const */ cm.css.CLOSE_BUTTON = goog.getCssName('cm-close-button'); /** @const */ cm.css.COLLAPSE = goog.getCssName('cm-collapse'); /** @const */ cm.css.COLLAPSE_ICON = goog.getCssName('cm-collapse-icon'); /** @const */ cm.css.COLOR_PALETTE = goog.getCssName('cm-color-palette'); /** @const */ cm.css.CONTAINS_PROMOTED_SUBLAYER = goog.getCssName('cm-contains-promoted-sublayer'); /** @const */ cm.css.CONTENT = goog.getCssName('cm-content'); /** @const */ cm.css.COPY_VIEWPORT = goog.getCssName('cm-copy-viewport'); /** @const */ cm.css.DIFF = goog.getCssName('cm-diff'); /** @const */ cm.css.DISABLED = goog.getCssName('cm-disabled'); /** @const */ cm.css.DISCLOSURE = goog.getCssName('cm-disclosure'); /** @const */ cm.css.DRAFT_INDICATOR = goog.getCssName('cm-draft-indicator'); /** @const */ cm.css.DRAGGABLE_FOLDER_BG = goog.getCssName('cm-draggable-folder-bg'); /** @const */ cm.css.DRAGGABLE_LAYER = goog.getCssName('cm-draggable-layer'); /** @const */ cm.css.DRAGGABLE_LAYER_BG = goog.getCssName('cm-draggable-layer-bg'); /** @const */ cm.css.DRAGGABLE_LAYER_TITLE = goog.getCssName('cm-draggable-layer-title'); /** @const */ cm.css.DRAGGABLE_SUBLAYER_CONTAINER = goog.getCssName('cm-draggable-sublayer-container'); /** @const */ cm.css.DRAGGED_CLONE = goog.getCssName('cm-dragged-clone'); /** @const */ cm.css.DRAGGED_CLONER = goog.getCssName('cm-dragged-cloner'); /** @const */ cm.css.DROP_TARGET_LINE = goog.getCssName('cm-drop-target-line'); /** @const */ cm.css.EAST = goog.getCssName('cm-east'); /** @const */ cm.css.EDIT = goog.getCssName('cm-edit'); /** @const */ cm.css.EDITORS = goog.getCssName('cm-editors'); /** @const */ cm.css.EDITORS_TOOLTIP = goog.getCssName('cm-editors-tooltip'); /** @const */ cm.css.EDIT_TOOLBAR = goog.getCssName('cm-edit-toolbar'); /** @const */ cm.css.EMAIL_ERROR = goog.getCssName('cm-email-error'); /** @const */ cm.css.EMBEDDED = goog.getCssName('cm-embedded'); /** @const */ cm.css.EMPTY = goog.getCssName('cm-empty'); /** @const */ cm.css.ERROR = goog.getCssName('cm-error'); /** @const */ cm.css.EXPAND = goog.getCssName('cm-expand'); /** @const */ cm.css.EXPANDED = goog.getCssName('cm-expanded'); /** @const */ cm.css.EXPAND_ICON = goog.getCssName('cm-expand-icon'); /** @const */ cm.css.EXTENTS = goog.getCssName('cm-extents'); /** @const */ cm.css.FACEBOOK_LIKE_BUTTON = goog.getCssName('cm-facebook-like-button'); /** @const */ cm.css.FEATURE_PALETTE = goog.getCssName('cm-feature-palette'); /** @const */ cm.css.FOLDER_CONTAINER = goog.getCssName('cm-folder-container'); /** @const */ cm.css.FOOTER = goog.getCssName('cm-footer'); /** @const */ cm.css.FRAME = goog.getCssName('cm-frame'); /** @const */ cm.css.GPLUS_IMG = goog.getCssName('cm-gplus-img'); /** @const */ cm.css.GPLUS_SHARE_BUTTON = goog.getCssName('cm-gplus-share-button'); /** @const */ cm.css.GRAPHIC_SELECTOR = goog.getCssName('cm-graphic-selector'); /** @const */ cm.css.HEADER = goog.getCssName('cm-header'); /** @const */ cm.css.HELP_ICON = goog.getCssName('cm-help-icon'); /** @const */ cm.css.HIDDEN = goog.getCssName('cm-hidden'); /** @const */ cm.css.HTML_EDITOR = goog.getCssName('cm-html-editor'); /** @const */ cm.css.IMPORTER = goog.getCssName('cm-importer'); /** @const */ cm.css.IMPORTER_HEADER = goog.getCssName('cm-importer-header'); /** @const */ cm.css.IMPORTER_LIST = goog.getCssName('cm-importer-list'); /** @const */ cm.css.INSPECTOR = goog.getCssName('cm-inspector'); /** @const */ cm.css.LABEL = goog.getCssName('cm-label'); /** @const */ cm.css.LANGUAGE_PICKER_ICON = goog.getCssName('cm-language-picker-icon'); /** @const */ cm.css.LAT_LNG = goog.getCssName('cm-lat-lng'); /** @const */ cm.css.LAYER_DESCRIPTION = goog.getCssName('cm-layer-description'); /** @const */ cm.css.LAYER_ENTRY = goog.getCssName('cm-layer-entry'); /** @const */ cm.css.LAYER_FILTER = goog.getCssName('cm-layer-filter'); /** @const */ cm.css.LAYER_FILTER_INFO = goog.getCssName('cm-layer-filter-info'); /** @const */ cm.css.LAYER_ITEM = goog.getCssName('cm-layer-item'); /** @const */ cm.css.LAYER_LEGEND = goog.getCssName('cm-layer-legend'); /** @const */ cm.css.LAYER_LEGEND_BOX = goog.getCssName('cm-layer-legend-box'); /** @const */ cm.css.LAYER_PREVIEW = goog.getCssName('cm-layer-preview'); /** @const */ cm.css.LAYER_SELECTED = goog.getCssName('cm-layer-selected'); /** @const */ cm.css.LAYER_TITLE = goog.getCssName('cm-layer-title'); /** @const */ cm.css.LAYOUT_RTL = goog.getCssName('cm-layout-rtl'); /** @const */ cm.css.LEGEND_COLOR = goog.getCssName('cm-legend-color'); /** @const */ cm.css.LEGEND_EDITOR = goog.getCssName('cm-legend-editor'); /** @const */ cm.css.LEGEND_GRAPHIC = goog.getCssName('cm-legend-graphic'); /** @const */ cm.css.LEGEND_ICON = goog.getCssName('cm-legend-icon'); /** @const */ cm.css.LEGEND_ITEM = goog.getCssName('cm-legend-item'); /** @const */ cm.css.LEGEND_ITEMS = goog.getCssName('cm-legend-items'); /** @const */ cm.css.LEGEND_LINE = goog.getCssName('cm-legend-line'); /** @const */ cm.css.LEGEND_POLYGON = goog.getCssName('cm-legend-polygon'); /** @const */ cm.css.LEGEND_TEXT = goog.getCssName('cm-legend-text'); /** @const */ cm.css.LOGIN = goog.getCssName('cm-login'); /** @const */ cm.css.LOGO_BOTTOM_LEFT = goog.getCssName('cm-logo-bottom-left'); /** @const */ cm.css.LOGO_WATERMARK = goog.getCssName('cm-logo-watermark'); /** @const */ cm.css.MAP = goog.getCssName('cm-map'); /** @const */ cm.css.MAPBUTTON = goog.getCssName('cm-mapbutton'); /** @const */ cm.css.MAP_COPYRIGHT = goog.getCssName('cm-map-copyright'); /** @const */ cm.css.MAP_DESCRIPTION = goog.getCssName('cm-map-description'); /** @const */ cm.css.MAP_PICKER = goog.getCssName('cm-map-picker'); /** @const */ cm.css.MAP_PICKER_BUTTON = goog.getCssName('cm-map-picker-button'); /** @const */ cm.css.MAP_PUBLISHER = goog.getCssName('cm-map-publisher'); /** @const */ cm.css.MAP_TITLE = goog.getCssName('cm-map-title'); /** @const */ cm.css.MAP_TITLE_PICKER = goog.getCssName('cm-map-title-picker'); /** @const */ cm.css.MAP_WRAPPER = goog.getCssName('cm-map-wrapper'); /** @const */ cm.css.MY_LOCATION_BUTTON = goog.getCssName('cm-my-location-button'); /** @const */ cm.css.NAV_COMPACT = goog.getCssName('cm-nav-compact'); /** @const */ cm.css.NAV_ITEM = goog.getCssName('cm-nav-item'); /** @const */ cm.css.NAV_ITEM_SEPARATOR = goog.getCssName('cm-nav-item-separator'); /** @const */ cm.css.NAV_ITEM_UNDELIMITED = goog.getCssName('cm-nav-item-undelimited'); /** @const */ cm.css.NAV_LINK = goog.getCssName('cm-nav-link'); /** @const */ cm.css.NAV_LIST = goog.getCssName('cm-nav-list'); /** @const */ cm.css.NO_PREVIEW = goog.getCssName('cm-no-preview'); /** @const */ cm.css.OPEN = goog.getCssName('cm-open'); /** @const */ cm.css.PANEL = goog.getCssName('cm-panel'); /** @const */ cm.css.PANEL_BELOW = goog.getCssName('cm-panel-below'); /** @const */ cm.css.PANEL_BUTTON = goog.getCssName('cm-panel-button'); /** @const */ cm.css.PANEL_COLLAPSED = goog.getCssName('cm-panel-collapsed'); /** @const */ cm.css.PANEL_DOCK = goog.getCssName('cm-panel-dock'); /** @const */ cm.css.PANEL_FLOAT = goog.getCssName('cm-panel-float'); /** @const */ cm.css.PANEL_HEADER = goog.getCssName('cm-panel-header'); /** @const */ cm.css.PANEL_INNER = goog.getCssName('cm-panel-inner'); /** @const */ cm.css.PANEL_LAYERS = goog.getCssName('cm-panel-layers'); /** @const */ cm.css.PANEL_LEFT = goog.getCssName('cm-panel-left'); /** @const */ cm.css.PANEL_LINKS = goog.getCssName('cm-panel-links'); /** @const */ cm.css.PANEL_OUTER_HEADER = goog.getCssName('cm-panel-outer-header'); /** @const */ cm.css.PANEL_RIGHT = goog.getCssName('cm-panel-right'); /** @const */ cm.css.PANEL_SCROLL = goog.getCssName('cm-panel-scroll'); /** @const */ cm.css.POPUP = goog.getCssName('cm-popup'); /** @const */ cm.css.PREVIEW = goog.getCssName('cm-preview'); /** @const */ cm.css.PREVIEW_ACTIVE = goog.getCssName('cm-preview-active'); /** @const */ cm.css.PREVIEW_LINK = goog.getCssName('cm-preview-link'); /** @const */ cm.css.PROMOTED_SUBLAYER = goog.getCssName('cm-promoted-sublayer'); /** @const */ cm.css.SEARCHBOX = goog.getCssName('cm-searchbox'); /** @const */ cm.css.SELECTED = goog.getCssName('cm-selected'); /** @const */ cm.css.SELECTED_COUNT = goog.getCssName('cm-selected-count'); /** @const */ cm.css.SHARE = goog.getCssName('cm-share'); /** @const */ cm.css.SHARE_EMAILER = goog.getCssName('cm-share-emailer'); /** @const */ cm.css.SHARE_HEADER = goog.getCssName('cm-share-header'); /** @const */ cm.css.SHARE_HTML = goog.getCssName('cm-share-html'); /** @const */ cm.css.SHARE_URL = goog.getCssName('cm-share-url'); /** @const */ cm.css.SHORTEN = goog.getCssName('cm-shorten'); /** @const */ cm.css.SHORTEN_CHECKBOX = goog.getCssName('cm-shorten-checkbox'); /** @const */ cm.css.SLIDER = goog.getCssName('cm-slider'); /** @const */ cm.css.SLIDER_CIRCLE = goog.getCssName('cm-slider-circle'); /** @const */ cm.css.SLIDER_DOT = goog.getCssName('cm-slider-dot'); /** @const */ cm.css.SOCIAL = goog.getCssName('cm-social'); /** @const */ cm.css.SUBLAYERS = goog.getCssName('cm-sublayers'); /** @const */ cm.css.SUBLAYER_SELECT = goog.getCssName('cm-sublayer-select'); /** @const */ cm.css.SUBMIT = goog.getCssName('cm-submit'); /** @const */ cm.css.TABBED = goog.getCssName('cm-tabbed'); /** @const */ cm.css.TAB_BAR_BUTTONS = goog.getCssName('cm-tab-bar-buttons'); /** @const */ cm.css.TAB_BAR_CONTAINER = goog.getCssName('cm-tab-bar-container'); /** @const */ cm.css.TAB_CONTENT = goog.getCssName('cm-tab-content'); /** @const */ cm.css.TAB_CONTENT_COLLAPSED = goog.getCssName('cm-tab-content-collapsed'); /** @const */ cm.css.TAB_PANEL = goog.getCssName('cm-tab-panel'); /** @const */ cm.css.TAB_PANEL_BELOW = goog.getCssName('cm-tab-panel-below'); /** @const */ cm.css.TAB_PANEL_EXPANDED = goog.getCssName('cm-tab-panel-expanded'); /** @const */ cm.css.TEXTAREA_ROW = goog.getCssName('cm-textarea-row'); /** @const */ cm.css.TEXT_INPUT_ROW = goog.getCssName('cm-text-input-row'); /** @const */ cm.css.TIMESTAMP = goog.getCssName('cm-timestamp'); /** @const */ cm.css.TOOLBAR = goog.getCssName('cm-toolbar'); /** @const */ cm.css.TOOLTIP = goog.getCssName('cm-tooltip'); /** @const */ cm.css.TOUCH = goog.getCssName('cm-touch'); /** @const */ cm.css.TRIANGLE = goog.getCssName('cm-triangle'); /** @const */ cm.css.TWITTER_IMG = goog.getCssName('cm-twitter-img'); /** @const */ cm.css.TWITTER_SHARE_BUTTON = goog.getCssName('cm-twitter-share-button'); /** @const */ cm.css.USER = goog.getCssName('cm-user'); /** @const */ cm.css.VALIDATION_ERROR = goog.getCssName('cm-validation-error'); /** @const */ cm.css.VIEWPORT_INFO = goog.getCssName('cm-viewport-info'); /** @const */ cm.css.WARNING = goog.getCssName('cm-warning'); /** @const */ cm.css.WEST = goog.getCssName('cm-west'); /** @const */ cm.css.WHATEVER_CLASS = goog.getCssName('cm-whatever-class'); /** @const */ cm.css.WMS_MENU_EDITOR = goog.getCssName('cm-wms-menu-editor'); <file_sep>#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at: http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distrib- # uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. See the License for # specific language governing permissions and limitations under the License. """Data model and related access permissions.""" __author__ = '<EMAIL> (<NAME>)' import base64 import datetime import json import random import cache import domains import logs import perms import users import utils from google.appengine.ext import db # A datetime value to represent null (the datastore cannot query on None). NEVER = datetime.datetime.utcfromtimestamp(0) class MapVersionModel(db.Model): """A particular version of the JSON content of a Map. NOTE: This class is private to this module; outside code should use the Map class to create or access versions. If this entity is constructed properly, its parent entity will be a MapModel. """ # The JSON string representing the map content, in MapRoot format. maproot_json = db.TextProperty() # Fields below are metadata for those with edit access, not for public # display. No updated field is needed; these objects are immutable. created = db.DateTimeProperty() creator_uid = db.StringProperty() creator = db.UserProperty() # DEPRECATED class MapModel(db.Model): """A single map object and its associated metadata; parent of its versions. NOTE: This class is private to this module; outside code should use the Map class to create or access maps. The key_name is a unique ID. The latest version is what's shown to viewers. """ # Title for the current version. Cached from the current version for display. # Plain text. title = db.StringProperty() # HTML description of the map. Cached from current version for display. description = db.TextProperty() # Metadata for auditing and debugging purposes. created = db.DateTimeProperty() creator_uid = db.StringProperty() creator = db.UserProperty() # DEPRECATED updated = db.DateTimeProperty() updater_uid = db.StringProperty() last_updated = db.DateTimeProperty() # DEPRECATED last_updater = db.UserProperty() # DEPRECATED # To mark a map as deleted, set this to anything other than NEVER; the map # won't be returned by Map.Get* methods, though it remains in the datastore. deleted = db.DateTimeProperty(default=NEVER) deleter_uid = db.StringProperty() deleter = db.UserProperty() # DEPRECATED # To mark a map as blocked, set this to anything other than NEVER; then only # the first owner can view or edit the map, and the map cannot be published. blocked = db.DateTimeProperty(default=NEVER) blocker_uid = db.StringProperty() blocker = db.UserProperty() # DEPRECATED # User IDs of users who can set the flags and permission lists on this object. owners = db.StringListProperty() # User IDs of users who can edit this map. editors = db.StringListProperty() # User IDs of users who can view the current version of this map. viewers = db.StringListProperty() # List of domains that this map belongs to. # TODO(kpy): Replace this with a single required StringProperty. # CAUTION: for not google domains this is potentially problematic, # since there may not be a google apps domain that corresponds to the # gaia ids (and hence no management). domains = db.StringListProperty() # Default role for users in one of the domains listed in the domains property. # domain_role can be set to admin, but we won't honor it. domain_role = db.StringProperty(choices=list(perms.Role)) # World-readable maps can be viewed by anyone. world_readable = db.BooleanProperty(default=False) # Cache of the most recent MapVersion. current_version = db.ReferenceProperty(reference_class=MapVersionModel) class CatalogEntryModel(db.Model): """A mapping from a (publisher domain, publication label) pair to a map. NOTE: This class is private to this module; outside code should use the CatalogEntry class to create or access catalog entries. The existence of a CatalogEntryModel with key_name "<domain>:<label>" causes the map to be available at the URL .../crisismap/a/<domain>/<label>. The catalog entry is like a snapshot; it points at a single MapVersionModel, so changes to the Map (i.e. new versions of the Map content) don't appear at .../crisismap/foo until the catalog entry is repointed at the new version. Each domain has a menu of maps (an instance of cm.MapPicker) that is shown on all the published map pages for that domain. The menu shows a subset of the catalog entries in that domain, as selected by the is_listed flag. """ # The domain and label (these are redundant with the key_name of the entity, # but broken out as separate properties so queries can filter on them). domain = db.StringProperty() label = db.StringProperty() # Metadata about the catalog entry itself. created = db.DateTimeProperty() creator_uid = db.StringProperty() creator = db.UserProperty() # DEPRECATED updated = db.DateTimeProperty() updater_uid = db.StringProperty() last_updated = db.DateTimeProperty() # DEPRECATED last_updater = db.UserProperty() # DEPRECATED # The displayed title (in the crisis picker). Set from the map_object. title = db.StringProperty() # The publisher name to display in the footer and below the map # title, in view-mode only. publisher_name = db.StringProperty() # The key_name of the map_version's parent MapModel (this is redundant with # map_version, but broken out as a property so queries can filter on it). map_id = db.StringProperty() # Reference to the map version published by this catalog entry. map_version = db.ReferenceProperty(MapVersionModel) # If true, this entry is shown in its domain's cm.MapPicker menu. is_listed = db.BooleanProperty(default=False) @staticmethod def Get(domain, label): return CatalogEntryModel.get_by_key_name(domain + ':' + label) @staticmethod def GetAll(domain=None): """Yields all CatalogEntryModels in reverse update order.""" query = CatalogEntryModel.all().order('-updated') if domain: query = query.filter('domain =', domain) return query @staticmethod def GetListed(domain=None): """Yields all the listed CatalogEntryModels in reverse update order.""" return CatalogEntryModel.GetAll(domain).filter('is_listed =', True) @staticmethod def Put(uid, domain, label, map_object, is_listed=False): """Stores a CatalogEntryModel pointing at the map's current version.""" if ':' in domain: raise ValueError('Invalid domain %r' % domain) now = datetime.datetime.utcnow() entity = CatalogEntryModel.Get(domain, label) if not entity: entity = CatalogEntryModel(key_name=domain + ':' + label, domain=domain, label=label, created=now, creator_uid=uid) entity.updated = now entity.updater_uid = uid entity.title = map_object.title entity.map_id = map_object.id entity.map_version = map_object.GetCurrent().key entity.is_listed = is_listed entity.put() return entity class CatalogEntry(object): """An access control wrapper around the CatalogEntryModel entity. All access from outside this module should go through CatalogEntry (never CatalogEntryModel). Entries should always be created via CatalogEntry.Create. The MapRoot JSON content of a CatalogEntry is always considered publicly readable, independent of the permission settings on the Map object. """ def __init__(self, catalog_entry_model): """Constructor not to be called directly. Use Create instead.""" self.model = catalog_entry_model @staticmethod def Get(domain, label): """Returns the CatalogEntry for a domain and label if it exists, or None.""" # We reserve the label 'empty' in all domains for a catalog entry pointing # at the empty map. Handy for development. if label == 'empty': return EmptyCatalogEntry(domain) # No access control; all catalog entries are publicly visible. model = CatalogEntryModel.Get(domain, label) return model and CatalogEntry(model) @staticmethod def GetAll(domain=None): """Gets all entries, possibly filtered by domain.""" # No access control; all catalog entries are publicly visible. # We use '*' in the cache key for the list that includes all domains. return cache.Get( [CatalogEntry, domain or '*', 'all'], lambda: map(CatalogEntry, CatalogEntryModel.GetAll(domain))) @staticmethod def GetListed(domain=None): """Gets all entries marked listed, possibly filtered by domain.""" # No access control; all catalog entries are publicly visible. # We use '*' in the cache key for the list that includes all domains. return cache.Get( [CatalogEntry, domain or '*', 'listed'], lambda: map(CatalogEntry, CatalogEntryModel.GetListed(domain))) @staticmethod def GetByMapId(map_id): """Returns all entries that point at a particular map.""" return [CatalogEntry(model) for model in CatalogEntryModel.GetAll().filter('map_id =', map_id)] # TODO(kpy): First argument should be a user. @staticmethod def Create(domain_name, label, map_object, is_listed=False): """Stores a new CatalogEntry with version set to the map's current version. If a CatalogEntry already exists with the same label, and the user is allowed to overwrite it, it is overwritten. Args: domain_name: The domain in which to create the CatalogEntry. label: The publication label to use for this map. map_object: The Map object whose current version to use. is_listed: If True, show this entry in the map picker menu. Returns: The new CatalogEntry object. Raises: ValueError: If the domain string is invalid. """ domain_name = str(domain_name) # accommodate Unicode strings domain = domains.Domain.Get(domain_name) if not domain: raise ValueError('Unknown domain %r' % domain_name) perms.AssertAccess(perms.Role.CATALOG_EDITOR, domain_name) perms.AssertAccess(perms.Role.MAP_VIEWER, map_object) perms.AssertPublishable(map_object) # If catalog is sticky, only a creator or domain admin may update an entry. if (domain.has_sticky_catalog_entries and not perms.CheckAccess(perms.Role.DOMAIN_ADMIN, domain_name)): entry = CatalogEntryModel.Get(domain_name, label) if entry: perms.AssertCatalogEntryOwner(entry) entry = CatalogEntryModel.Put( users.GetCurrent().id, domain_name, label, map_object, is_listed) logs.RecordEvent(logs.Event.MAP_PUBLISHED, domain_name=domain_name, map_id=map_object.id, map_version_key=entry.map_version.key().name(), catalog_entry_key=domain_name + ':' + label, uid=users.GetCurrent().id) # We use '*' in the cache key for the list that includes all domains. cache.Delete([CatalogEntry, '*', 'all']) cache.Delete([CatalogEntry, '*', 'listed']) cache.Delete([CatalogEntry, domain_name, 'all']) cache.Delete([CatalogEntry, domain_name, 'listed']) return CatalogEntry(entry) @staticmethod def Delete(domain_name, label, user=None): """Deletes an existing CatalogEntry. Args: domain_name: The domain to which the CatalogEntry belongs. label: The publication label. user: (optional) the user initiating the delete, or None for the current user. Raises: ValueError: if there's no CatalogEntry with the given domain and label. """ if not user: user = users.GetCurrent() domain_name = str(domain_name) # accommodate Unicode strings domain = domains.Domain.Get(domain_name) if not domain: raise ValueError('Unknown domain %r' % domain_name) entry = CatalogEntryModel.Get(domain_name, label) if not entry: raise ValueError('No CatalogEntry %r in domain %r' % (label, domain_name)) perms.AssertAccess(perms.Role.CATALOG_EDITOR, domain_name) # If catalog is sticky, only a creator or domain admin may delete an entry. if (domain.has_sticky_catalog_entries and not perms.CheckAccess(perms.Role.DOMAIN_ADMIN, domain_name)): perms.AssertCatalogEntryOwner(entry) # Grab all the log information before we delete the entry map_id, version_key = entry.map_id, entry.map_version.key().name() entry_key = entry.key().name() entry.delete() logs.RecordEvent(logs.Event.MAP_UNPUBLISHED, domain_name=domain_name, map_id=map_id, map_version_key=version_key, catalog_entry_key=entry_key, uid=user.id) # We use '*' in the cache key for the list that includes all domains. cache.Delete([CatalogEntry, '*', 'all']) cache.Delete([CatalogEntry, '*', 'listed']) cache.Delete([CatalogEntry, domain_name, 'all']) cache.Delete([CatalogEntry, domain_name, 'listed']) # TODO(kpy): Make Delete and DeleteByMapId both take a user argument, and # reuse Delete here by calling it with an admin user. @staticmethod def DeleteByMapId(map_id): """NO ACCESS CHECK. Deletes every CatalogEntry pointing at a given map.""" for entry in CatalogEntry.GetByMapId(map_id): domain, label = str(entry.domain), entry.label entry = CatalogEntryModel.Get(domain, label) entry.delete() # We use '*' in the cache key for the list that includes all domains. cache.Delete([CatalogEntry, '*', 'all']) cache.Delete([CatalogEntry, '*', 'listed']) cache.Delete([CatalogEntry, domain, 'all']) cache.Delete([CatalogEntry, domain, 'listed']) is_listed = property( lambda self: self.model.is_listed, lambda self, value: setattr(self.model, 'is_listed', value)) id = property(lambda self: self.model.key().name()) # The datastore key of this catalog entry's MapVersionModel. def GetMapVersionKey(self): return CatalogEntryModel.map_version.get_value_for_datastore(self.model) map_version_key = property(GetMapVersionKey) # maproot_json gets the (possibly cached) MapRoot JSON for this entry. def GetMaprootJson(self): return cache.Get([CatalogEntry, self.domain, self.label, 'json'], lambda: self.model.map_version.maproot_json) maproot_json = property(GetMaprootJson) # Make the other properties of the CatalogEntryModel visible on CatalogEntry. for x in ['domain', 'label', 'map_id', 'title', 'publisher_name', 'created', 'creator_uid', 'updated', 'updater_uid']: locals()[x] = property(lambda self, x=x: getattr(self.model, x)) # Handy access to the user profiles associated with user IDs. creator = property(lambda self: users.Get(self.creator_uid)) updater = property(lambda self: users.Get(self.updater_uid)) def SetMapVersion(self, map_object): """Points this entry at the specified MapVersionModel.""" self.model.map_id = map_object.id self.model.map_version = map_object.GetCurrent().key self.model.title = map_object.title def SetPublisherName(self, publisher_name): """Sets the publisher name to be displayed in the map viewer.""" self.model.publisher_name = publisher_name def Put(self): """Saves any modifications to the datastore.""" domain_name = str(self.domain) # accommodate Unicode strings perms.AssertAccess(perms.Role.CATALOG_EDITOR, domain_name) # If catalog is sticky, only a creator or domain admin may update an entry. domain = domains.Domain.Get(domain_name) if not domain: raise ValueError('Unknown domain %r' % domain_name) # TODO(kpy): We could use a perms function for this catalog entry check. if (domain.has_sticky_catalog_entries and not perms.CheckAccess(perms.Role.DOMAIN_ADMIN, domain_name)): perms.AssertCatalogEntryOwner(self.model) self.model.updater_uid = users.GetCurrent().id self.model.updated = datetime.datetime.utcnow() self.model.put() logs.RecordEvent(logs.Event.MAP_PUBLISHED, domain_name=domain_name, map_id=self.map_id, map_version_key=self.GetMapVersionKey().name(), catalog_entry_key=self.id, uid=users.GetCurrent().id) # We use '*' in the cache key for the list that includes all domains. cache.Delete([CatalogEntry, '*', 'all']) cache.Delete([CatalogEntry, '*', 'listed']) cache.Delete([CatalogEntry, domain_name, 'all']) cache.Delete([CatalogEntry, domain_name, 'listed']) cache.Delete([CatalogEntry, domain_name, self.label, 'json']) class Map(object): """An access control wrapper around the MapModel entity. All access from outside this module should go through Map (never MapModel). Maps should always be created with Map.Create, which ensures that every map has at least one version. """ # NOTE(kpy): Every public static method or public impure method should # call self.AssertAccess(...) first! NAMESPACE = 'Map' # cache namespace def __init__(self, map_model): """Constructor not to be called directly.""" self.model = map_model def __eq__(self, other): return isinstance(other, Map) and self.model.key() == other.model.key() def __hash__(self): return hash(self.model) # The datastore key for this map's MapModel entity. key = property(lambda self: self.model.key()) # The datastore key for this map's latest MapVersionModel. current_version_key = property( lambda self: MapModel.current_version.get_value_for_datastore(self.model)) # Map IDs are in base64, so they are safely convertible from Unicode to ASCII. id = property(lambda self: str(self.model.key().name())) # Make the other properties of the underlying MapModel readable on the Map. for x in ['created', 'creator_uid', 'updated', 'updater_uid', 'blocked', 'blocker_uid', 'deleted', 'deleter_uid', 'title', 'description', 'current_version', 'world_readable', 'owners', 'editors', 'viewers', 'domains', 'domain_role']: locals()[x] = property(lambda self, x=x: getattr(self.model, x)) # Handy access to the user profiles associated with user IDs. creator = property(lambda self: users.Get(self.creator_uid)) updater = property(lambda self: users.Get(self.updater_uid)) blocker = property(lambda self: users.Get(self.blocker_uid)) deleter = property(lambda self: users.Get(self.deleter_uid)) # Handy Boolean access to the blocked or deleted status. is_blocked = property(lambda self: self.blocked != NEVER) is_deleted = property(lambda self: self.deleted != NEVER) @staticmethod def get(key): # lowercase to match db.Model.get # pylint: disable=g-bad-name return Map(MapModel.get(key)) @staticmethod def _GetAll(domain=None): """NO ACCESS CHECK. Yields all non-deleted maps; can filter by domain.""" query = MapModel.all().order('-updated').filter('deleted =', NEVER) if domain: query = query.filter('domains =', domain) return (Map(model) for model in query) @staticmethod def GetAll(domain=None): """Yields all non-deleted maps, possibly filtered by domain.""" perms.AssertAccess(perms.Role.ADMIN) return Map._GetAll(domain) @staticmethod def GetViewable(user, domain=None): """Yields all maps visible to the user, possibly filtered by domain.""" # TODO(lschumacher): This probably won't scale to a large number of maps. # Also, we should only project the fields we want. # Share the AccessPolicy object to avoid fetching access lists repeatedly. policy = perms.AccessPolicy() for m in Map._GetAll(domain): if m.CheckAccess(perms.Role.MAP_VIEWER, user, policy=policy): yield m @staticmethod def Get(key_name): """Gets a Map by its map ID (key_name), or returns None if none exists.""" # We reserve the special ID '0' for an empty map. Handy for development. if key_name == '0': return EmptyMap() model = MapModel.get_by_key_name(key_name) if model and model.deleted == NEVER: map_object = Map(model) map_object.AssertAccess(perms.Role.MAP_VIEWER) return map_object @staticmethod def GetDeleted(key_name): """Gets a deleted Map by its ID. Returns None if no map or not deleted.""" perms.AssertAccess(perms.Role.ADMIN) model = MapModel.get_by_key_name(key_name) return model and model.deleted != NEVER and Map(model) @staticmethod def Create(maproot_json, domain, owners=None, editors=None, viewers=None, world_readable=False): """Stores a new map with the given properties and MapRoot JSON content.""" # maproot_json must be syntactically valid JSON, but otherwise any JSON # object is allowed; we don't check for MapRoot validity here. # TODO(rew): Change the domain argument to take a domains.Domain instead # of a string domain_obj = domains.Domain.Get(domain) if not domain_obj: raise domains.UnknownDomainError(domain) domain = domain_obj perms.AssertAccess(perms.Role.MAP_CREATOR, domain.name) if owners is None: # TODO(kpy): Take user as an argument instead of calling GetCurrent. owners = [users.GetCurrent().id] if editors is None: editors = [] if viewers is None: viewers = [] if domain.initial_domain_role: domain_subjects = set(perms.GetSubjectsForTarget(domain.name).keys()) if domain.initial_domain_role == perms.Role.MAP_OWNER: owners = list(set(owners) | domain_subjects) elif domain.initial_domain_role == perms.Role.MAP_EDITOR: editors = list(set(editors) | domain_subjects) elif domain.initial_domain_role == perms.Role.MAP_VIEWER: viewers = list(set(viewers) | domain_subjects) # urlsafe_b64encode encodes 12 random bytes as exactly 16 characters, # which can include digits, letters, hyphens, and underscores. Because # the length is a multiple of 4, it won't have trailing "=" signs. map_object = Map(MapModel( key_name=base64.urlsafe_b64encode( ''.join(chr(random.randrange(256)) for i in xrange(12))), created=datetime.datetime.utcnow(), creator_uid=users.GetCurrent().id, owners=owners, editors=editors, viewers=viewers, domains=[domain.name], domain_role=domain.initial_domain_role, world_readable=world_readable)) map_object.PutNewVersion(maproot_json) # also puts the MapModel return map_object @staticmethod def _GetVersionByKey(key): """NO ACCESS CHECK. Returns a map version by its datastore entity key.""" return utils.StructFromModel(MapVersionModel.get(key)) def PutNewVersion(self, maproot_json): """Stores a new MapVersionModel object for this Map and returns its ID.""" self.AssertAccess(perms.Role.MAP_EDITOR) maproot = json.loads(maproot_json) # validate the JSON first now = datetime.datetime.utcnow() uid = users.GetCurrent().id new_version = MapVersionModel(parent=self.model, maproot_json=maproot_json, created=now, creator_uid=uid) # Update the MapModel from fields in the MapRoot JSON. self.model.title = maproot.get('title', '') self.model.description = maproot.get('description', '') self.model.updated = now self.model.updater_uid = uid def PutModels(): self.model.current_version = new_version.put() self.model.put() db.run_in_transaction(PutModels) cache.Delete([Map, self.id, 'json']) return new_version.key().id() def GetCurrent(self): """Gets this map's latest version. Returns: A utils.Struct with the properties of this map's current version, along with a property 'id' containing the version's ID; or None if the current version has not been set. (Version IDs are not necessarily in creation order, and are unique within a particular Map but not across all Maps.) """ self.AssertAccess(perms.Role.MAP_VIEWER) return self.current_version and utils.StructFromModel(self.current_version) def Delete(self): """Marks a map as deleted (so it won't be returned by Get or GetAll).""" self.AssertAccess(perms.Role.MAP_OWNER) self.model.deleted = datetime.datetime.utcnow() self.model.deleter_uid = users.GetCurrent().id CatalogEntry.DeleteByMapId(self.id) self.model.put() logs.RecordEvent(logs.Event.MAP_DELETED, map_id=self.id, uid=self.model.deleter_uid) cache.Delete([Map, self.id, 'json']) def Undelete(self): """Unmarks a map as deleted.""" self.AssertAccess(perms.Role.ADMIN) self.model.deleted = NEVER self.model.deleter_uid = None self.model.put() logs.RecordEvent(logs.Event.MAP_UNDELETED, map_id=self.id, uid=users.GetCurrent().id) cache.Delete([Map, self.id, 'json']) def SetBlocked(self, block): """Sets whether a map is blocked (private to one user and unpublishable).""" perms.AssertAccess(perms.Role.ADMIN) if block: self.model.blocked = datetime.datetime.utcnow() self.model.blocker_uid = users.GetCurrent().id CatalogEntry.DeleteByMapId(self.id) logs.RecordEvent(logs.Event.MAP_BLOCKED, map_id=self.id, uid=self.model.blocker_uid) else: self.model.blocked = NEVER self.model.blocker_uid = None logs.RecordEvent(logs.Event.MAP_UNBLOCKED, map_id=self.id, uid=users.GetCurrent().id) self.model.put() cache.Delete([Map, self.id, 'json']) def Wipe(self): """Permanently destroys a map.""" self.AssertAccess(perms.Role.ADMIN) CatalogEntry.DeleteByMapId(self.id) map_id, domain_name = self.id, self.domains[0] db.delete([self.model] + list(MapVersionModel.all().ancestor(self.model))) logs.RecordEvent(logs.Event.MAP_WIPED, domain_name=domain_name, map_id=map_id, uid=users.GetCurrent().id) def GetCurrentJson(self): """Gets the current JSON for public viewing only.""" self.AssertAccess(perms.Role.MAP_VIEWER) return cache.Get([Map, self.id, 'json'], lambda: getattr(self.GetCurrent(), 'maproot_json', None)) def GetVersions(self): """Yields all versions of this map in order from newest to oldest.""" self.AssertAccess(perms.Role.MAP_EDITOR) query = MapVersionModel.all().ancestor(self.model).order('-created') return utils.ResultIterator(query) def GetVersion(self, version_id): """Returns a specific version of this map.""" self.AssertAccess(perms.Role.MAP_EDITOR) version = MapVersionModel.get_by_id(version_id, parent=self.model.key()) return utils.StructFromModel(version) def SetWorldReadable(self, world_readable): """Sets whether the map is world-readable.""" self.AssertAccess(perms.Role.MAP_OWNER) self.model.world_readable = world_readable self.model.put() def RevokePermission(self, role, uid): """Revokes user permissions for the map.""" self.AssertAccess(perms.Role.MAP_OWNER) # Does nothing if the user does not have the role to begin with or if # the role is not editor, viewer, or owner. if role == perms.Role.MAP_VIEWER and uid in self.model.viewers: self.model.viewers.remove(uid) elif role == perms.Role.MAP_EDITOR and uid in self.model.editors: self.model.editors.remove(uid) elif role == perms.Role.MAP_OWNER and uid in self.model.owners: self.model.owners.remove(uid) self.model.put() def ChangePermissionLevel(self, role, uid): """Changes the user's level of permission.""" # When a user's permission is changed to viewer, editor, or owner, # their former permission level is revoked. # Does nothing if role is not in permissions. self.AssertAccess(perms.Role.MAP_OWNER) permissions = [ perms.Role.MAP_VIEWER, perms.Role.MAP_EDITOR, perms.Role.MAP_OWNER] if role not in permissions: return elif role == perms.Role.MAP_VIEWER and uid not in self.model.viewers: self.model.viewers.append(uid) elif role == perms.Role.MAP_EDITOR and uid not in self.model.editors: self.model.editors.append(uid) elif role == perms.Role.MAP_OWNER and uid not in self.model.owners: self.model.owners.append(uid) # Take away the other permissions for permission in permissions: if permission != role: self.RevokePermission(permission, uid) self.model.put() def CheckAccess(self, role, user=None, policy=None): """Checks whether a user has the specified access role for this map.""" return perms.CheckAccess(role, self, user, policy=policy) def AssertAccess(self, role, user=None, policy=None): """Requires a user to have the specified access role for this map.""" perms.AssertAccess(role, self, user, policy=policy) class EmptyMap(Map): """An empty stand-in for a Map object (handy for development).""" # To ensure that the app has something to display, we return this special # empty map object as the map with ID '0'. TITLE = 'Empty map' DESCRIPTION = 'This is an empty map for testing.' JSON = '{"title": "%s", "description": "%s"}' % (TITLE, DESCRIPTION) def __init__(self): Map.__init__(self, MapModel( key_name='0', owners=[], editors=[], viewers=[], domains=['gmail.com'], world_readable=True, title=self.TITLE, description=self.DESCRIPTION)) def GetCurrent(self): key = db.Key.from_path('MapModel', '0', 'MapVersionModel', 1) return utils.Struct(id=1, key=key, maproot_json=self.JSON) def GetVersions(self): return [self.GetCurrent()] def GetVersion(self, version_id): if version_id == 1: return self.GetCurrent() def ReadOnlyError(self, *unused_args, **unused_kwargs): raise TypeError('EmptyMap is read-only') SetWorldReadable = ReadOnlyError PutNewVersion = ReadOnlyError Delete = ReadOnlyError RevokePermission = ReadOnlyError ChangePermissionLevel = ReadOnlyError class EmptyCatalogEntry(CatalogEntry): """An empty stand-in for a CatalogEntry object (handy for development).""" # To ensure that the app has something to display, we return this special # catalog entry as the entry with label 'empty' in all domains. def __init__(self, domain): CatalogEntry.__init__(self, CatalogEntryModel( domain=domain, label='empty', title=EmptyMap.TITLE, map_id='0')) maproot_json = property(lambda self: EmptyMap.JSON) def ReadOnlyError(self, *unused_args, **unused_kwargs): raise TypeError('EmptyCatalogEntry is read-only') SetMapVersion = ReadOnlyError Put = ReadOnlyError
866e42046c2d81b041aaaa6e2d152344447a2907
[ "Markdown", "Python", "JavaScript" ]
16
Python
AppScale/crisismap
758f0befbdbbc0eb2621fdaa2d250afd84d8829b
ad887d5dbfa19ad7a9139cbdde64838d3eed35f3
refs/heads/master
<file_sep>require "pry" class Song @@count = 0 @@artists = [] @@genres = [] @@genre_count = {} @@artist_count = {} attr_accessor :name, :artist, :genre def initialize(name, artist, genre) @name = name @artist = artist @genre = genre @@count += 1 @@artists.push(artist) @@genres.push(genre) end def self.count @@count end def self.genres counter = 0 return_array = [] @@genres.each do |genre| counter += 1 unless genre == @@genres[counter] return_array.push(genre) end end return_array end def self.artists counter = 0 return_array = [] @@artists.each do |artist| counter += 1 unless artist == @@artists[counter] return_array.push(artist) end end return_array end def self.genre_count return_hash = {} @@genres.each do |genre| if return_hash[genre] return_hash[genre] += 1 else return_hash[genre] = 1 end end return_hash end def self.artist_count return_hash = {} @@artists.each do |artist| if return_hash[artist] return_hash[artist] += 1 else return_hash[artist] = 1 end end return_hash end end
8d41d23343010c22b5c7fa9bb294f0abb08a98c2
[ "Ruby" ]
1
Ruby
mttwright/ruby-class-variables-and-class-methods-lab-online-web-pt-090919
ecc5a4704136d0f71812e25c02d2d41ee117bc65
af9160aed698969cec64403d856f7d653ecbadaa
refs/heads/main
<file_sep>// // ExploreController.swift // Twitter Clone // // Created by <NAME> on 06/06/21. // import UIKit class ExploreController: UIViewController{ // MARK : - Properties // MARK : - Lifecycles override func viewDidLoad() { super.viewDidLoad() configureUI() } // MARK:- Helpers func configureUI(){ view.backgroundColor = .white navigationItem.title = "Explore" } } <file_sep>// // MainTabController.swift // Twitter Clone // // Created by <NAME> on 05/06/21. // import UIKit class MainTabController: UITabBarController { // MARK : - Properties let actionButton : UIButton = { let button = UIButton(type: .system) button.tintColor = .white button.backgroundColor = .twitterBlue button.setImage(UIImage(named: "new_tweet"), for: .normal) button.addTarget(self, action: #selector(actionButtonTapped), for: .touchUpInside) return button }() // MARK : - Lifecycles func configureUI() { view.addSubview(actionButton) actionButton.anchor(bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.rightAnchor, paddingBottom: 64, paddingRight: 16, width: 56, height: 56) actionButton.layer.cornerRadius = 56 / 2 } override func viewDidLoad() { super.viewDidLoad() configureViewController() configureUI() } // MARK :- Selectors @objc func actionButtonTapped(){ print("Tapped") } // MARK:- Helpers func configureViewController() { let feed = FeedController() let nav1 = templateNavigationController(image: UIImage(named: "home_unselected")!, rootNavigationController: feed) let explore = ExploreController() explore.tabBarItem.image = UIImage(named: "search_unselected") let nav2 = templateNavigationController(image: UIImage(named: "search_unselected")!, rootNavigationController: explore) let notification = NotificationController() let nav3 = templateNavigationController(image: UIImage(named: "like_unselected")!, rootNavigationController: notification) let conversation = ConversationController() let nav4 = templateNavigationController(image: UIImage(named: "ic_mail_outline_white_2x-1")!, rootNavigationController: conversation) viewControllers = [nav1, nav2, nav3, nav4] } func templateNavigationController(image: UIImage, rootNavigationController: UIViewController) -> UINavigationController { let nav = UINavigationController(rootViewController: rootNavigationController) nav.tabBarItem.image = image nav.tabBarItem.image = image nav.navigationBar.barTintColor = .white return nav } } <file_sep>// // ConversationController.swift // Twitter Clone // // Created by <NAME> on 06/06/21. // import UIKit class ConversationController: UIViewController { // MARK : - Properties // MARK : - Lifecycles override func viewDidLoad() { super.viewDidLoad() configureUI() } // MARK:- Helpers func configureUI(){ view.backgroundColor = .white navigationItem.title = "Messages" } } <file_sep>// // FeedController.swift // Twitter Clone // // Created by <NAME> on 05/06/21. // import UIKit class FeedController: UIViewController{ // MARK : - Properties // MARK : - Lifecycles override func viewDidLoad() { super.viewDidLoad() configureUI() } // MARK:- Helpers func configureUI(){ view.backgroundColor = .white let imageView = UIImageView(image: UIImage(named: "twitter_logo_blue")) imageView.contentMode = .scaleAspectFit navigationItem.titleView = imageView } }
6647e543d43b711d087f085b3f20d5e3e912dcb3
[ "Swift" ]
4
Swift
IOS-HACKS/Twitter-clone
380799919e6190de548e3a0c29b53b31525f45e5
77b8975320c45f5ecdb64faf16c42a05e4da7e0c
refs/heads/master
<file_sep>(function() { var global = global || this || window || Function('return this')(); var nx = global.nx || require('next-js-core2'); var isObject = function(target) { return typeof target === 'object'; }; nx.deepEqObject = function(inObj1, inObj2) { if (inObj1 === inObj2) { return true; } if (inObj1 && inObj2 && isObject(inObj1) && isObject(inObj2)) { var keys = Object.keys(inObj1); var length = keys.length; if (length !== Object.keys(inObj2).length) { return false; } for (i = length; i-- !== 0; ) { key = keys[i]; if (!nx.deepEqObject(inObj1[key], inObj2[key])) { return false; } } return true; } return false; }; if (typeof module !== 'undefined' && module.exports) { module.exports = nx.deepEqObject; } })(); <file_sep># next-deep-eq-object > Equal object for next ## install: ```bash npm install -S afeiship/next-deep-eq-object --registry=https://registry.npm.taobao.org ``` ## usage: ```js //DOCS here! ```
c9820a6a6268864b5adceff50d8fb83b8e6d0208
[ "JavaScript", "Markdown" ]
2
JavaScript
afeiship/next-deep-eq-object
259c7ad822ebf46154bae8c4e996121d4cd327fa
e20ac230068fa47793434d5bc2a94cb1ca78e32c
refs/heads/main
<file_sep><div class="product-card"> <div class="card-img-container"> <img src="./images/img.png" alt="img" /> </div> <div class="card-content"> <h1 class="main-header"> <?php echo $item["product_name"]; ?> </h1> <h2 class='second-header'> <?php echo $item["product_title"]; ?> </h2> <div class="content-text"> <?php echo $item["product_description"]; ?> </div> <form action="/products-task-php/product.php" method="POST"> <button class="more-btn btn" name="more-btn" value="<?php echo $item["product_id"]; ?>">VEČ O IZEDLKU <?php echo $item["product_id"]; ?> </button> </form> </div> </div><file_sep><?php include_once('includes/db.connection.php'); include('header.php'); ?> <!-- Products Page Content --> <div class="products-container"> <?php $query = "SELECT * FROM products;"; $result = mysqli_query($conn, $query); $resultCheck = mysqli_num_rows($result); if ($resultCheck > 0) { while ($item = mysqli_fetch_assoc($result)) { include('Templates/_productCard.php'); } } ?> </div> <?php include('footer.php'); ?><file_sep># products_php => Start Apache Server and Database => http://localhost/products-task-php/product.php <file_sep>const parentNav = document.querySelector(".nav"); const navBar = document.querySelector(".nav-bar"); const navBarToggler = document.querySelector(".navbar-toggler"); let togglerHelper = true; const onTogglerClick = () => { if (!togglerHelper) { navBar.classList.remove("show"); parentNav.style.height = "80px"; togglerHelper = true; } else { parentNav.style.height = "330px" setTimeout(() => { navBar.classList.add("show"); }, 700) togglerHelper = false; } } navBarToggler.addEventListener('click', () => { onTogglerClick() });<file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Products</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700;800&display=swap" rel="stylesheet"> <link rel="stylesheet" href="./frontend/style.css"> </head> <!-- Navbar --> <?php include('Templates/_navbar.php'); ?> <body><file_sep><?php include_once('includes/db.connection.php'); include('header.php'); ?> <div class="product-page"> <?php $query = "SELECT * FROM products WHERE product_id = {$_POST["more-btn"]};"; $result = mysqli_query($conn, $query); $resultCheck = mysqli_num_rows($result); if ($resultCheck > 0) { $item = mysqli_fetch_assoc($result) ?> <div class="img-container"> <img src="./img.png" alt="img" /> </div> <div class="content"> <h1 class="main-header"> <?php echo $item["product_name"]; ?> </h1> <h2 class="second-header"> <?php echo $item["product_title"]; ?> </h2> <div class="content-text"> <?php echo $item["product_description"]; ?> </div> <form action="/products-task-php/index.php"> <button class="nazaj-btn">NAZAJ NA SEZNAM</button> </form> </div> <?php } ?> </div> <?php include('footer.php'); ?>
10dad4cb2024400c575f332e732eaa1f1aaeb61f
[ "Markdown", "JavaScript", "PHP" ]
6
PHP
bojanstojmenovski/products_php
083e2df58eafaa2103a5020833bc874926c1e3d0
307ff69a2918c4e2417235d6faacbfe77e1eb9bd
refs/heads/main
<file_sep>package com.elltor.demo.conf; import com.elltor.demo.service.MyJsonService; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @ConditionalOnClass(MyJsonService.class) @EnableConfigurationProperties(MyJsonProperties.class) public class MyJsonAutoConfiguration { private MyJsonProperties myJsonProperties; // 构造器注入 public MyJsonAutoConfiguration(MyJsonProperties myJsonProperties){ this.myJsonProperties = myJsonProperties; } // 自动配置 @Bean // 条件判读,当不存在MyJsonService时创建该Bean @ConditionalOnMissingBean(MyJsonService.class) public MyJsonService myJsonService(){ MyJsonService myJsonService = new MyJsonService(); myJsonService.setPrefixName(myJsonProperties.getPrefixName()); myJsonService.setSuffixName(myJsonProperties.getSuffixName()); return myJsonService; } } <file_sep>package com.elltor.demo.service; import com.alibaba.fastjson.JSON; public class MyJsonService { // 前缀 private String prefixName; // 后缀 private String suffixName; public String objectToJson(Object o){ return prefixName+JSON.toJSONString(o)+suffixName; } public String getPrefixName() { return prefixName; } public void setPrefixName(String prefixName) { this.prefixName = prefixName; } public String getSuffixName() { return suffixName; } public void setSuffixName(String suffixName) { this.suffixName = suffixName; } } <file_sep>### SpringBoot Starter原理与教程 https://blog.csdn.net/songzehao/article/details/100837463 https://blog.csdn.net/songzehao/article/details/100865939 https://www.jianshu.com/p/ab5254ecb8da https://blog.csdn.net/weixin_35962223/article/details/109161043 ### 步骤 1. 创建配置属性类 XXXProperties,设置注解 `@ConfigurationProperties` 2. 创建自动配置类,注解 - @Configuration 标志配置 - @ConditionalXXX 根据一定的条件使配置生效 - @EnableConfigurationProperties 指定配置属性类 3. 在`resources`中创建`META-INF`,创建 `spring.factories` 4. spring.factories ```bash org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.elltor.demo.conf.MyJsonAutoConfiguration ``` 5. 打包(package),将jar安装(install)到本地仓库
5200990c7f4680ca12fecac99d896006ff355b72
[ "Markdown", "Java" ]
3
Java
elltor/springboot-starter-demo
6a45ea6f9976dc55e2779d88ecae701b3e2b67bd
b73bcc5e87cae01e7a42783c3211a638f866be59
refs/heads/master
<repo_name>somecat1996/Classifier<file_sep>/CNNClassifier_jpg.py import tensorflow as tf from tiffReader import * ModelPath = "./jpg_CNN_1" TrainRate = 0.8 # 输入为[批大小,宽度,高度,深度] # -1代表自动处理当前大小 INPUTSHAPE = [-1, 96, 72, 3] # 输入形状 # 第一层卷积层输入形状为[批大小, 96, 72, 1] # 第一层卷积层输出形状为[批大小, 96, 72, 32] FILTER1_NUM = 32 # 第一层滤波器数量 FILTER1_SHAPE = [5, 5] # 第一层滤波器形状 # 第一层池化层输入形状为[批大小, 96, 72, 32] # 第一层池化层输出形状为[批大小, 48, 36, 32] POOL1_SHAPE = [2, 2] # 第一层池化层形状 POOL1_STRIDE = 2 # 第一层池化层步长 # 第二层卷积层输入形状为[批大小, 48, 36, 32] # 第二层卷积层输出形状为[批大小, 48, 36, 64] FILTER2_NUM = 64 # 第二层滤波器数量 FILTER2_SHAPE = [5, 5] # 第二层滤波器形状 # 第二层池化层输入形状为[批大小, 48, 36, 64] # 第二层池化层输出形状为[批大小, 12, 9, 64] POOL2_SHAPE = [4, 4] # 第二层池化层形状 POOL2_STRIDE = 4 # 第二层池化层步长 # 展平前输入形状为[批大小, 12, 9, 64] # 展平后形状为[批大小, 12*9*64] FLAT_SHAPE = [-1, 12*9*64] # 展平后形状 # 全连接层输入形状为[批大小,12*9*64] # 全连接层输出个数为[批大小,1024] DENSE_UNIT = 1024 # 全连接层输出个数 # 按概率丢弃神经元,避免过拟合 DROPOUT_RATE = 0.4 # 丢弃概率 # 输出个数,代表分类结果 OUTPUT_UNIT = 40 # 学习率 LEARNING_RATE = 0.001 def NeutralNetwork(features, labels, mode): # 重置输入形状 print(features["packet"]) input_layer = tf.reshape(features["packet"], INPUTSHAPE) # 第一层卷积层,创建FILTER1_NUM个形状为FILTER1_SHAPE的滤波器 # 采用默认步长(1, 1),卷积结果填充为与输入相同大小 # 使用激活函数max(feature, 0) conv1 = tf.layers.conv2d( inputs=input_layer, filters=FILTER1_NUM, kernel_size=FILTER1_SHAPE, padding="same", activation=tf.nn.relu) # 第一层池化层,采用形状为POOL1_SHAPE,步长为POOL1_STRIDE pool1 = tf.layers.max_pooling2d( inputs=conv1, pool_size=POOL1_SHAPE, strides=POOL1_STRIDE) # 第一层卷积层,创建FILTER2_NUM个形状为FILTER2_SHAPE的滤波器 # 采用默认步长(1, 1),卷积结果填充为与输入相同大小 # 使用激活函数max(feature, 0) conv2 = tf.layers.conv2d( inputs=pool1, filters=FILTER2_NUM, kernel_size=FILTER2_SHAPE, padding="same", activation=tf.nn.relu) # 第一层池化层,采用形状为POOL2_SHAPE,步长为POOL2_STRIDE pool2 = tf.layers.max_pooling2d( inputs=conv2, pool_size=POOL2_SHAPE, strides=POOL2_STRIDE) # 展平输出为[批大小, FLAT_SHAPE] pool2_flat = tf.reshape( tensor=pool2, shape=FLAT_SHAPE) # 全连接层,输出为[批大小, DENSE_UNIT] # 使用激活函数max(feature, 0) dense = tf.layers.dense( inputs=pool2_flat, units=DENSE_UNIT, activation=tf.nn.relu) # 按DROPOUT_RATE随机丢弃神经元 dropout = tf.layers.dropout( inputs=dense, rate=DROPOUT_RATE, training=mode == tf.estimator.ModeKeys.TRAIN) # 逻辑回归层,最终获得OUTPUT_UNIT个输出 logits = tf.layers.dense( inputs=dropout, units=OUTPUT_UNIT) # 预测 predictions = { # argmax返回第axis的索引所对应的最大值的索引 # logits形状为[批大小, 2],则其返回每一批中 # 最大值的索引——0或1 "classes": tf.argmax(input=logits, axis=1), # 默认对最后一个维度计算softmax函数 "probabilities": tf.nn.softmax(logits, name="softmax_tensor")} # 如果目前是预测状态,返回预测结果 if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) # 目前不是预测状态,获得损失函数 loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits) # 配置训练操作 if mode == tf.estimator.ModeKeys.TRAIN: optimizer = tf.train.GradientDescentOptimizer(learning_rate=LEARNING_RATE) train_op = optimizer.minimize( loss=loss, global_step=tf.train.get_global_step()) return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op) # 添加评价指标 eval_metric_ops = { "accuracy": tf.metrics.accuracy( labels=labels, predictions=predictions["classes"])} return tf.estimator.EstimatorSpec( mode=mode, loss=loss, eval_metric_ops=eval_metric_ops) tf.logging.set_verbosity(tf.logging.INFO) def main(unused): classifier = tf.estimator.Estimator( model_fn=NeutralNetwork, model_dir=ModelPath) packets_train, labels_train, packets_eval, labels_eval = ReadTiffData("./leaf/RGB") tensors_to_log = {"probabilities": "softmax_tensor"} logging_hook = tf.train.LoggingTensorHook( tensors=tensors_to_log, every_n_iter=50) train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"packet": packets_train}, y=labels_train, batch_size=50, num_epochs=None, shuffle=True) eval_input_fn = tf.estimator.inputs.numpy_input_fn( x={"packet": packets_eval}, y=labels_eval, num_epochs=1, shuffle=False) for i in range(200): classifier.train( input_fn=train_input_fn, steps=100, hooks=[logging_hook]) eval_results = classifier.evaluate(input_fn=eval_input_fn) print(eval_results) tf.app.run() <file_sep>/jpgReader.py import numpy as np import os from PIL import Image def ReadTiffData(path, rate=0.5): classes_path = [os.path.join(path, x) for x in os.listdir(path)] classes = [int(x.split('. ')[0]) for x in os.listdir(path)] imgs_train = [] labels_train = [] imgs_eval = [] labels_eval = [] for e in range(len(classes_path)): files = [os.path.join(classes_path[e], x) for x in os.listdir(classes_path[e])] for i in range(len(files)): tiff = Image.open(files[i]) tiff = tiff.resize((96, 72), Image.ANTIALIAS) tiff = np.asarray(tiff, np.int32) if i < rate*len(files): imgs_train.append(tiff) labels_train.append(classes[e]-1) else: imgs_eval.append(tiff) labels_eval.append(classes[e]-1) imgs_train = np.asarray(imgs_train, np.float32) labels_train = np.asarray(labels_train, np.int32) shuffle = np.arange(len(imgs_train)) np.random.shuffle(shuffle) imgs_train = imgs_train[shuffle] labels_train = labels_train[shuffle] imgs_eval = np.asarray(imgs_eval, np.float32) labels_eval = np.asarray(labels_eval, np.int32) shuffle = np.arange(len(imgs_eval)) np.random.shuffle(shuffle) imgs_eval = imgs_eval[shuffle] labels_eval = labels_eval[shuffle] print(imgs_train.shape) print(labels_train.shape) print(imgs_eval.shape) print(labels_eval.shape) return imgs_train, labels_train, imgs_eval, labels_eval
a8cddeddebe5a8ada2c7f6925f92736f4be8fbbf
[ "Python" ]
2
Python
somecat1996/Classifier
76f028ba63d0cfe87a4e543d7d57f0f35d05264e
7b1ba36d48d938bfe47433dd89d2080d41c759ba
refs/heads/master
<repo_name>shrikrushnazirape/sppu-se-DSAL-Assignments<file_sep>/code/21286_Assignment03_code.py class matrix: # function for taking single matrix input which takes row and column parameter and return a single 2D matrix def getone(self,r,c): mat=[] for i in range (r): sub_mat=[] for j in range (c): sub_mat.append(int(input())) mat.append(sub_mat) return mat # # function for addition of two matrices def add(self): row=int(input("Enter the no of rows :")) column=int(input("Enter the no of column :")) print("Enter the first matrix ") mat1=self.getone(row, column) print("Enter the second matrix ") mat2=self.getone(row, column) print("Addition of two matrix is") for i in range (row): for j in range (column): print(mat1[i][j]+mat2[i][j], end=" ") print(" ") # function for subtraction of two matrices def sub(self): row=int(input("Enter the no of rows :")) column=int(input("Enter the no of column :")) print("Enter the first matrix") mat1=self.getone(row, column) print("Enter the second matrix") mat2=self.getone(row, column) print("subtraction of two matrix is") for i in range (row): for j in range (column): print(mat1[i][j]-mat2[i][j], end=" ") print(" ") #Function for multiplication of two matrix def multi(self): r1=int(input("Enter the no of rows :")) c1=int(input("Enter the no of columns :")) r2,c2=c1, r1 print("Enter the first matrix") mat1=self.getone(r1,c1) print("Enter the second matrix") mat2=self.getone(r2,c2) print("Multiplication of two marix is") for i in range (r1): for j in range (c2): result=0 for k in range(r2): result += mat1[i][k] * mat2[k][j] print(result, end=" ") print("") #function for transpose of given matrix def trans(self): r=int(input("Enter the No of rows :")) c=int(input("Enter the No of columns :")) matrix=self.getone(r,c) print("you have Entered the matrix :",matrix) print("Transpose of given matrix :") for i in range (c): for j in range (r): print(matrix[j][i], end=" ") print("") s1=matrix() while True: print("_______________________________________________________________") print("1. Addition of two matrices") print("2. subtraction of two matrices") print("3. Multiplication of two matrices") print("4. Transpose of matrix") print("5. Exit ") ch=int(input("Enter your Choice (from 1 to 5) :")) print("_________________________________________________________________") if ch==1: s1.add() elif ch==2: s1.sub() elif ch==3: s1.multi() elif ch==4: s1.trans() elif ch==5: print("Ending the Program") break else: print("!!Wrong Choice!! ") ''' OUTPUT:>>>>> _______________________________________________________________ 1. Addition of two matrices 2. subtraction of two matrices 3. Multiplication of two matrices 4. Transpose of matrix 5. Exit Enter your Choice (from 1 to 5) :1 _________________________________________________________________ Enter the no of rows :3 Enter the no of column :3 Enter the first matrix 1 2 3 4 5 6 7 8 9 Enter the second matrix 1 2 3 4 5 6 7 8 9 Addition of two matrix is 2 4 6 8 10 12 14 16 18 _______________________________________________________________ '''<file_sep>/code/21286_Assignment11_code.cpp /* Name :- <NAME> Assignment:-11 Roll No :- 21286 Batch :- H2 Prb Sta:- Queues are frequently used in computer programming, and a typical example is the creation of a job queue by an operating system. If the operating system does not use priorities, then the jobs are processed in the order they enter the system. Write C++ program for simulating job queue. Write functions to add job and delete job from queue. */ #include<iostream> #include<string> #define max 10 using namespace std; class queue{ int front; int rear; string job[max]; public: queue(){ front = -1; rear = -1; for (int i=0; i<max; i++){ job[i]="Null"; } } bool is_empty(){ if(front == -1 && rear == -1){ return true; } else return false; } bool is_full(){ if(rear == (max -1)){ return true; } else return false; } void enqueue(string str){ if(is_full()){ cout<<"Queue is Full\n"; return ; } else if(is_empty()){ front=0; rear =0; job[rear]=str; } else{ rear +=1; job[rear] = str; } } string dequeue(){ string x="Null"; if (is_empty()){ cout<<"Queue is Empty\n"; return x; } else if(rear == front){ x= job[front]; rear = front = -1; return x; } else{ x= job[front]; job[front]="Null"; front +=1; return x; } } void display(){ if(is_empty()){ cout<<"No Job Present\n"; return; } else { cout<<"-------------------\n All Jobs \n"; int count =1; for (int i=front; i<= rear; i++){ cout<<count<<" "<<job[i]<<"\n"; count ++; } cout<<"-------------------\n \n"; } } }; int main(){ queue q; int ch; string str; do{ cout<<"\n---------------------Menu--------------------------\n"; cout<<"1. Insert a Job\n"; cout<<"2. Delete a Job\n"; cout<<"3. Print all Job\n"; cout<<"0. End the Program\n"; cout<<"Enter the Choice\n"; cout<<"-------------------------------------------------------\n"; cin>>ch; switch(ch){ case 0: break; case 1: cout<<"Enter the job wanted to add\n"; cin>>str; q.enqueue(str); cout<<"Job Added Successfully\n"; break; case 2: q.dequeue(); cout<<"Job Deleted Successfully\n"; break; case 3: q.display(); break; default: cout<<"Entet the correct Option\n"; break; } }while(ch != 0); return 0; }<file_sep>/code/21286_Assignment07_code.cpp /* Name :- <NAME> Assignment no :-7 Problem Statement:- Assignment 7: The ticket booking system of Cinemax theater has to be implemented using C++ program. There are 10 rows and 7 seats in each row. Doubly circular linked list has to be maintained to keep track of free seats at rows. Assume some random booking to start with. Use array to store pointers (Head pointer) to each row. On demand a) The list of available seats is to be displayed b) The seats are to be booked c) The booking can be cancelled. */ #include<iostream> using namespace std; class seat { public: seat* next; seat* prev; int seat; bool available; friend class theater; }; class row{ public: int row_capacity = 7; seat* head,* tail ,* temp; row(){ int i=1; temp = new seat; temp->seat = 1; temp->available=true; tail=head=temp; for(int i=2; i<=row_capacity; i++){ seat *p; p= new seat; p->seat=i; p->available=true; tail->next=p; p->prev=tail; tail=p; tail->next=head; head->prev=tail; } } void display_row(){ seat *col; col = head; while( col->next != head){ if(col->available == true){ cout<<col->seat<<" : UB |"; } else{ cout<<col->seat<<" : B |"; } col = col->next; } if(col->available == true){ cout<<col->seat<<" : UB |"; } else{ cout<<col->seat<<" : B |"; } } void book_seat(int cl){ seat *bk; bk=new seat; bk = head; while( bk->seat != cl){ bk=bk->next; } if(bk->available == false){ cout<<"\n Sorry Seat is not Available \n"; } else{ temp->available=false; cout<<"\n Seat booked \n"<<endl; } } void unbook_seat(int rc){ seat *ro; ro = new seat; ro = head; while( ro->seat != rc){ ro=ro->next; } if(ro->available == true){ cout<<"\n Seat is not Booked yeat \n"; } else{ ro->available = true; cout<<"\n Booking Cancelled Successfully \n"; } } }theater[10]; void display_all_theater(){ for(int i=0; i<10; i++){ cout<<"\n Row No. :- "<<i+1<<"|"; theater[i].display_row(); } } void seat_book_in_theater(){ int row_no, col_no; cout<<"\nEnter the No of Row :"; cin>>row_no; if(row_no > 10 && row_no <1){ cout<<"Wrong Row No input "; } cout<<"\n Enter the No of Seat want to Book :"; cin>>col_no; if(col_no > 7 && col_no <1){ cout<<"Wrong column No input "; } theater[row_no-1].book_seat(col_no); } void seat_unbook_in_theater(){ int row_no, col_no; cout<<"\nEnter the No of Row :"; cin>>row_no; if(row_no > 10 && row_no <1){ cout<<"Wrong Row No input "; } cout<<"\n Enter the No of Seat want to Book :"; cin>>col_no; if(col_no > 7 && col_no <1){ cout<<"Wrong column No input "; } theater[row_no-1].unbook_seat(col_no); } int main(){ int option; do { cout << "\nWhat operation do you want to perform? Select Option number. Enter 0 to exit." << endl; cout << "1. The list of all available seats" << endl; cout << "2. The available seat in a row" << endl; cout << "3. Book a Seat" << endl; cout << "4. Cancel Booking" << endl; cin >> option; switch (option) { case 0: break; case 1: cout<<"Printing all available seat"<<endl; display_all_theater(); break; case 2: int row_search_no; cout<<"Enter the no of row you want to search :"<<endl; cin>>row_search_no; cout<<"\n---------------------------------------\n"; cout<<"Available seat in row no "<<endl; theater[row_search_no-1].display_row(); cout<<"\n---------------------------------------\n"; break; case 3: seat_book_in_theater(); break; case 4: seat_unbook_in_theater(); break; default: cout << "Enter Proper Option number " << endl; } } while (option != 0); return 0; } /* output:- What operation do you want to perform? Select Option number. Enter 0 to exit. 1. The list of all available seats 2. The available seat in a row 3. Book a Seat 4. Cancel Booking 1 Printing all available seat Row No. :- 1|1 : UB |2 : UB |3 : UB |4 : UB |5 : UB |6 : UB |7 : UB | Row No. :- 2|1 : UB |2 : UB |3 : UB |4 : UB |5 : UB |6 : UB |7 : UB | Row No. :- 3|1 : UB |2 : UB |3 : UB |4 : UB |5 : UB |6 : UB |7 : UB | Row No. :- 4|1 : UB |2 : UB |3 : UB |4 : UB |5 : UB |6 : UB |7 : UB | Row No. :- 5|1 : UB |2 : UB |3 : UB |4 : UB |5 : UB |6 : UB |7 : UB | Row No. :- 6|1 : UB |2 : UB |3 : UB |4 : UB |5 : UB |6 : UB |7 : UB | Row No. :- 7|1 : UB |2 : UB |3 : UB |4 : UB |5 : UB |6 : UB |7 : UB | Row No. :- 8|1 : UB |2 : UB |3 : UB |4 : UB |5 : UB |6 : UB |7 : UB | Row No. :- 9|1 : UB |2 : UB |3 : UB |4 : UB |5 : UB |6 : UB |7 : UB | Row No. :- 10|1 : UB |2 : UB |3 : UB |4 : UB |5 : UB |6 : UB |7 : UB | What operation do you want to perform? Select Option number. Enter 0 to exit. 1. The list of all available seats 2. The available seat in a row 3. Book a Seat 4. Cancel Booking 3 Enter the No of Row :1 Enter the No of Seat want to Book :1 Seat booked What operation do you want to perform? Select Option number. Enter 0 to exit. 1. The list of all available seats 2. The available seat in a row 3. Book a Seat 4. Cancel Booking 3 Enter the No of Row :1 Enter the No of Seat want to Book :1 Sorry Seat is not Available What operation do you want to perform? Select Option number. Enter 0 to exit. 1. The list of all available seats 2. The available seat in a row 3. Book a Seat 4. Cancel Booking 4 Enter the No of Row :1 Enter the No of Seat want to Book :1 Booking Cancelled Successfully What operation do you want to perform? Select Option number. Enter 0 to exit. 1. The list of all available seats 2. The available seat in a row 3. Book a Seat 4. Cancel Booking 2 Enter the no of row you want to search : 1 --------------------------------------- Available seat in row no 1 : UB |2 : UB |3 : UB |4 : UB |5 : UB |6 : UB |7 : UB | --------------------------------------- What operation do you want to perform? Select Option number. Enter 0 to exit. 1. The list of all available seats 2. The available seat in a row 3. Book a Seat 4. Cancel Booking */ <file_sep>/code/21286_Assignment05_code.py import math class sort: #function to determine length of given array def getlen(self, lst): lst.append(-1) i=0 while (lst[i] != -1): i+=1 lst.remove(-1) return i # function to perform insertion sort def insertion_sort(self,lst): i,key,j=0,0,0 n=self.getlen(lst) for i in range (1,n): key=lst[i] j=i-1 while (j>=0 and key < lst[j]): lst[j+1]=lst[j] j-=1 lst[j+1]=key print("----------------Insertion Sort------------") print("Top 5 Scores") for i in range (-1,-6,-1): print(lst[i]) print("------------------------------------------") #function for swap def shell_sort(self, lst): n=self.getlen(lst) gap=n//2 while (gap>0): for i in range (gap, n): temp=lst[i] j=i while j >= gap and arr[j-gap] >temp: lst[j] = arr[j-gap] j -= gap arr[j] = temp gap =gap//2 print("-----------Shell Sort-------------------") print("Top 5 Scores") for i in range (-1,-6,-1): print(lst[i]) print("------------------------------------------") # Taking the input of the user t=int(input("Enter the Total No of student in class ")) arr=[] print("Enter the Scores") for i in range (t): arr.append(float(input())) s1=sort() while True: print("1. Insertion Sort") print("2. Shell Sort") print("3. Exit\n") ch=int(input("Enter your Choice (from 1 to 3) :")) if ch==1: s1.insertion_sort(arr) elif ch==2: s1.shell_sort(arr) elif ch==3: break else: ("!!Wrong Choice!! ") ''' OUTPUT Enter the Total No of student in class 7 Enter the Scores 35.25 65.45 87.35 98.45 100.00 45.25 87.15 1. Insertion Sort 2. Shell Sort 3. Exit Enter your Choice (from 1 to 3) :1 ----------------Insertion Sort------------ Insertion Sort Top 5 Scores 100.0 98.45 87.35 87.15 65.45 ------------------------------------------ '''<file_sep>/code/21286_Assignment12_code.cpp /* Name :- <NAME> Assignment:-12 Roll No :- 21286 Batch :- H2 Prb Sta:- */ <file_sep>/code/21286_Assignment10_code.cpp /* Name :- <NAME> Assigment No :- 10 Roll no :- 21286 Batch :- H2 problem statement :- Implement C++ program for expression conversion as infix to postfix and its evaluation using stack based on given conditions: 1. Operands and operator, both must be single character. 2. Input Postfix expression must be in a desired format. 3. Only '+', '-', '*' and '/ ' operators are expected. ​ */ #include <iostream> #include <string.h> using namespace std; class stack{ char stack_array[30]; int top=-1; int n=30; public: char top_element(){ return stack_array[top]; } bool isempty(){ if(top == -1){ return true; } else return false; } void pop(){ if(top == -1){ cout<<"Stack Underflow \n"; } else{ top --; } } void push(char c){ if(top >= n-1){ cout<<"Stack Overflow \n"; } else{ top ++; stack_array[top] = c; } } }s; int precedence( char c){ if(c == '+' || c == '-'){ return 1; } else if(c == '*' || c == '/'){ return 2; } else if(c == '^'){ return 3; } else{ return -1; } } bool is_Operator(char c){ if(c=='+' || c=='-' || c=='*' || c=='/' || c=='^'){ return true; } else{ return false; } } string InfixToPostfix(string infix){ string postfix; for (int i=0; i<infix.length(); i++){ //condition if the char is operend if((infix[i] >= 'a' && infix[i] <='z')||(infix[i] >= 'A' && infix[i] <='Z')){ postfix+=infix[i]; } else if(infix[i] == '('){ s.push(infix[i]); } else if(infix[i] == ')'){ while((s.top_element() != '(') && (!s.isempty())){ char temp = s.top_element(); postfix += temp; s.pop(); } if(s.top_element() == '('){ s.pop(); } } else if(is_Operator(infix[i])){ if(s.isempty()){ s.push(infix[i]); } else{ if(precedence(infix[i])> precedence(s.top_element())){ s.push(infix[i]); } else{ while((!s.isempty()) && (precedence(infix[i])<= precedence(s.top_element()))){ postfix+=s.top_element(); s.pop(); } s.push(infix[i]); } } } } while ( !s.isempty()){ postfix+=s.top_element(); s.pop(); } return postfix; } int main(){ string s1; while (true){ cout<<"Enter the string :"; cin>>s1; cout<<"\n *******************************************\n"; cout<<"Infix Exp:- "<<s1<<endl; cout<<"Postfix Exp :- "<<InfixToPostfix(s1)<<endl; cout<<"\n *******************************************\n"; } return 0; } /* OUTPUT:- Enter the string :a+b*(c^d-e)^(f+g*h)-i ******************************************* Infix Exp:- a+b*(c^d-e)^(f+g*h)-i Postfix Exp :- abcd^e-fgh*+^*+i- ******************************************* Enter the string :X*Y/Z+P*Q-R ******************************************* Infix Exp:- X*Y/Z+P*Q-R Postfix Exp :- XY*Z/PQ*+R- ******************************************* */<file_sep>/code/list.cpp //============================================================================ // Name : LinkedList_practice_assignment.cpp // Author : <NAME> // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; class Node{ int data; Node *next; public: Node(){ data=0; next=NULL; } Node(int k){ data = k; next = NULL; } friend class LinkedList; }; class LinkedList{ public: Node *head; LinkedList(){ head =NULL; } void addAtEnd(int k); void addAtBegin(int k); void addBefore(int before, int data); void addAfter(int after, int data); void addAtLocation(int add, int data); void deleteByKey(int key); void printAllList(); void printReverse(Node *temp); void makeListReverse(); void unionOfList(LinkedList a, LinkedList b); void intersectionOfList(LinkedList a, LinkedList b); bool is_present(int key); void conList(LinkedList a, LinkedList b); }; void LinkedList::addAtEnd(int k){ Node *NewNode = new Node(k); if(head == NULL){ head = NewNode; } else{ Node *temp2 = head; while(temp2->next != NULL){ temp2 = temp2->next; } temp2->next=NewNode; } } void LinkedList::addAtBegin(int k){ Node *NewNode = new Node(k); if(head == NULL){ head = NewNode; } else{ NewNode->next = head; head = NewNode; } } void LinkedList::addBefore(int before, int data){ Node *current = head; Node *previous = NULL; while(current->data != before){ previous = current; current = current->next; } Node *NewNode= new Node(data); NewNode->next = current; previous->next = NewNode; } void LinkedList::addAfter(int after, int data){ Node *current = head; while(current-> data != after){ current=current->next; } Node *NewNode=new Node(data); NewNode->next = current->next; current->next = NewNode; } void LinkedList::addAtLocation(int add, int data){ Node *temp = head; while(temp != NULL){ if(temp->data == add){ temp->data =data; cout<<"modified at location\n"; } temp = temp->next; } cout<<"Address not found\n"; } void LinkedList::deleteByKey(int k){ if (head == NULL) { cout << "Singly Linked List already Empty. Can't delete" << endl; } else if (head != NULL) { if ( head-> data == k) { head = head -> next; cout << "Node UNLINKED with value : " << k << endl; } else { Node * temp = NULL; Node * prevptr = head; Node * currentptr = head -> next; while (currentptr != NULL) { if (currentptr -> data == k) { temp = currentptr; currentptr = NULL; } else { prevptr = prevptr -> next; currentptr = currentptr -> next; } } if (temp != NULL) { prevptr -> next = temp -> next; cout << "Node UNLINKED with value : " << k << endl; } else { cout << "Node Doesn't exist with value : " << k << endl; } } } } void LinkedList::printAllList(){ if(head == NULL){ cout<<"nothing to show \n"; } else{ Node *temp = head; while(temp != NULL){ cout<<temp->data<<"\t"; temp=temp->next; } cout<<endl; } } void LinkedList::printReverse(Node *temp){ if(temp==NULL){ return; } LinkedList::printReverse(temp->next); cout<<temp->data<<"\t"; } void LinkedList::makeListReverse(){ Node *current, *previous, *next; current = head; previous =NULL; next = NULL; while(current != NULL){ next=current->next; current->next = previous; previous = current; current = next; } head=previous; } bool LinkedList::is_present(int key){ bool check=false; if(head == NULL){ return false; } else{ Node *temp=head; while (temp != NULL){ if(temp->data == key){ check=true; } temp=temp->next; } return check; } } void LinkedList::unionOfList(LinkedList a, LinkedList b){ Node *tempa = a.head; Node *tempb = b.head; while (tempa != NULL){ if(is_present(tempa->data)==false){ addAtEnd(tempa->data); } tempa=tempa->next; } while (tempb != NULL){ if(is_present(tempb->data)==false){ addAtEnd(tempb->data); } tempb= tempb->next; } } void LinkedList::conList(LinkedList a, LinkedList b){ Node *tempa = a.head; Node *tempb = b.head; while (tempa != NULL){ addAtEnd(tempa->data); tempa=tempa->next; } while (tempb != NULL){ addAtEnd(tempb->data); tempb= tempb->next; } } void intersectionOfList(LinkedList a, LinkedList b){ // Node *temp=a.head; // while(temp != NULL){ // if(b.is_present(temp->data)){ // if(a.is_present(temp->data) == false){ // addAtEnd(temp->data); // } // } // temp=temp->next; // } } int main() { LinkedList l; int location, data; int ch; return 0; } <file_sep>/code/21286_Assignment02_code.py class string: #function to determine the longest string in the two string def longest_length(self): string1=str(input("Enter the first string :")) string2=str(input("Enter the second string :")) if(self.getlength(string1)>self.getlength(string2)): print("The Largest String is ", string1, "with the length ", self.getlength(string1)) else: print("The Largest String is ", string2, "with the length ", self.getlength(string2)) #function to obtain freq of char def char_freq_op(self): string=str(input("Enter the string :")) char=str(input("Enter the Char :")) freq=self.char_freq(string, char) print("frequency of char", char, "in the string", string, "is ", freq) # function to check is the string is palindrome or not def ispalindrome(self): string=str(input("Enter the string :")) len_of_string=self.getlength(string) ans="Pallindrome" for i in range (int(len_of_string/2)): if(string[i] != string [(0-i)-1]): ans="Not Pallindrome" break print("Given string is", ans) # function to find first occurance of substring in the string def first_occur(self): string1=str(input("Enter the string :")) substring=str(input("Enter the Substring :")) len1=self.getlength(string1) len2=self.getlength(substring) occur=[] for i in range (len1-len2+1): if string1[i: (i+len2)]== substring: occur.append(i) print("First occurance of" ,substring, "in the ",string1, " at the index", occur[0]) # function to find all occurrences of the substring in the string def alloccur(self): string1=str(input("Enter the string :")) substring=str(input("Enter the Substring :")) len1=self.getlength(string1) len2=self.getlength(substring) occur=[] for i in range (len1-len2+1): if string1[i: (i+len2)]== substring: occur.append(i) print("Totle occurrences of ", substring, "in the ", string1, "are",len(occur)," at index ", occur) # -------------function for returning the length of given string_____________ def getlength(self,str): count=0 while str[count:]: count+=1 return count # -------------function for determining the frequency of given char in the string def char_freq(self, string, char): chr=char[0] len_of_string=self.getlength(string) count=0 for i in range (len_of_string): if(string[i]==chr): count+=1 return count s1=string() # main program for menu and choice while (True): choice=0 print("____________________________________________________________________") print(" Menu For the Program") print("1. To display the word of longest length") print("2. To display frequency of charecter") print("3. To determine palindrome or not") print("4. To display index of first appeerence of substring") print("5. To display count of occurrence of each word in given string") print("6. To End the program") choice = int(input("Enter Choice - ")) print("______________________________________________________________________") if choice==1 : s1.longest_length() elif choice==2 : s1.char_freq_op() elif choice==3 : s1.ispalindrome() elif choice==4: s1.first_occur() elif choice ==5: s1.alloccur() elif choice ==6: print("Ending the Program") break else: print("Enter the Correct Choice") '''OUTPUT >>> ____________________________________________________________________ Menu For the Program 1. To display the word of longest length 2. To display frequency of charecter 3. To determine palindrome or not 4. To display index of first appeerence of substring 5. To display count of occurrence of each word in given string 6. To End the program Enter Choice - 1 ______________________________________________________________________ Enter the first string :shrikrushna Enter the second string :krushna The Largest String is shrikrushna with the length 11 ____________________________________________________________________ '''<file_sep>/code/21286_Assignment06_code.py class sort: #recursive call for the quick sort function def quickSort(self,arr,low,high): if low < high: pi = self.part(arr,low,high) self.quickSort(arr, low, pi-1) self.quickSort(arr, pi+1, high) #function for sorting the array left to pivote and right to pivote and return pivote index def part(self,arr,low,high): pindex = low-1 pivot = arr[high] for j in range(low , high): if arr[j] < pivot: pindex +=1 arr[pindex],arr[j] = arr[j],arr[pindex] arr[pindex+1],arr[high] = arr[high],arr[pindex+1] return ( pindex +1 ) #function for printing top 5 score def topper(self, lst): print("------------------------------------------") print("Top 5 Scores") for i in range (-1,-6,-1): print(lst[i]) print("------------------------------------------") t=int(input("Enter the total no of ")) lst=[] for i in range (t): lst.append(float(input())) s1=sort() while True: print("1. Sort Numbers using the quick sort") print("2. Exit\n") ch=int(input("Enter your Choice (from 1 to 2) :")) if ch==1: print("Before Sorting",lst) s1.quickSort(lst,0,t-1) print("After Sorting",lst) s1.topper(lst) elif ch==2: break else: print("!!Wrong Choice!! ") '''Output: Enter the total no of student5 10.25 45.32 14.32 56.32 11.12 1. Sort Numbers using the quick sort 2. Exit Enter your Choice (from 1 to 2) :1 Before Sorting [10.25, 45.32, 14.32, 56.32, 11.12] After Sorting [10.25, 11.12, 14.32, 45.32, 56.32] ------------------------------------------ Top 5 Scores 56.32 45.32 14.32 11.12 10.25 ------------------------------------------ 1. Sort Numbers using the quick sort 2. Exit '''<file_sep>/code/21286_Assignment04_code.py class sort: array=[] totle_student=0 def __init__(self,list,n): self.array=list self.totle_student=n #function to perform linear search def linear_search(self,key): count=0 for i in range (self.totle_student): if(self.array[i]==key): count+=1 if(count==0): print("not attended the training program") else: print(" attended the training program") #function to perform sentinal search def sen_search(self,key): lst=self.array lst.append(99) count=0 i=0 while (lst[i]!=99): if(lst[i]==key): count+=1 i+=1 if(count==0): print("Not attended the training program") else: print("attended the training program") #function to perform binary search def bin_search(self,key): ls=self.array n=self.totle_student mid, low, high = 0, 0, n - 1 while low <= (high): mid = low + (high - low) // 2 if ls[mid] == key: print("Attended the training program") break elif ls[mid] < key: low = mid + 1 else: high = mid - 1 else: print("Not attended the training program") # function in fib search for returning the (m-2)th element in the fib series def rindex(self,n): f2 = 0 f1 = 1 f = 1 index = 0 while (f < n): f2 = f1 f1 = f f = f1 + f2 index = f1 return index # function for cheaking is the key element is present in the list or not def fibonacci(self,ls, n, key): flag, first, last = 0, 0, n - 1 while (flag != 1 and first <= last): index = self.rindex(n) if (key == ls[index + first]): flag = 1 break elif (key > ls[index + first]): first = first + index + 1 else: last = first + index - 1 n = last - first + 1 if (flag == 1): print(" attended the training program") else: print("Not attended the training program") # actual function of fib search which handles the user input def fib_search(self,key): ls=self.array n=self.totle_student self.fibonacci(ls,n,key) # program for taking input from the user n=int(input("Enter the no of student who attended the training program :")) lst=[] print("Enter the roll no of student") for i in range (n): lst.append(int(input())) key=int(input("Enter the Roll no you want to search")) searching=sort(lst, n) while True: print("_________________________________________________________________") print("1. Linear search") print("2. Sentinel search") print("3. Binary search") print("4. Fibonacci search ​") print("5. Exit ") ch=int(input("Enter your Choice (from 1 to 5) :")) print("_________________________________________________________________") if ch==1: searching.linear_search(key) elif ch==2: searching.sen_search(key) elif ch==3: searching.bin_search(key) elif ch==4: searching.fib_search(key) elif ch==5: print("Ending the Program") break else: print("!!Wrong Choice!! ") '''OUTPUT:- Enter the no of student who attended the training program :5 Enter the roll no of student 1 2 3 4 5 Enter the Roll no you want to search5 _________________________________________________________________ 1. Linear search 2. Sentinel search 3. Binary search 4. Fibonacci search ​ 5. Exit Enter your Choice (from 1 to 5) :4 _________________________________________________________________ attended the training program _________________________________________________________________ '''<file_sep>/code/21286_Assignment08_code.cpp /* Name :- <NAME> Roll No :- 21286 Assignment :- Grpup C , assigment 8 Problem statement :- Second year Computer Engineering class, set A of students like Vanilla Ice-cream and set B of students like butterscotch ice-cream. Write C++ program to store two sets using linked list. compute and display- a) Set of students who like both vanilla and butterscotch b) Set of students who like either vanilla or butterscotch or not both c) Number of students who like neither vanilla nor butterscotch */ #include<string.h> #include<iostream> using namespace std; class student{ int roll_no; string name; student *link; public: student(){ roll_no=0; name="student name"; link=NULL; } student(int roll,string n){ roll_no=roll; name=n; link=NULL; } friend class set; }; class set{ int total_in_set; student *head; public: set(){ head=NULL; } //adding node at the end of the linked list void create_student_node(int roll, string nm){ student *temp=new student(roll, nm); if(head == NULL){ head= temp; } else{ student *temp2=head; while(temp2->link != NULL){ temp2=temp2->link; } temp2->link=temp; } } //printing all members of the linked list void print_all_member(){ if(head == NULL){ cout<<"List is Empty No members to Show"<<endl; } student *temp=head; cout<<"------------------------------------------"<<endl; cout<<"Roll_no"<<"\t|\t"<<"Name of student"<<endl; cout<<"------------------------------------------"<<endl; while (temp != NULL){ cout<<temp->roll_no<<"\t|\t"<<temp->name<<endl; temp=temp->link; } } //function to create set; void create_set(){ int n,ro; string str; cout<<"Enrer the total no of student :"; cin>>n; total_in_set=n; for (int i=0; i<n; i++){ cout<<"Enter roll no :"; cin>>ro; cout<<"Enter name :"; cin>>str; create_student_node(ro,str); } } //function to check presence of emement bool is_present(int r){ bool check=false; if(head == NULL){ return false; } else{ student *temp=head; while (temp != NULL){ if(temp->roll_no == r){ check=true; } temp=temp->link; } return check; } } //function to calculate length of linked list int getlen(){ int count=0; student *temp=head; while (temp !=NULL){ count+=1; temp=temp->link; } return count; } // function to find union of two sets void union_set(set a, set b){ student *t1 = a.head; student *t2 = b.head; while (t1 != NULL){ if(is_present(t1->roll_no)==false){ create_student_node(t1->roll_no, t1->name); } t1=t1->link; } while (t2 != NULL){ if(is_present(t2->roll_no)==false){ create_student_node(t2->roll_no, t2->name); } t2=t2->link; } } //fuction to find intersection of two set void intersection_set(set a, set b){ student *temp=a.head; while(temp != NULL){ if(b.is_present(temp->roll_no)){ if(is_present(temp->roll_no) == false){ create_student_node(temp->roll_no, temp->name); } } temp=temp->link; } } //function to determine difference of the two sets; void diff(set a, set b){ student *temp=a.head; while (temp != NULL){ if(b.is_present(temp->roll_no) == false){ if(is_present(temp->roll_no) == false){ create_student_node(temp->roll_no, temp->name); } } temp=temp->link; } } // function to determine symetric difference of the two sets (a union b )- (a intersection b) void sym_diff(set a, set b){ set union_s, inter_s; union_s.union_set(a,b); inter_s.intersection_set(a,b); diff(union_s,inter_s); } }; int main(){ set comp_student, vanila , butterscotch, result1, result2, result3; while (true){ int choice; cout<<"-------------------------------------------------------------------------"<<endl; cout<<"1. Add Second Year Student"<<endl; cout<<"2. Add Student Who like Vanilla Ice-cream"<<endl; cout<<"3. Add a student who like butterscotch ice-cream"<<endl; cout<<"4. Display students who like both vanilla and butterscotch"<<endl; cout<<"5. Display students who like either vanilla or butterscotch or not both"<<endl; cout<<"6. Display students who like neither vanilla nor butterscotch"<<endl; cout<<"7. Exit"<<endl; cout<<"-------------------------------------------------------------------------"<<endl; cout<<"Enter Your Choice "; cin>>choice; if (choice ==1){ int t; cout<<"Enter Total no of student : "; cin>>t; for (int i=0; i<t; i++){ int roll; string name; cout<<"Enter the Roll No of student : "; cin>>roll; cout<<"Enter the Name of student : "; cin>>name; comp_student.create_student_node(roll, name); } } else if(choice ==2){ int v; cout<<"Enter No of Student who like Vanila Ice-Cream : "; cin>>v; for (int j=0; j<v; j++){ int roll; string name; cout<<"Enter the Roll No of student : "; cin>>roll; cout<<"Enter the Name of student : "; cin>>name; vanila.create_student_node(roll, name); if(comp_student.is_present(roll) == false){ comp_student.create_student_node(roll, name); } } } else if (choice ==3) { int b; cout<<"Enter No of Student who like butterscotch Ice-Cream : "; cin>>b; for (int k=0; k<b; k++){ int roll; string name; cout<<"Enter the Roll No of student : "; cin>>roll; cout<<"Enter the Name of student : "; cin>>name; butterscotch.create_student_node(roll, name); if(comp_student.is_present(roll) == false){ comp_student.create_student_node(roll, name); } } } else if (choice ==4){ result1.intersection_set(vanila,butterscotch); cout<<"---------------------------------------------------"<<endl; cout<<"Student Who Likes Both Vanila as well as Butterscotch"<<endl; cout<<"---------------------------------------------------"<<endl; result1.print_all_member(); } else if (choice ==5){ result2.sym_diff(vanila, butterscotch); cout<<"---------------------------------------------------"<<endl; cout<<"Student Who Likes either vanilla or butterscotch but not both"<<endl; cout<<"---------------------------------------------------"<<endl; result2.print_all_member(); } else if (choice ==6){ set temp_union; temp_union.union_set(vanila,butterscotch); result3.diff(comp_student,temp_union); cout<<"---------------------------------------------------"<<endl; cout<<"Student Who Likes neither vanilla nor butterscotch"<<endl; cout<<"---------------------------------------------------"<<endl; result3.print_all_member(); } else if(choice ==7){ break; } else{ cout<<"Wrong choice"; } } return 0; } /* OUTPUT:- 1. Add Second Year Student 2. Add Student Who like Vanilla Ice-cream 3. Add a student who like butterscotch ice-cream 4. Display students who like both vanilla and butterscotch 5. Display students who like either vanilla or butterscotch or not both 6. Display students who like neither vanilla nor butterscotch 7. Exit ------------------------------------------------------------------------- Enter Your Choice 1 Enter Total no of student : 6 Enter the Roll No of student : 1 Enter the Name of student : shrikrushna Enter the Roll No of student : 2 Enter the Name of student : suyash Enter the Roll No of student : 3 Enter the Name of student : shlok Enter the Roll No of student : 4 Enter the Name of student : sahil Enter the Roll No of student : 5 Enter the Name of student : utkarsh Enter the Roll No of student : 6 Enter the Name of student : sid ------------------------------------------------------------------------- 1. Add Second Year Student 2. Add Student Who like Vanilla Ice-cream 3. Add a student who like butterscotch ice-cream 4. Display students who like both vanilla and butterscotch 5. Display students who like either vanilla or butterscotch or not both 6. Display students who like neither vanilla nor butterscotch 7. Exit ------------------------------------------------------------------------- Enter Your Choice 1 Enter Total no of student : 1 Enter the Roll No of student : 7 Enter the Name of student : mota-bhai ------------------------------------------------------------------------- 1. Add Second Year Student 2. Add Student Who like Vanilla Ice-cream 3. Add a student who like butterscotch ice-cream 4. Display students who like both vanilla and butterscotch 5. Display students who like either vanilla or butterscotch or not both 6. Display students who like neither vanilla nor butterscotch 7. Exit ------------------------------------------------------------------------- Enter Your Choice 2 Enter No of Student who like Vanila Ice-Cream : 3 Enter the Roll No of student : 1 Enter the Name of student : shrikrushna Enter the Roll No of student : 2 Enter the Name of student : suyash Enter the Roll No of student : 3 Enter the Name of student : shlok ------------------------------------------------------------------------- 1. Add Second Year Student 2. Add Student Who like Vanilla Ice-cream 3. Add a student who like butterscotch ice-cream 4. Display students who like both vanilla and butterscotch 5. Display students who like either vanilla or butterscotch or not both 6. Display students who like neither vanilla nor butterscotch 7. Exit ------------------------------------------------------------------------- Enter Your Choice 3 Enter No of Student who like butterscotch Ice-Cream : 3 Enter the Roll No of student : 3 Enter the Name of student : shlok Enter the Roll No of student : 4 Enter the Name of student : sahil Enter the Roll No of student : 5 Enter the Name of student : utkarsh ------------------------------------------------------------------------- 1. Add Second Year Student 2. Add Student Who like Vanilla Ice-cream 3. Add a student who like butterscotch ice-cream 4. Display students who like both vanilla and butterscotch 5. Display students who like either vanilla or butterscotch or not both 6. Display students who like neither vanilla nor butterscotch 7. Exit ------------------------------------------------------------------------- Enter Your Choice 4 --------------------------------------------------- Student Who Likes Both Vanila as well as Butterscotch --------------------------------------------------- ------------------------------------------ Roll_no | Name of student ------------------------------------------ 3 | shlok ------------------------------------------------------------------------- 1. Add Second Year Student 2. Add Student Who like Vanilla Ice-cream 3. Add a student who like butterscotch ice-cream 4. Display students who like both vanilla and butterscotch 5. Display students who like either vanilla or butterscotch or not both 6. Display students who like neither vanilla nor butterscotch 7. Exit ------------------------------------------------------------------------- Enter Your Choice 5 --------------------------------------------------- Student Who Likes either vanilla or butterscotch but not both --------------------------------------------------- ------------------------------------------ Roll_no | Name of student ------------------------------------------ 1 | shrikrushna 2 | suyash 4 | sahil 5 | utkarsh ------------------------------------------------------------------------- 1. Add Second Year Student 2. Add Student Who like Vanilla Ice-cream 3. Add a student who like butterscotch ice-cream 4. Display students who like both vanilla and butterscotch 5. Display students who like either vanilla or butterscotch or not both 6. Display students who like neither vanilla nor butterscotch 7. Exit ------------------------------------------------------------------------- Enter Your Choice 6 --------------------------------------------------- Student Who Likes neither vanilla nor butterscotch --------------------------------------------------- ------------------------------------------ Roll_no | Name of student ------------------------------------------ 6 | sid 7 | mota-bhai ------------------------------------------------------------------------- */<file_sep>/code/21286_Assignment09_code.cpp /* Name :- <NAME> Assigment No :- 9 Problem Statement :- In any language program mostly syntax error occurs due to unbalancing delimiter such as { }, [ ] and ( ). Write C++ program using stack to check whether given expression is well parenthesized or not. ​ */ #include<iostream> #include <string.h> using namespace std; const int size=15; class stack_exp{ int top; char stack_array[size]; public: stack_exp(){ top = -1; } void push(char chr){ if(!is_full()){ top +=1; stack_array[top]= chr; } } char pop(){ if(!is_empty()){ char ch = stack_array[top]; top -=1; return ch; } else return '\0'; } bool is_empty(){ if(top == -1){ return true; } else{ return false; } } bool is_full(){ if(top == 15){ return true; } else{ return false; } } void check(){ cout<<"Enter the String you want to check :"<<endl; string str; char ch; bool result=true; cin>>str; int i=0; while(str[i] != '\0'){ if(str[i]=='(' || str[i]=='['|| str[i]=='{'){ push(str[i]); } if(str[i]==')' || str[i]==']'|| str[i]=='}'){ if(is_empty()){ result=false; break; } ch=pop(); if((str[i]==')'&& ch!='(')||(str[i]==']'&& ch!='[')|| (str[i]=='}' && ch!='{') ){ result=false; break; } } i++; } if(is_empty()==true && result == true){ cout<<"_________________________"<<endl; cout<<"Well parenthesized"<<endl; cout<<"_________________________"<<endl; } else{ cout<<"_________________________"<<endl; cout<<"Not Parenthesized"<<endl; cout<<"_________________________"<<endl; } } }s1; int main(){ int choice; do{ cout<<"enter 0 to break "<<endl; cout<<"Enter 1 to Test String "<<endl; cin>>choice; if(choice ==1){ s1.check(); } }while(choice !=0); return 0; } /* OUTPUT:- enter 0 to break Enter 1 to Test String 1 Enter the String you want to check : {ab}(c+d)(a(bc)) _________________________ Well parenthesized _________________________ enter 0 to break Enter 1 to Test String 1 Enter the String you want to check : (()))) _________________________ Not Parenthesized _________________________ */<file_sep>/code/21286_Assignment01_code.py class set: def __init__(self,comp_student,cricket_playing, badminton_playing, football_playing): self.comp_student=comp_student self.badminton_playing=badminton_playing self.football_playing=football_playing #_________________________functin for cheak is the element is present in the list or not (repacement of " in or " "not in") def pin(self,lst, elem): flag= False for i in range (len(lst)): if(lst[i]==elem): flag=True return flag #_____________________________function to find the intersection of the two set def intersection(self,lst1,lst2): lst3=[] for i in range (len(lst1)): for j in range (len(lst2)): if(lst1[i]==lst2[j]): lst3.append(lst1[i]) return lst3 # ---------------------------------function to find the union of the two set def union(self,list1, list2): list3=list1.copy() for i in range (len(list2)): if(self.pin(list2,list2[i])==False): list3.append(list2[i]) return list3 #-----------------------------------Function to find the Difference to the two set def diff(self,lst1, lst2): lst3=[] for i in range (len(lst1)): if (self.pin(lst2, lst1[i])== False): lst3.append(lst1[i]) return(lst3) # ------------------------------------function for finding symetric difference which def diff2(self,lst1,lst2): a1=self.union(lst1, lst2) a2=self.intersection(lst1, lst2) D1=self.diff(a1,a2) return D1 # function for finding the parameters in the assignment # 1......List of students who play both cricket and badminton. def cricket_badminton(self): lst1=cricket_playing lst2=badminton_playing print("no of student who play both cricket and badminton",len(self.intersection(lst1, lst2))) print("list of student who play both cricket and badminton",self.intersection(lst1, lst2)) return len(self.intersection(lst1, lst2)) # 2..........List of students who play either cricket or badminton but not both. def only_cricket_o_badminton(self): lst1=cricket_playing lst2=badminton_playing print("no of student who play either cricet or badminton but not both",len(self.diff2(lst1, lst2))) print("list of student who play either cricet or badminton but not both",self.diff2(lst1, lst2)) return len(self.diff2(lst1, lst2)) # 3........ Function for finding Number of students who play neither cricket nor badminton def no_N_cricket_badminton(self): lst1=comp_student lst2=cricket_playing lst3=badminton_playing lst4=self.diff(lst1,self.union(lst2,lst3)) print(" no of students who play neither cricket nor badminton is : ",len(lst4)) print("\n\nList of students who play neither cricket nor badminton is : ",lst4) return len(lst4) # 4............ Number of students who play cricket and football but not badminton def no_cricket_badminton_N_football(self): lst1=cricket_playing lst2=football_playing lst3=badminton_playing lst4 = self.diff(self.intersection(lst1,lst2),lst3) print("no of student who play cricket and football but not badminton :",len(lst4)) print("\n\nList of students who play cricket and football but not badminton is : ",lst4) return len(lst4) # ____________________Function for taking Input from the User ______________________________________________ comp_student=[] cricket_playing=[] badminton_playing=[] football_playing=[] print("Totle no of student in comp department") n_comp_department=int(input()) print('Enter the name of student(each on new line)') for i in range (n_comp_department): comp_student.append(input()) print("No of student who play cricket") n_cricket=int(input()) print("enter name of student who play cricket(each on new line)") for i in range (n_cricket): cricket_playing.append(input()) print("No of student who play badminton") n_badminton=int(input()) print("enter name of student who play badminton(each on new line)") for i in range (n_badminton): badminton_playing.append(input()) print("No of student who play football") n_football=int(input()) print("enter name of student who play football(each on new line)") for i in range (n_football): football_playing.append(input()) print("_____________________________________________________________") print("no of student in comp department", n_comp_department) print(comp_student) print("no of student who play cricket",n_cricket) print(cricket_playing) print("no of student who play badminton",n_badminton) print(badminton_playing) print("no of student who play football",n_football) print(football_playing) print("______________________________________________________________") # ________________________________________________Main function for the menu driven program s1=set(comp_student,cricket_playing,badminton_playing,football_playing) while True: print("_______________________________________________________________") print("1. both cricket and badminton") print("2. either cricket or badminton but not both") print("3. neither cricket nor badminton") print("4. cricket and football but not badminton") print("5. Exit\n") ch=int(input("Enter your Choice (from 1 to 5) :")) print("_________________________________________________________________") if ch==1: ( s1.cricket_badminton()) elif ch==2: ( s1.only_cricket_o_badminton()) elif ch==3: ( s1.no_N_cricket_badminton()) elif ch==4: ( s1.no_cricket_badminton_N_football()) elif ch==5: break else: ("!!Wrong Choice!! ") ''' Output of the program ----------------------------********--------------------------------------- Totle no of student in comp department 5 Enter the name of student(each on new line) a b c d e No of student who play cricket 2 enter name of student who play cricket(each on new line) a b No of student who play badminton 2 enter name of student who play badminton(each on new line) b c No of student who play football 2 enter name of student who play football(each on new line) c d _____________________________________________________________ no of student in comp department 5 ['a', 'b', 'c', 'd', 'e'] no of student who play cricket 2 ['a', 'b'] no of student who play badminton 2 ['b', 'c'] no of student who play football 2 ['c', 'd'] ______________________________________________________________ _______________________________________________________________ 1. both cricket and badminton 2. either cricket or badminton but not both 3. neither cricket nor badminton 4. cricket and football but not badminton 5. Exit Enter your Choice (from 1 to 5) :1 _________________________________________________________________ no of student who play both cricket and badminton 1 list of student who play both cricket and badminton ['b'] _______________________________________________________________ 1. both cricket and badminton 2. either cricket or badminton but not both 3. neither cricket nor badminton 4. cricket and football but not badminton 5. Exit Enter your Choice (from 1 to 5) :2 _________________________________________________________________ no of student who play either cricet or badminton but not both 1 list of student who play either cricet or badminton but not both ['a'] _______________________________________________________________ 1. both cricket and badminton 2. either cricket or badminton but not both 3. neither cricket nor badminton 4. cricket and football but not badminton 5. Exit Enter your Choice (from 1 to 5) :3 _________________________________________________________________ no of students who play neither cricket nor badminton is : 3 List of students who play neither cricket nor badminton is : ['c', 'd', 'e'] _______________________________________________________________ 1. both cricket and badminton 2. either cricket or badminton but not both 3. neither cricket nor badminton 4. cricket and football but not badminton 5. Exit Enter your Choice (from 1 to 5) :4 _________________________________________________________________ no of student who play cricket and football but not badminton : 0 List of students who play cricket and football but not badminton is : [] _______________________________________________________________ 1. both cricket and badminton 2. either cricket or badminton but not both 3. neither cricket nor badminton 4. cricket and football but not badminton 5. Exit 3. neither cricket nor badminton 4. cricket and football but not badminton 5. Exit Enter your Choice (from 1 to 5) :2 _________________________________________________________________ no of student who play either cricet or badminton but not both 1 list of student who play either cricet or badminton but not both ['a'] _______________________________________________________________ 1. both cricket and badminton 2. either cricket or badminton but not both 3. neither cricket nor badminton 4. cricket and football but not badminton 5. Exit Enter your Choice (from 1 to 5) :3 _________________________________________________________________ no of students who play neither cricket nor badminton is : 3 List of students who play neither cricket nor badminton is : ['c', 'd', 'e'] _______________________________________________________________ 1. both cricket and badminton 2. either cricket or badminton but not both 3. neither cricket nor badminton 4. cricket and football but not badminton 5. Exit Enter your Choice (from 1 to 5) :4 _________________________________________________________________ no of student who play cricket and football but not badminton : 0 List of students who play cricket and football but not badminton is : [] _______________________________________________________________ 1. both cricket and badminton 2. either cricket or badminton but not both 3. neither cricket nor badminton 4. cricket and football but not badminton 5. Exit Enter your Choice (from 1 to 5) :5 _________________________________________________________________ '''
e58f70a2708a898a669b4bfbc442d0b8d63fb79f
[ "Python", "C++" ]
13
Python
shrikrushnazirape/sppu-se-DSAL-Assignments
c166c6b75bd5f5294d5a9e4370e9c3bb79591c35
4f43f61490a9e2bb38a7660a05f0c3d5acdc2ac9
refs/heads/master
<file_sep>class ChangeUserTypeToOrder < ActiveRecord::Migration def up add_reference :orders, :user, index: true end end <file_sep>class Product < ActiveRecord::Base has_many :users, through: :order end
95361a4bfdaae83a90f17e36d36e770268267118
[ "Ruby" ]
2
Ruby
chelbig/capitalisimo
f66d69bbf5679d3f68d9d1733074c3f969fbabfd
b215be3ceff710a5a918cb7577ed99c87c20c37f
refs/heads/master
<file_sep>$(function() { $('#flash').delay(100).fadeIn('normal', function() { $(this).delay(2500).fadeOut(); }); }); function showhide() { var divParam = document.getElementById("vulnParamschart"); var divCmd = document.getElementById("divCmd"); var elem = document.getElementById("paramBtn"); if (divParam.style.display == "block") { divParam.style.display = "none"; } else { divParam.style.display = "block"; } if (elem.value == "Hide Parameters") { elem.value = "Show Parameters"; } else { elem.value = "Hide Parameters"; } } function createFilesystem(id, dict) { console.log(dict); var file_margins = {top: 30, right: 50, bottom: 30,left:50}, file_width = $(id).parent().width() - file_margins.right -file_margins.left; var file_root = {}, path, node, next, i, j, N, M; for (i = 0, N = dict.length; i < N; i++) { path = dict[i]; node = file_root; for (j = 0, M = path.length; j < M; j++) { if (node.children) { } else { node.children = {}; } next = node.children[path[j]]; if (!next) { next = node.children[path[j]] = {label: path[j]}; } node = next; } } file_root = d3.values(file_root.children)[0]; function childrenToArray(n) { if (!n.children) { } else { n.children = d3.values(n.children); n.children.forEach(childrenToArray) } } childrenToArray(file_root); var file_height = 400; var file_tree = d3.layout.tree().size([file_height, file_width]); var file_diag = d3.svg.diagonal().projection(function(d) { return [d.y, d.x]; }); var file_svg = d3.select(id).append("svg") .attr("width", file_width + file_margins.left + file_margins.right + 200) .attr("height", file_height) .append("svg:g") .attr("transform", "translate(100, 0)"); var file_nodes = file_tree.nodes(file_root).reverse(), file_links = file_tree.links(file_nodes); var file_link = file_svg.selectAll(".link") .data(file_links) .enter().append("svg:path") .attr("class", "link") .attr("d", file_diag); var file_node = file_svg.selectAll("g.node") .data(file_nodes, function(d) { return d.id || (d.id = ++i); }) .enter().append("svg:g") .attr("class", "node") .attr("transform", function (d) { return "translate(" + d.y + "," + d.x + ")"; }); file_node.append("svg:circle") .attr("r", 3.5); file_node.append("svg:text") .attr("dx", function (d) { return d.children || d.children ? -8 : 8; }) .attr("dy", 11) .style("text-anchor", function (d) { return d.children ? "end" : "start"; }) .style("fill-opacity", 1) .text(function (d) { return d.label; }); }
f990ea7cb96498a7be09a741b4600dbd9f19efde
[ "JavaScript" ]
1
JavaScript
HolyChute/VisualFi
d98fb438402d768d2bcf1ab86b80dc4712bf6c88
762501d229d743c94ade79faac28ef4d90a7f1e8
refs/heads/master
<file_sep>import React from 'react'; import MDX from '@mdx-js/runtime'; const components = { h1: props => <h1 style={{ color: 'tomato' }} { ...props } />, Demo: () => <h1>This is a demo component</h1>, }; const mdx = ` # Hello, MDX Runtime! Why can you not resolve your package? <Demo /> `; export default () => ( <MDX components={components}>{ mdx }</MDX> ); <file_sep># MDX + Next.js + MDX Runtime This project is a simple example to show that using `@mdx-js/runtime` within NextJS is raising the following error. ``` Module not found: Can't resolve '@mdx-js/runtime' in '~/code/mdx-runtime-error-nextjs/pages' ``` Run the steps below to see the error: - `yarn install` - `yarn dev` - Visit `http:localhost:3000` to view the Index page loading correctly. - Visit `http:localhost:3000/hello` to view the Hello page loading correctly. - Visit `http:localhost:3000/runtime` to view the "Module not found" error. **NOTE:** `@mdx-js` is installed within `node_modules` and includes the `/runtime/dist` directory. <file_sep># :wave: Hello, world! This is MDX! This is the static INDEX page.<file_sep># :wave: Hi there! This is the static HELLO page!
af81318924f2945018c721bc56e2430eabc17f71
[ "JavaScript", "Markdown" ]
4
JavaScript
Dangeranger/mdx-runtime-error-nextjs
7c5dd019beabab2d12fe413167d91462f2b87544
75c94b70e63466e1e90998d5bffa856e8c2753b3
refs/heads/master
<repo_name>HanLee/sitecore-checker<file_sep>/sitecore-checker.py #!/usr/bin/python import sys from sys import version_info import urllib2 collection = { 'Accessible debug URLs': ['/sitecore/debug/default.aspx'], 'Accessible web service URLs': ['/sitecore/shell/webservice/service.asmx'], 'XML files can be downloaded (sample)': ['/sitecore/shell/applications/shell.xml'], 'XSLT files can be downloaded (sample)': ['/xsl/system/webedit/hidden%20rendering.xslt'], 'Accessible administrative URLs': ['/sitecore/admin/cache.aspx', '/sitecore/admin/dbbrowser.aspx', '/sitecore/admin/login.aspx', '/sitecore/admin/restore.aspx', '/sitecore/admin/serialization.aspx', '/sitecore/admin/showconfig.aspx', '/sitecore/admin/stats.aspx', '/sitecore/admin/unlock_admin.aspx', '/sitecore/admin/updateinstallationwizard.aspx', '/sitecore/admin/wizard/installupdatepackage.aspx'] } if( len(sys.argv) < 2): print '[*] Usage: ' + sys.argv[0] + ' ' + 'http://www.yourURLhere.com/' else: url = sys.argv[1] valid_status_code = None invalid_status_code = None #first check for the default status code for a valid url try: response = urllib2.urlopen(url) valid_status_code = response.getcode() except urllib2.HTTPError, e: if e.code: print '[info] The url you provided appears to be returning ' + str(e.code) + ' , is this correct?' py3 = version_info[0] > 2 #creates boolean value for test that Python major version > 2 user_response = None while True: if py3: user_response = input("y/n: ") else: user_response = raw_input("y/n: ") if user_response.strip() == 'y' or user_response.strip() == 'n': break if user_response == 'y': print '[info] proceeding with test even though provided URL returns status ' + str(e.code) valid_status_code = e.code elif user_response == 'n': print 'invalid url inputted, quitting.' exit() #secondly check for the default status for URLs that dont exist try: random_filename = '/f7348fh3j.aspx' random_file_url = url + random_filename response = urllib2.urlopen(url + random_file_url) invalid_status_code = response.getcode() except urllib2.HTTPError, e: if e.code: print '[info] random file check with ' + random_file_url + ' returned status ' + str(e.code) invalid_status_code = e.code if(valid_status_code == invalid_status_code): print '[warning] Both valid and invalid URLs return the same status code, I will not be able to identify if the pages of interest are properly loaded' print 'Would you like me to list out the pages of interest for manual verification?' while True: if py3: user_response = input("y/n: ") else: user_response = raw_input("y/n: ") if user_response.strip() == 'y' or user_response.strip() == 'n': break if user_response == 'y': for key in collection: payloads = collection[key] for payload in payloads: print url+payload elif user_response == 'n': print 'cya!' exit() else: print '[info] Valid URLs and invalid URLs return status code ' + str(valid_status_code) + ' and ' + str(invalid_status_code) + ' respectively, using ' + str(valid_status_code) + ' as baseline to check for access to test pages' for key in collection: print "\nChecking for " + key payloads = collection[key] for payload in payloads: full_url = url+payload found = False try: response = urllib2.urlopen(full_url) if response.getcode() == valid_status_code: found = True except urllib2.HTTPError, e: #in case of weird status code being returned for valid pages if e.code == valid_status_code: found = True if found: print '\t[y] ' + full_url else: print '\t[n] ' + full_url <file_sep>/README.md sitecore-checker ================ A python security checker for web applications that runs on SiteCore. Checks for default login/admin/default files.
b9eda3452c7f0005cd8c1b4082425d52f5a4363b
[ "Markdown", "Python" ]
2
Python
HanLee/sitecore-checker
5465606d6fa86f1c362b56ab5fec768112195180
8b79ab41ac305b6abe9576a6ca87652b72cc339d
refs/heads/master
<repo_name>NCNecros/PolisViewer<file_sep>/src/sample/Controller.java package sample; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.event.EventType; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Pane; import javafx.util.Callback; import javafx.util.StringConverter; import java.io.IOException; import java.net.URL; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ResourceBundle; public class Controller implements Initializable{ @FXML private Button buttonFindByPolis; @FXML private Button buttonFindByFIO; @FXML private TextField textFieldSerial; @FXML private TextField textFieldNumber; @FXML private TextField textFieldLastName; @FXML private TextField textFieldFirstName; @FXML private DatePicker datePickerBirthDate; @FXML private TableView tableViewResult; @FXML private Label labelType; @FXML private Label labelSMO; @FXML private Label labelSerial; @FXML private Label labelNumber; private HtmlHelper helper; @Override public void initialize(URL location, ResourceBundle resources) { helper = new HtmlHelper(); datePickerBirthDate.setConverter(new StringConverter<LocalDate>() { private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("ddMMyyyy"); private DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("dd.MM.yyyy"); @Override public String toString(LocalDate localDate) { if (localDate == null) return ""; return dateTimeFormatter2.format(localDate); } @Override public LocalDate fromString(String dateString) { if (dateString == null || dateString.trim().isEmpty()) { return null; } return LocalDate.parse(dateString, dateTimeFormatter); } }); addEventFilter(textFieldFirstName); addEventFilter(textFieldLastName); addEventFilter(datePickerBirthDate); datePickerBirthDate.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue ){ datePickerBirthDate.getEditor(). } } }); } public void findByFIO(ActionEvent actionEvent) { findByFIO(); } private void findByFIO(){ Human human = new Human(); human.setFirstName(textFieldFirstName.getText()); human.setLastName(textFieldLastName.getText()); human.setBirthDate(datePickerBirthDate.getEditor().getText()); Polis polis = helper.getPolis(human); labelType.setText(polis.getType()); labelSMO.setText(polis.getSMO()); labelSerial.setText(polis.getSerial()); labelNumber.setText(polis.getNumber()); } public void findByPolis(ActionEvent actionEvent) { } private void addEventFilter(Node element) { if (element instanceof TextField || element instanceof DatePicker) element.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { if (event.getCode() == KeyCode.ENTER) { if (textFieldLastName.isFocused()) { textFieldFirstName.requestFocus(); } else if (textFieldFirstName.isFocused()) { datePickerBirthDate.requestFocus(); } else if (datePickerBirthDate.isFocused()) { buttonFindByFIO.requestFocus(); findByFIO(); } else if (buttonFindByFIO.isFocused()) { textFieldFirstName.requestFocus(); } } } }); } public void onEnter(KeyEvent keyEvent) { } } <file_sep>/src/sample/HtmlHelper.java package sample; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class HtmlHelper { Polis polis; //Конструктор public Polis getPolis(Human human){ try{ //Загружаем html код сайта //УРЛ URL url = new URL("http://www.kubanoms.ru/Polis/index.php"); /*Соединение*/ URLConnection con = url.openConnection(); /*Настройка параметров соединения*/ con.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), Charset.forName("cp1251")); wr.write("search_type=2&"); wr.write("p_ser=&"); wr.write("p_num=&"); wr.write("surname=" + human.getLastName()+"&"); wr.write("names=" + human.getFirstName()+"&"); wr.write("secname=" + "&"); wr.write("birth=" + human.getBirthDate()+"&"); wr.write("btn_search=ПОИСК"); wr.write("\r\n"); wr.flush(); wr.close(); String html = readStreamToString(con.getInputStream(), "CP1251"); Document doc = Jsoup.parse(html); Elements elements = doc.getElementsByClass("f-row"); System.out.println(elements.size()); System.out.println(elements); if (elements.size() == 1){ Element element = elements.first(); polis = new Polis(); Elements tds = element.getElementsByTag("td"); polis.setType(tds.get(1).text()); polis.setSMO(tds.get(0).text()); polis.setSerial(tds.get(2).text().replaceFirst("&nbsp;", "")); polis.setNumber(tds.get(3).text()); }else { polis = new Polis(); polis.setSerial("Полис не найден"); } }catch (Exception e){ polis.setNumber("Возникла ошибка"); } return polis; } private String readStreamToString(InputStream in, String encoding) throws IOException { StringBuffer b = new StringBuffer(); InputStreamReader r = new InputStreamReader(in, encoding); int c; while ((c = r.read()) != -1) { b.append((char) c); } return b.toString(); } }<file_sep>/src/sample/Polis.java package sample; /** * Created by User on 15.02.2015. */ public class Polis { private String serial=""; private String number=""; private String SMO=""; private String type=""; public String getSerial() { return serial; } public void setSerial(String serial) { this.serial = serial; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getSMO() { return SMO; } public void setSMO(String SMO) { this.SMO = SMO; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
01fea4460f57e9afd117066ab49f17b326e41425
[ "Java" ]
3
Java
NCNecros/PolisViewer
b60c28d866c0aed2f74e6e4d8cb6a8641dba3d37
cd5d60e4f2ca2150d866eb4f968e2a5ed3b5b4d2
refs/heads/master
<file_sep>using MultilingualXFSample.ViewModels; using Xamarin.Forms; namespace MultilingualXFSample.Views { public partial class ChangeLanguagePage : ContentPage { public ChangeLanguagePage() { InitializeComponent(); BindingContext = new ChangeLanguageViewModel(); } } } <file_sep>using System; using Xamarin.Forms; namespace MultilingualXFSample.Controls { public class LocalizedDatePicker : DatePicker { public static readonly BindableProperty PositiveActionTextProperty = BindableProperty.Create(nameof(PositiveActionText), typeof(string), typeof(LocalizedDatePicker), "Set"); public string PositiveActionText { get { return (string)GetValue(PositiveActionTextProperty); } set { SetValue(PositiveActionTextProperty, value); } } public static readonly BindableProperty NegativeActionTextProperty = BindableProperty.Create(nameof(NegativeActionText), typeof(string), typeof(LocalizedDatePicker), "Cancel"); public string NegativeActionText { get { return (string)GetValue(NegativeActionTextProperty); } set { SetValue(NegativeActionTextProperty, value); } } } } <file_sep> namespace MultilingualXFSample.Models { public class Language { public Language(string name, string ci) { Name = name; CI = ci; } public string Name { get; set; } public string CI { get; set; } } }
0696545d3f07ab837b2c9712f1c1985b175612ee
[ "C#" ]
3
C#
johanssonviktor/MasteringMultilingualSample
523002f1fcd63161a93504e2e20ecdb09642a5ba
94e966cc29327e0f9c873d96b6a9cb7eee00e013
refs/heads/master
<file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using StudIS.DAL; using StudIS.Models.Users; using StudIS.DAL.Repositories; using StudIS.DAL.Tests; namespace StudIS.Services.Tests { [TestClass] public class StudentServicesTests { private INHibernateService _nhs; public StudentServicesTests() { _nhs = new NHibernateService2(); var userRep = new UserRepository(_nhs); var userServices = new UserServices(userRep); var student = new Student() { Id = 1, Name = "Zlatko", Surname = "Hrastić", Email = "<EMAIL>", NationalIdentificationNumber = "343999999", StudentIdentificationNumber = "0036476522", CoursesEnrolledIn = null, PasswordHash = "xxx" }; var administrator = new Administrator() { Id = 2, Email = "<EMAIL>", PasswordHash = EncryptionService.EncryptSHA1("<PASSWORD>"), Name = "Željko", Surname = "Baranek", NationalIdentificationNumber = "123456" }; userServices.CreateUser(student); userServices.CreateUser(administrator); } [TestMethod] public void GetStudentdata_StudentId() { var userRep = new UserRepository(_nhs); var studentServices = new StudentServices(userRep); var studentData = studentServices.getStudentdata(1); Assert.IsNotNull(studentData); Assert.AreEqual(studentData.Id, 1); } [TestMethod] public void GetStudentdata_NotStudentId() { var userRep = new UserRepository(_nhs); var studentServices = new StudentServices(userRep); var studentData = studentServices.getStudentdata(2); Assert.IsNull(studentData); } } } <file_sep>using StudIS.Models; using StudIS.Models.RepositoryInterfaces; using StudIS.Models.Users; using System.Collections.Generic; using System.Linq; namespace StudIS.Services { public class CourseServices { private ICourseRepository _courseRepository; private IUserRepository _userRepository; private IComponentRepository _componentRepository; public CourseServices(ICourseRepository courseRepository, IUserRepository userRepository, IComponentRepository componentRepository) { _courseRepository = courseRepository; _userRepository = userRepository; _componentRepository = componentRepository; } public IList<Course> GetAllCourses() { return _courseRepository.GetAll(); } public Course GetCourseByNaturalIdentifier(string naturalIdentifier) { return _courseRepository.GetByNaturalIdentifier(naturalIdentifier); } public List<Course> GetCoursesByUserId(int id) { var student = _userRepository.GetById(id); if (student == null || !UserServices.IsUserStudent(student)) return null; var courses = _courseRepository.GetByStudentEnroledId(id); if (courses == null) return null; var coursesList = courses.ToList(); coursesList.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); return coursesList; } public List<Course> GetCoursesByLecturerId(int id) { var lecturer= _userRepository.GetById(id); if (lecturer==null || !UserServices.IsUserLecturer(lecturer)) return null; var courses = _courseRepository.GetByLecturerInChargerId(id); if (courses == null) return null; var coursesList = courses.ToList(); coursesList.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); return coursesList; } public Course GetCourseById(int courseId) { return _courseRepository.GetById(courseId); } public Course CreateCourse(string name, string naturalIdentifier, int ectsCredits) { var course = new Course() { Name = name, NaturalIdentifier = naturalIdentifier, EctsCredits = ectsCredits }; return _courseRepository.Create(course); } public Course UpdateCourse(int courseId, string name, string naturalIdentifier, int ectsCredits) { var course = _courseRepository.GetById(courseId); if (course == null) return null; course.Name = name; course.NaturalIdentifier = naturalIdentifier; course.EctsCredits = ectsCredits; return _courseRepository.Update(course); } public bool DeleteCourse(int id) { return _courseRepository.DeleteById(id); } public Course AddLecturer(int courseId, int lecturerId) { var course = _courseRepository.GetById(courseId); var lecturer = _userRepository.GetById(lecturerId); if (course == null || lecturer == null || !UserServices.IsUserLecturer(lecturer)) return null; course.LecturersInCharge.Add((Lecturer)lecturer); return _courseRepository.Update(course); } public Course RemoveLecturer(int courseId, int lecturerId) { var course = _courseRepository.GetById(courseId); var lecturer = _userRepository.GetById(lecturerId); if (course == null || lecturer == null || !UserServices.IsUserLecturer(lecturer)) return null; course.LecturersInCharge.Remove((Lecturer)lecturer); return _courseRepository.Update(course); } public Course UpdateLecturers(int courseId, IList<Lecturer> lecturers) { var course = _courseRepository.GetById(courseId); var toBeRemoved = new List<Lecturer>(); if (course.LecturersInCharge == null) { course.LecturersInCharge = new List<Lecturer>(); } foreach (var lecturer in course.LecturersInCharge) { if (!lecturers.Contains(lecturer)) { toBeRemoved.Add(lecturer); } } foreach (var lecturer in toBeRemoved) { RemoveLecturer(courseId, lecturer.Id); } foreach (var lecturer in lecturers) { if (!course.LecturersInCharge.Contains(lecturer)) { AddLecturer(courseId, lecturer.Id); } } course.LecturersInCharge = lecturers; return course; } public Course UpdateStudents(int courseId, IList<Student> students) { var course = _courseRepository.GetById(courseId); var toBeRemoved = new List<Student>(); if (course.StudentsEnrolled == null) { course.StudentsEnrolled = new List<Student>(); } foreach (var student in course.StudentsEnrolled) { if (!students.Contains(student)) { RemoveStudent(courseId, student.Id); } } foreach (var student in toBeRemoved) { RemoveStudent(courseId, student.Id); } foreach (var student in students) { if (!course.StudentsEnrolled.Contains(student)) { AddStudent(courseId, student.Id); } } course.StudentsEnrolled = students; return course; } public Course AddStudent(int courseId, int studentId) { var course = _courseRepository.GetById(courseId); var student = _userRepository.GetById(studentId); if (course == null || student == null || !UserServices.IsUserStudent(student)) return null; course.StudentsEnrolled.Add((Student)student); return _courseRepository.Update(course); } public Course RemoveStudent(int courseId, int studentId) { var course = _courseRepository.GetById(courseId); var student = _userRepository.GetById(studentId); if (course == null || student == null || !UserServices.IsUserStudent(student)) return null; course.StudentsEnrolled.Remove((Student)student); return _courseRepository.Update(course); } public Course AddComponent(int courseId, int componentId) { var course = _courseRepository.GetById(courseId); var component = _componentRepository.GetById(courseId); if (course == null || component == null) return null; course.Components.Add(component); return _courseRepository.Update(course); } public Course RemoveComponent(int courseId, int componentId) { var course = _courseRepository.GetById(courseId); var component = _componentRepository.GetById(courseId); if (course == null || component == null) return null; course.Components.Remove(component); return _courseRepository.Update(course); } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using StudIS.Models.RepositoryInterfaces; using StudIS.DAL.Repositories; using StudIS.Models.Users; namespace StudIS.DAL.Tests { [TestClass] public class UserRepositoryTests { INHibernateService _nhs; IUserRepository _usrRep; public UserRepositoryTests() { _nhs = new NHibernateService2(); _usrRep = new UserRepository(_nhs); } [TestMethod] public void CreateTest_Success() { var admin = new Administrator() { Email = "<EMAIL>", Name = "Adminko", Surname = "Adminic", NationalIdentificationNumber = "12345", PasswordHash = "xxx" }; var created = _usrRep.Create(admin); Assert.IsNotNull(created); Assert.IsFalse(created.Id == 0); } [TestMethod] public void CreateTest_Fail() { var admin = new Administrator() { Email = "<EMAIL>", Name = "Adminko", Surname = "Adminic", NationalIdentificationNumber = "12345", PasswordHash = null }; try { var created = _usrRep.Create(admin); Assert.Fail("No exception thrown"); } catch (Exception ex) { Assert.IsTrue(ex is NHibernate.PropertyValueException); } } [TestMethod] public void DeleteTest_True() { var admin = new Administrator() { Email = "<EMAIL>", Name = "Adminko", Surname = "Adminic", NationalIdentificationNumber = "12345", PasswordHash = "xxx" }; var created = _usrRep.Create(admin); var wasDeleted = _usrRep.DeleteById(created.Id); Assert.IsTrue(wasDeleted); } [TestMethod] public void DeleteTest_False() { var admin = new Administrator() { Email = "<EMAIL>", Name = "Adminko", Surname = "Adminic", NationalIdentificationNumber = "12345", PasswordHash = "xxx" }; var created = _usrRep.Create(admin); _usrRep.DeleteById(created.Id); var wasDeleted = _usrRep.DeleteById(created.Id); Assert.IsFalse(wasDeleted); } [TestMethod] public void GetByIdTest_Correct() { var admin = new Administrator() { Email = "<EMAIL>", Name = "Adminko", Surname = "Adminic", NationalIdentificationNumber = "12345", PasswordHash = "xxx" }; var created = _usrRep.Create(admin); var user = _usrRep.GetById(created.Id); Assert.IsNotNull(user); } [TestMethod] public void GetByIdTest_InCorrect() { _usrRep.DeleteById(10); var user = _usrRep.GetById(10); Assert.IsNull(user); } [TestMethod] public void GetByEmailTest_Correct() { var admin = new Administrator() { Email = "<EMAIL>", Name = "Adminko", Surname = "Adminic", NationalIdentificationNumber = "12345", PasswordHash = "xxx" }; var created = _usrRep.Create(admin); var user = _usrRep.GetByEmail(created.Email); Assert.IsNotNull(user); } [TestMethod] public void GetByEmailTest_InCorrect() { var user = _usrRep.GetByEmail("wrongemail"); Assert.IsNull(user); } [TestMethod] public void UpdateUser_Success() { var admin = new Administrator() { Email = "<EMAIL>", Name = "Adminko", Surname = "Adminic", NationalIdentificationNumber = "12345", PasswordHash = "xxx" }; var created = _usrRep.Create(admin); created.Name = "UpdatedAdminko"; var updated = _usrRep.Update(created); Assert.IsNotNull(updated); Assert.AreEqual(updated.Name, "UpdatedAdminko"); } [TestMethod] public void UpdateUser_Fail() { var admin = new Administrator() { Email = "<EMAIL>", Name = "Adminko", Surname = "Adminic", NationalIdentificationNumber = "12345", PasswordHash = "xxx" }; var created = _usrRep.Create(admin); created.PasswordHash = null; try { var updated = _usrRep.Update(created); Assert.Fail("No exception thrown"); } catch (Exception ex) { Assert.IsTrue(ex is NHibernate.PropertyValueException); } } } } <file_sep>using StudIS.Models.RepositoryInterfaces; using StudIS.Services; using StudIS.Web.Mvc.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace StudIS.Web.Mvc.Controllers { public class LoginController : Controller { private IUserRepository _usrRep; public LoginController(IUserRepository usrRep) { _usrRep = usrRep; } // GET: Login public ActionResult Index(Credentials credentials) { if (ModelState.IsValid) { var loginService = new LoginService(_usrRep); var encryptedPassword = EncryptionService.EncryptSHA1(credentials.Password); var user = loginService.LoginUser(credentials.Email, encryptedPassword); if (user == null || UserServices.IsUserAdministrator(user)) return RedirectToAction("Index", "Home",new {error=true }); else { Session.Add("userId", user.Id); Session.Add("email", user.Email); if (UserServices.IsUserStudent(user)) { Session.Add("userType", "Student"); return RedirectToAction("Index", "Student"); } if (UserServices.IsUserLecturer(user)) { Session.Add("userType", "Lecturer"); return RedirectToAction("Index", "Lecturer"); } } } return RedirectToAction("Index", "Home", new { error = true }); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace StudIS.Web.Api.Models { public class ScoredCourse { public String Name { get; set; } public List<SimpleScore> ScoreList { get; set; } } }<file_sep>using System.Collections.Generic; using StudIS.Models; using StudIS.Services; namespace StudIS.Desktop.Controllers { public class MainFormController { private readonly UserServices _userServices; private readonly CourseServices _courseServices; public MainFormController(UserServices userServices, CourseServices courseServices) { _userServices = userServices; _courseServices = courseServices; } public IList<Course> GetAllCourses() { return _courseServices.GetAllCourses(); } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using StudIS.DAL.Repositories; using StudIS.Models.RepositoryInterfaces; using StudIS.Models; namespace StudIS.DAL.Tests { [TestClass] public class CourseRepositoryTests { INHibernateService _nhs; ICourseRepository _corRep; public CourseRepositoryTests() { _nhs = new NHibernateService2(); _corRep = new CourseRepository(_nhs); } [TestMethod] public void CourseRepository_Create_Success() { Course course = new Course() { Name = "<NAME>", NaturalIdentifier = "KVARC-FER-2016", EctsCredits = 5, StudentsEnrolled = null, LecturersInCharge = null, Components = null }; var created = _corRep.Create(course); Assert.IsNotNull(created); Assert.IsFalse(created.Id == 0); } [TestMethod] public void CourseRepository_Create_Fail() { Course course = new Course() { Name = "<NAME>", NaturalIdentifier = null, EctsCredits = 5, StudentsEnrolled = null, LecturersInCharge = null, Components = null }; try { var created = _corRep.Create(course); Assert.Fail("No exception thrown"); } catch (Exception ex) { Assert.IsTrue(ex is NHibernate.PropertyValueException); } } [TestMethod] public void CourseRepository_GetByNaturalIdentifier_Success() { Course course = new Course() { Name = "<NAME>", NaturalIdentifier = "KVARC-FER-2016", EctsCredits = 5, StudentsEnrolled = null, LecturersInCharge = null, Components = null }; _corRep.Create(course); var result = _corRep.GetByNaturalIdentifier("KVARC-FER-2016"); Assert.AreEqual(result.NaturalIdentifier, "KVARC-FER-2016"); Assert.AreEqual(result.Name, "<NAME>"); } [TestMethod] public void CourseRepository_GetByNaturalIdentifier_Fail() { var result = _corRep.GetByNaturalIdentifier("wrong identifier"); Assert.IsNull(result); } [TestMethod] public void CourseRepository_Update_Success() { Course course = new Course() { Id = 1, Name = "<NAME>", NaturalIdentifier = "KVARC-FER-2016", EctsCredits = 5, StudentsEnrolled = null, LecturersInCharge = null, Components = null }; _corRep.Create(course); var created = _corRep.GetById(1); created.NaturalIdentifier = "NewNat"; var updated = _corRep.Update(created); Assert.AreEqual(updated.NaturalIdentifier, "NewNat"); } } } <file_sep>using StudIS.Models.RepositoryInterfaces; using StudIS.Models.Users; using StudIS.Services; using StudIS.Web.Mvc.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace StudIS.Web.Mvc.Controllers { public class StudentController : Controller { private ICourseRepository _courseRepository; private IScoreRepository _scoreRepository; private IUserRepository _userRepository; IComponentRepository _componentRepository; public StudentController(ICourseRepository courseRepository, IScoreRepository scoreRepository, IUserRepository userRepository, IComponentRepository componentRepository) { _courseRepository = courseRepository; _scoreRepository = scoreRepository; _userRepository = userRepository; _componentRepository = componentRepository; } // GET: Student /// <summary> /// Show the list of available courses /// </summary> /// <returns></returns> public ActionResult Index() { if (Session["userId"] == null) return RedirectToAction("Index", "Home"); ViewBag.Email = Session["email"]; ViewBag.Title = "Predmeti"; int userId = (int)Session["userId"]; List<StudentCourseViewModel> courseList = new List<StudentCourseViewModel>(); var courseServices = new CourseServices(_courseRepository, _userRepository, _componentRepository); var courses = courseServices.GetCoursesByUserId(userId); if (courses != null) { foreach (var course in courses) { courseList.Add(new StudentCourseViewModel(course)); } } return View(courseList); } /// <summary> /// /// </summary> /// <param name="id">Course id</param> /// <returns></returns> public ActionResult ScoreInfo(int id) { if (Session["userId"] == null) return RedirectToAction("Index", "Home"); ViewBag.Email = Session["email"]; ViewBag.Title = "Bodovi"; var studentId = (int)Session["userId"]; var scoreServcies = new ScoreServices(_scoreRepository, _courseRepository, _userRepository); var courseServices = new CourseServices(_courseRepository, _userRepository, _componentRepository); var course = courseServices.GetCourseById(id); var scores = scoreServcies.GetScorebyStudentAndCourse(studentId, id); var scoresViewModel = new List<ScoreViewModel>(); float cumScore = 0; foreach (var score in scores) { scoresViewModel.Add(new ScoreViewModel(score)); cumScore += score.Value; } scoresViewModel.Sort((m1, m2) => m1.ComponentName.CompareTo(m2.ComponentName)); var scoredCourse = new ScoredCourseViewModel() { Name = course.Name, scoreList = scoresViewModel, cumulativeScore=cumScore }; return View(scoredCourse); } public ActionResult PersonalData() { if (Session["userId"] == null) return RedirectToAction("Index", "Home"); ViewBag.Email = Session["email"]; ViewBag.Title = "Osobni podaci"; var studentId = (int)Session["userId"]; var user = _userRepository.GetById(studentId); if (user == null || !UserServices.IsUserStudent(user)) return RedirectToAction("Index", "Home"); return View(new StudentViewModel((Student)user)); } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using StudIS.Desktop.Controllers; using StudIS.Models; using StudIS.Models.Users; namespace StudIS.Desktop { public partial class MainForm : Form { private readonly MainFormController _mainFormController; private readonly LoginFormController _loginFormController; private readonly CourseFormController _courseFormController; private readonly UserFormController _userFormController; public MainForm( MainFormController mainFormController, LoginFormController loginFormController, CourseFormController courseFormController, UserFormController userFormController) { _mainFormController = mainFormController; _loginFormController = loginFormController; _courseFormController = courseFormController; _userFormController = userFormController; InitializeComponent(); populateCoursesListBox(); } private void populateCoursesListBox() { this.coursesListBox.DataSource = _mainFormController.GetAllCourses(); this.coursesListBox.DisplayMember = "Naturalidentifier"; this.coursesListBox.ValueMember = "Id"; } private bool getSelectedAccountTypeAndEmail(out User user, out string email) { email = this.emailTextBox.Text; user = null; if (email.Length == 0) { MessageBox.Show("Unesite e-mail adresu", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } if (this.studentRadioButton.Checked) { user = new Student(); ((Student)user).CoursesEnrolledIn = new List<Course>(); } else if (this.lecturerRadioButton.Checked) { user = new Lecturer(); ((Lecturer)user).CoursesInChargeOf = new List<Course>(); } else if (this.adminRadioButton.Checked) { user = new Administrator(); } else { MessageBox.Show("Odaberite vrstu korisnika", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } user.Email = email; return true; } private void newUserButton_Click(object sender, EventArgs e) { User user; string email; var valid = getSelectedAccountTypeAndEmail(out user, out email); if (valid) { var success = _userFormController.OpenFormNewUser(user); if (!success) { MessageBox.Show("Korisnik s unesenom e-mail adresom već postoji", "Korisnik postoji", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void editUserButton_Click(object sender, EventArgs e) { User user; string email; var valid = getSelectedAccountTypeAndEmail(out user, out email); if (valid) { var success = _userFormController.OpenFormEditUser(email); if (!success) { MessageBox.Show("Korisnik s unesenom e-mail adresom ne postoji.", "Ne postoji taj korisnik", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void deleteUserButton_Click(object sender, EventArgs e) { User user; string email; var valid = getSelectedAccountTypeAndEmail(out user, out email); if (valid) { var prompt = MessageBox.Show("Zaista izbristi korisnika i sve njegove rezultate?", "Potvrda", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (prompt == DialogResult.No) { return; } var success = _userFormController.DeleteUser(email); if (success) { MessageBox.Show("Korisnik izbrisan!", "Uspjeh", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Korisnik s unesenom e-mail adresom ne postoji", "Nema tog korisnika", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void newCourseButton_Click(object sender, EventArgs e) { _courseFormController.OpenFormNewCourse(); } private void editCourseButton_Click(object sender, EventArgs e) { var courseId = (int)this.coursesListBox.SelectedValue; _courseFormController.OpenFormEditCourse(courseId); } private void deleteCourseButton_Click(object sender, EventArgs e) { var courseId = (int)this.coursesListBox.SelectedValue; var prompt = MessageBox.Show("Izbrisati predmet i sve rezultate?", "Potvrda brisanja", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (prompt == DialogResult.No) { return; } bool success = _courseFormController.DeleteCourse(courseId); if(!success) { MessageBox.Show("Došlo je do greške prilikom brisanja", "Neuspjeh", MessageBoxButtons.OK, MessageBoxIcon.Error); } populateCoursesListBox(); } private void MainForm_Activated(object sender, EventArgs e) { populateCoursesListBox(); } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using StudIS.DAL; using StudIS.DAL.Repositories; using StudIS.Models.Users; using Moq; using StudIS.Models.RepositoryInterfaces; using StudIS.Models; using System.Collections.Generic; using StudIS.DAL.Tests; namespace StudIS.Services.Tests { [TestClass] public class ScoreServicesTests { private INHibernateService _nhs; private User student; private User administrator; public ScoreServicesTests() { _nhs = new NHibernateService2(); var userRep = new UserRepository(_nhs); var userServices = new UserServices(userRep); student = new Student() { Id = 1, Name = "Zlatko", Surname = "Hrastić", Email = "<EMAIL>", NationalIdentificationNumber = "343999999", StudentIdentificationNumber = "0036476522", CoursesEnrolledIn = null, PasswordHash = "xxx" }; administrator = new Administrator() { Id = 2, Email = "<EMAIL>", PasswordHash = EncryptionService.EncryptSHA1("<PASSWORD>"), Name = "Željko", Surname = "Baranek", NationalIdentificationNumber = "123456" }; } [TestMethod] public void GetScorebyStudentAndCourseTest() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); var componentList = new List<Component>(); componentList.Add(new Component()); Mock<Course> courseMock = new Mock<Course>(); courseMock.Setup(c => c.Components).Returns(componentList); corRepMock.Setup(c => c.GetById(It.IsAny<int>())).Returns(courseMock.Object); usrRepMock.Setup(c => c.GetById(It.IsAny<int>())).Returns(student); scrRepMock.Setup(c => c.GetByStudentIdAndComponentId(It.IsAny<Student>(), It.IsAny<Component>())).Returns(new Score()); var scoreService = new ScoreServices(scrRepMock.Object, corRepMock.Object, usrRepMock.Object); var scores = scoreService.GetScorebyStudentAndCourse(1, 1); Assert.IsNotNull(scores); Assert.IsFalse(scores.Count == 0); } [TestMethod] public void GetScorebyStudentAndCourseTest_DefaultScore() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); var componentList = new List<Component>(); componentList.Add(new Component()); Mock<Course> courseMock = new Mock<Course>(); courseMock.Setup(c => c.Components).Returns(componentList); corRepMock.Setup(c => c.GetById(It.IsAny<int>())).Returns(courseMock.Object); usrRepMock.Setup(c => c.GetById(It.IsAny<int>())).Returns(student); scrRepMock.Setup(c => c.GetByStudentIdAndComponentId(It.IsAny<Student>(), It.IsAny<Component>())).Returns<Score>(null); scrRepMock.Setup(c => c.CreateOrUpdate(It.IsAny<Score>())).Returns(new Score() { Value = 0 }); var scoreService = new ScoreServices(scrRepMock.Object, corRepMock.Object, usrRepMock.Object); var scores = scoreService.GetScorebyStudentAndCourse(1, 1); Assert.IsNotNull(scores); Assert.IsFalse(scores.Count == 0); Assert.AreEqual(0, scores[0].Value); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using StudIS.Models.Users; using StudIS.Services; using System.Windows.Forms; namespace StudIS.Desktop.Controllers { public class LoginFormController { private readonly MainFormController _mainFormController; private readonly LoginService _loginService; public LoginFormController( MainFormController mainFormController, LoginService loginService) { _mainFormController = mainFormController; _loginService = loginService; } public bool Login(string email, string password) { var passwordHash = EncryptionService.EncryptSHA1(password); var user = _loginService.LoginUser(email, passwordHash); if (user != null) { if (!UserServices.IsUserAdministrator(user)) { MessageBox.Show(user.FullName + " nije u ulozi administratora", "Nedovoljna prava", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } else { return true; } } else { MessageBox.Show("Neispravni podaci korisnika", "", MessageBoxButtons.OK, MessageBoxIcon.Information); return false; } } } } <file_sep>using StudIS.Models; using StudIS.Models.RepositoryInterfaces; using StudIS.Models.Users; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Services { public class UserServices { private IUserRepository _userRepository; public UserServices(IUserRepository userRepository) { _userRepository = userRepository; } public static bool IsUserAdministrator(User user) { if (user.GetType() == typeof(Administrator)) return true; else return false; } public static bool IsUserLecturer(User user) { if (user.GetType() == typeof(Lecturer)) return true; else return false; } public static bool IsUserStudent(User user) { if (user.GetType() == typeof(Student)) return true; else return false; } public User CreateUser(User user) { return _userRepository.Create(user); } public IList<User> GetAllUsers() { return _userRepository.GetAll(); } public IList<Administrator> GetAllAdministrators() { return _userRepository.GetAllAdministrators(); } public IList<Lecturer> GetAllLecturers() { return _userRepository.GetAllLecturers(); } public IList<Student> GetAllStudents() { return _userRepository.GetAllStudents(); } public User GetUserById(int id) { return _userRepository.GetById(id); } public User GetUserByEmail(string email) { return _userRepository.GetByEmail(email); } public User UpdateUser(User user) { return _userRepository.Update(user); } public bool DeleteUserById(int id) { return _userRepository.DeleteById(id); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Desktop { interface IWindowFormsFactory { } } <file_sep>using System; using System.Windows.Forms; using StudIS.DAL; using StudIS.DAL.Repositories; using StudIS.Services; using StudIS.Desktop.Controllers; namespace StudIS.Desktop { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { var nhService = new NHibernateService(); var userRepository = new UserRepository(nhService); var courseRepository = new CourseRepository(nhService); var componentRepository = new ComponentRepository(nhService); var scoreRepository = new ScoreRepository(nhService); var loginService = new LoginService(userRepository); var userServices = new UserServices(userRepository); var courseServices = new CourseServices(courseRepository, userRepository, componentRepository); var mainFormController = new MainFormController(userServices, courseServices); var loginFormController = new LoginFormController(mainFormController, loginService); var courseFormController = new CourseFormController(courseServices, userServices); var userFormController = new UserFormController(userServices, courseServices); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var loginForm = new LoginForm(loginFormController); var mainForm = new MainForm( mainFormController, loginFormController, courseFormController, userFormController); Application.Run(loginForm); var loginResult = loginForm.LoginResult; if (loginResult) { Application.Run(mainForm); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Models { public class Component { public virtual int Id { get; set; } public virtual Course Course { get; set; } public virtual string Name { get; set; } public virtual float MaximumPoints { get; set; } public virtual float MinimumPointsToPass { get; set; } } } <file_sep>using StudIS.DAL; using StudIS.DAL.Repositories; using StudIS.Models.RepositoryInterfaces; using StudIS.Models; using StudIS.Services; using StudIS.Web.Api.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace StudIS.Web.Api.Controllers { public class StudentDataController : ApiController { private IUserRepository _usrRep; private ICourseRepository _corRep; private IScoreRepository _scrRep; private IComponentRepository _comRep; public StudentDataController(IUserRepository usrRep,ICourseRepository corRep,IScoreRepository scrRep,IComponentRepository comRep) { _usrRep = usrRep; _corRep = corRep; _scrRep = scrRep; _comRep = comRep; } /// <summary> /// Returns simpleCourse model for student with given id, returns null otherwise /// </summary> /// <param name="studentId">id of the student</param> /// <returns></returns> [Route("api/StudentData/GetCoursesByStudentId/{studentId}")] public List<SimpleCourseModel> GetCoursesByStudentId(int studentId) { var courseServices = new CourseServices(_corRep,_usrRep,_comRep); var courses = courseServices.GetCoursesByUserId(studentId); if (courses == null) return null; else { var simpleCourseList = new List<SimpleCourseModel>(); foreach(var course in courses) { simpleCourseList.Add(new SimpleCourseModel(course)); } return simpleCourseList; } } [Route("api/StudentData/GetScoreData/{studentId}/{courseId}")] public ScoredCourse GetScoreData(int studentId,int courseId) { var scoreServcies = new ScoreServices(_scrRep, _corRep, _usrRep); var courseServices = new CourseServices(_corRep,_usrRep,_comRep); var course = courseServices.GetCourseById(courseId); var scores = scoreServcies.GetScorebyStudentAndCourse(studentId, courseId); var scoresViewModel = new List<SimpleScore>(); foreach (var score in scores) { scoresViewModel.Add(new SimpleScore(score)); } scoresViewModel.Sort((m1, m2) => m1.ComponentName.CompareTo(m2.ComponentName)); var scoredCourse = new ScoredCourse() { Name = course.Name, ScoreList = scoresViewModel }; return scoredCourse; } [Route("api/StudentData/GetStudentData/{id}")] public SimpleStudentModel GetStudentData(int id) { var studentServices = new StudentServices(_usrRep); var student = studentServices.getStudentdata(id); if (student != null) return new SimpleStudentModel(student); else return null; } } } <file_sep>using StudIS.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace StudIS.Web.Mvc.Models { public class ComponentViewModel { public virtual int Id { get; set; } [Required(ErrorMessage = "Ime komponente je obavezno!")] public virtual string Name { get; set; } [Required(ErrorMessage = "Broj bodova mora biti definiran!")] public virtual float MaximumPoints { get; set; } [Required(ErrorMessage = "Prag mora biti definiran (makar bio 0)!")] public virtual float MinimumPointsToPass { get; set; } public virtual int CourseId { get; set; } public virtual string CourseName { get; set; } public ComponentViewModel() { } public ComponentViewModel(Component component) { this.Id = component.Id; this.Name = component.Name; this.MaximumPoints = component.MaximumPoints; this.MinimumPointsToPass = component.MinimumPointsToPass; this.CourseId = component.Course.Id; this.CourseName = component.Course.Name; } } }<file_sep>using StudIS.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace StudIS.Web.Api.Models { public class SimpleCourseModel { public int Id { get; set; } public string NaturalIdentifier { get; set; } public string Name { get; set; } public int EctsCredits { get; set; } public SimpleCourseModel() { } public SimpleCourseModel(Course course) { Id = course.Id; NaturalIdentifier = course.NaturalIdentifier; Name = course.Name; EctsCredits = course.EctsCredits; } } }<file_sep>using StudIS.Models.RepositoryInterfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using NHibernate; using NHibernate.Exceptions; namespace StudIS.DAL.Repositories { public class ComponentRepository : IComponentRepository { private ISession _session; public ComponentRepository(INHibernateService nhs) { _session = nhs.OpenSession(); } public Component Create(Component component) { using (var transaction = _session.BeginTransaction()) { _session.SaveOrUpdate(component); transaction.Commit(); return component; } } public bool DeleteById(int id) { using (var transaction = _session.BeginTransaction()) { var component = GetById(id); if (component == null) return false; _session.Delete(component); try { transaction.Commit(); } catch (GenericADOException e) { return false; } return true; } } public Component GetById(int id) { return _session.Get<Component>(id); } public Component Update(Component component) { using (var transaction = _session.BeginTransaction()) { _session.Update(component); transaction.Commit(); return component; } } public IList<Component> GetAll() { return _session.QueryOver<Component>().List(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using FluentNHibernate.Mapping; namespace StudIS.DAL.Mappings { public class ComponentMap : ClassMap<Component> { public ComponentMap() { Id(x => x.Id).GeneratedBy.Native(); Map(x => x.Name).Not.Nullable(); Map(x => x.MinimumPointsToPass); Map(x => x.MaximumPoints); References(x => x.Course); } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using StudIS.Web.Api.Controllers; using StudIS.Models.RepositoryInterfaces; using Moq; using StudIS.Services; using StudIS.Models.Users; namespace StudIS.Web.Api.Tests { [TestClass] public class LoginControllerTests { [TestMethod] public void Api_LoginTest_Correct() { var student = new Student() { Email = "<EMAIL>", PasswordHash = "xxx" }; Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); usrRepMock.Setup(u => u.GetByEmail(It.IsAny<string>())).Returns(student); var controller = new LoginController(usrRepMock.Object); var studentModel=controller.Index("<EMAIL>", "xxx"); Assert.IsNotNull(studentModel); } [TestMethod] public void Api_LoginTest_InCorrect() { var student = new Student() { Email = "<EMAIL>", PasswordHash = "xxx" }; Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); usrRepMock.Setup(u => u.GetByEmail(It.IsAny<string>())).Returns(student); var controller = new LoginController(usrRepMock.Object); var studentModel = controller.Index("<EMAIL>", "yyy"); Assert.IsNull(studentModel); } [TestMethod] public void Api_LoginTest_Admin() { var administrator = new Administrator() { Email = "<EMAIL>", PasswordHash = "xxx" }; Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); usrRepMock.Setup(u => u.GetByEmail(It.IsAny<string>())).Returns(administrator); var controller = new LoginController(usrRepMock.Object); var studentModel = controller.Index("<EMAIL>", "xxx"); Assert.IsNull(studentModel); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Models.Users { public class Administrator : User { } } <file_sep>using StudIS.Models; using StudIS.Models.RepositoryInterfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Services { public class ComponentServices { private IComponentRepository _componentRepository; private ICourseRepository _courseRepository; public ComponentServices(IComponentRepository componentRepository, ICourseRepository courseRepository) { _componentRepository = componentRepository; _courseRepository = courseRepository; } public Component CreateComponent(string name, int courseId, float minPointsToPass, float maxPoints) { var course = _courseRepository.GetById(courseId); if (course == null) return null; var component = new Component() { Name = name, Course = course, MinimumPointsToPass = minPointsToPass, MaximumPoints = maxPoints }; return _componentRepository.Create(component); } public Component UpdateComponent(string name, int componentId, float minPointsToPass, float maxPoints) { var component = _componentRepository.GetById(componentId); if (component == null) return null; component.Name = name; component.MinimumPointsToPass = minPointsToPass; component.MaximumPoints = maxPoints; return _componentRepository.Update(component); } public bool DeleteComponent(int id) { return _componentRepository.DeleteById(id); } public Component GetById(int id) { var component = _componentRepository.GetById(id); return component; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using StudIS.Models.Users; namespace StudIS.Web.Api.Models { public class SimpleStudentModel { public int Id { get; set; } public string Name { get; set; } public string Surname { get; set; } public string NationalIdentificationNumber { get; set; } public string Email { get; set; } public string FullName; public string StudentIdentificationNumber { get; set; } public SimpleStudentModel(Student student) { Id = student.Id; Name = student.Name; Surname = student.Surname; NationalIdentificationNumber = student.NationalIdentificationNumber; Email = student.Email; FullName = student.FullName; StudentIdentificationNumber = student.StudentIdentificationNumber; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using FluentNHibernate.Mapping; namespace StudIS.DAL.Mappings { public class CourseMap : ClassMap<Course> { public CourseMap() { Id(x => x.Id).GeneratedBy.Native(); Map(x => x.NaturalIdentifier) .Not.Nullable().Unique(); Map(x => x.Name).Not.Nullable(); Map(x => x.EctsCredits).Not.Nullable(); HasMany(x => x.Components).LazyLoad().Cascade.All(); HasManyToMany(x => x.LecturersInCharge).LazyLoad(); HasManyToMany(x => x.StudentsEnrolled).LazyLoad(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Models.Users { public class Student : User { public virtual string StudentIdentificationNumber { get; set; } public virtual IList<Course> CoursesEnrolledIn { get; set; } } } <file_sep>using StudIS.Models; using StudIS.Models.Users; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace StudIS.Web.Mvc.Models { public class StudentEnrollementViewModel { public IList<Score> scores { get; set; } public StudentEnrollementViewModel() { } public StudentEnrollementViewModel(IList<Score> scores) { this.scores = scores; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Models.Users { public class Lecturer : User { public virtual IList<Course> CoursesInChargeOf { get; set; } } } <file_sep>using System; using StudIS.Models.Users; using StudIS.Services; namespace StudIS.Desktop.Controllers { public class UserFormController { private readonly UserServices _userServices; private readonly CourseServices _courseServices; public UserFormController(UserServices userServices, CourseServices courseServices) { _userServices = userServices; _courseServices = courseServices; } public bool OpenFormNewUser(User user) { var existingUser = _userServices.GetUserByEmail(user.Email); if (existingUser != null) { return false; } var courses = _courseServices.GetAllCourses(); var userForm = new UserForm(this, user, courses); userForm.Show(); return true; } public bool OpenFormEditUser(string email) { var courses = _courseServices.GetAllCourses(); var user = _userServices.GetUserByEmail(email); if (user == null) { return false; } var userForm = new UserForm(this, user, courses); userForm.Show(); return true; } public bool DeleteUser(string email) { var user = _userServices.GetUserByEmail(email); if (user == null) { return false; } return _userServices.DeleteUserById(user.Id); } public bool SaveUser(User user) { try { if (_userServices.GetUserByEmail(user.Email) == null) { _userServices.CreateUser(user); } else { _userServices.UpdateUser(user); } return true; } catch (Exception ex) { return false; } } } } <file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using StudIS.DAL.Repositories; using StudIS.DAL.Tests; using StudIS.Models; using StudIS.Models.RepositoryInterfaces; using StudIS.Models.Users; using StudIS.Services; using StudIS.Web.Mvc.Controllers; using StudIS.Web.Mvc.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace StudIS.Web.Mvc.Tests { [TestClass] public class LecturerTests { private static readonly Student student = new Student() { Id = 1, Email = "<EMAIL>", PasswordHash = "<PASSWORD>", Name = "Example", Surname = "Examply", NationalIdentificationNumber = "124", StudentIdentificationNumber = "343" }; private static readonly Lecturer lecturer = new Lecturer() { Id = 1, Email = "<EMAIL>", PasswordHash = "<PASSWORD>", Name = "Sample", Surname = "Samply", NationalIdentificationNumber = "124", CoursesInChargeOf = new List<Course>() }; private static readonly Component component = new Component() { Id = 1, Course = course, Name = "Seminari", MaximumPoints = 40, MinimumPointsToPass = 20 }; private static readonly Course course = new Course() { Id = 1, Name = "<NAME>", NaturalIdentifier = "KVARC-FER-2016", EctsCredits = 5, StudentsEnrolled = new List<Student>(), LecturersInCharge = new List<Lecturer>(), Components = new List<Component>() }; private static readonly Score score = new Score() { Id = 1, Component = component, Student = student, Value = 10 }; public LecturerTests() { score.Component = component; score.Student = student; course.StudentsEnrolled.Add(student); course.LecturersInCharge.Add(lecturer); course.Components.Add(component); component.Course = course; lecturer.CoursesInChargeOf.Add(course); } [TestMethod] public void MVC_LecturerTests_DisplayPersonalData() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(1)).Returns(lecturer); var controller = new LecturerController(corRepMock.Object, scrRepMock.Object, usrRepMock.Object, comRepMock.Object); var controllerContext = new Mock<ControllerContext>(); controllerContext.SetupGet(p => p.HttpContext.Session["userId"]).Returns(1); controllerContext.SetupGet(p => p.HttpContext.Session["email"]).Returns("<EMAIL>"); controller.ControllerContext = controllerContext.Object; var result = controller.PersonalData() as ViewResult; var viewModel = (LecturerViewModel)result.ViewData.Model; Assert.AreEqual(lecturer.Email, viewModel.Email); } [TestMethod] public void MVC_LecturerTests_EnrolledStudents() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(1)).Returns(lecturer); corRepMock.Setup(c => c.GetById(1)).Returns(course); IList<Component> components = new List<Component>(); comRepMock.Setup(c => c.GetAll()).Returns(components); IList<Score> scores = new List<Score>(); scrRepMock.Setup(c => c.GetAll()).Returns(scores); usrRepMock.Setup(c => c.GetByCourse(It.IsAny<Course>())).Returns(new List<Student>() { student}); var controller = new LecturerController(corRepMock.Object, scrRepMock.Object, usrRepMock.Object, comRepMock.Object); var controllerContext = new Mock<ControllerContext>(); controllerContext.SetupGet(p => p.HttpContext.Session["userId"]).Returns(1); controllerContext.SetupGet(p => p.HttpContext.Session["email"]).Returns("<EMAIL>"); controller.ControllerContext = controllerContext.Object; var result = controller.StudentsEnrolled(1, false) as ViewResult; var viewModel = (List<StudentEnrollementViewModel>)result.ViewData.Model; Assert.AreEqual(1, viewModel.Count); } [TestMethod] public void MVC_LecturerTests_Index() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(1)).Returns(lecturer); corRepMock.Setup(c => c.GetByLecturerInChargerId(1)).Returns(new List<Course>() { course}); comRepMock.Setup(c => c.GetById(1)).Returns(component); scrRepMock.Setup(c => c.GetById(1)).Returns(score); //GetByLecturerInChargerId var controller = new LecturerController(corRepMock.Object, scrRepMock.Object, usrRepMock.Object, comRepMock.Object); var controllerContext = new Mock<ControllerContext>(); controllerContext.SetupGet(p => p.HttpContext.Session["userId"]).Returns(1); controllerContext.SetupGet(p => p.HttpContext.Session["email"]).Returns("<EMAIL>"); controller.ControllerContext = controllerContext.Object; var result = controller.Index() as ViewResult; var viewModel = (IList<LecturerCourseViewModel>)result.ViewData.Model; Assert.AreEqual(1, viewModel.Count); } } } <file_sep># StudIS Repozitorij sadrži projekt/seminar iz Objektnog oblikovanja za grupu **ExceptionCollection**, ak. godina 2016./2017. Dokumentacija: [Seminar-StudIS.docx](Seminar-StudIS.docx) ## Članovi tima - <NAME> - *<NAME>* (voditelj) - <NAME> - <NAME> ## Alati i tehnologije Sustav je razvijen koristeći Visual Studio i Android Studio uz sljedeće tehnologije za pojedina sučelja: - Windows Forms za desktop - ASP.NET MVC za korisničko web sučelje - ASP.NET WebAPI2 sučelje za mobilne i ostale klijente - Android aplikacija ## Upute za pokretanje ### Baza podataka #### Stvaranje datoteke Koristi se MSSQL Express Server i file baza podataka naziva ``StudIS_DB.mdf``. **Datoteku je potrebno ručno stvoriti u putanji ``C:\Users\Public\databases``** (npr. iz Visual Studia, desni klik na projekt i *New -> Item -> Data -> Service-based Database*, nazvati ``StudIS_DB.mdf`` i nakon toga premjestiti u spomenutu putanju). #### Schema export i punjenje baze početnim podacima (*Seed*) - Potrebno je u projektu ``StudIS.DAL`` u datoteci ``NHibernateService.cs`` u metodi ``ISessionFactory OpenSessionFactory()`` odkomentirati redak ``.ExposeConfiguration(cfg => new NHibernate.Tool.hbm2ddl.SchemaExport(cfg).Execute(true, true, false))`` kako bi se prilikom pokretanja izgradila shema baze podataka. - Pokrenuti projekt ``StudIS.DatabaseSeed`` da bi se prazna baza napunila testnim podacima (i prethodno se izvede Schema Export). Ovaj korak izvršiti samo jednom nad istom datotekom baze podataka. - Zakomentirati prethodno odkomentirati redak za SchemaExport Sada je sustav spreman za pokretanje korisničkih sučelja. ### Desktop sučelje Pokrenuti projekt ``StudIS.Desktop``. ### Web sučelje Pokrenuti projekt ``StudIS.Web.Mvc``. ### WebAPI2 sučelje Pokrenuti projekt ``StudIS.Web.Api``. <file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using StudIS.DAL.Repositories; using StudIS.DAL.Tests; using StudIS.Models; using StudIS.Models.RepositoryInterfaces; using StudIS.Models.Users; using StudIS.Services; using StudIS.Web.Mvc.Controllers; using StudIS.Web.Mvc.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace StudIS.Web.Mvc.Tests { [TestClass] public class StudentTests { private static readonly Student student = new Student() { Id = 1, Email = "<EMAIL>", PasswordHash = "<PASSWORD>", Name = "Example", Surname = "Examply", NationalIdentificationNumber = "124", StudentIdentificationNumber = "343" }; private static readonly Lecturer lecturer = new Lecturer() { Id = 2, Email = "<EMAIL>", PasswordHash = "<PASSWORD>", Name = "Sample", Surname = "Samply", NationalIdentificationNumber = "124" }; private static readonly Component component = new Component() { Id = 534, Course = course, Name = "Seminari", MaximumPoints = 40, MinimumPointsToPass = 20 }; private static readonly Course course = new Course() { Id=1, Name = "<NAME>", NaturalIdentifier = "KVARC-FER-2016", EctsCredits = 5, StudentsEnrolled = new List<Student>() { student }, LecturersInCharge = new List<Lecturer>() { lecturer }, Components = new List<Component>() { component } }; private static readonly Score score = new Score() { Id = 1, Component = component, Student = student, Value = 10 }; public StudentTests() { } [TestMethod] public void MVC_StudentTests_DisplayScoreInfo() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); corRepMock.Setup(c => c.GetById(1)).Returns(course); usrRepMock.Setup(c => c.GetById(1)).Returns(student); scrRepMock.Setup(c => c.GetByStudentIdAndComponentId(It.IsAny<Student>(), It.IsAny<Component>())).Returns(score); var controller = new StudentController(corRepMock.Object, scrRepMock.Object, usrRepMock.Object, comRepMock.Object); var controllerContext = new Mock<ControllerContext>(); controllerContext.SetupGet(p => p.HttpContext.Session["userId"]).Returns(1); controllerContext.SetupGet(p => p.HttpContext.Session["email"]).Returns("<EMAIL>"); controller.ControllerContext = controllerContext.Object; var result=controller.ScoreInfo(1) as ViewResult; var viewModel = (ScoredCourseViewModel)result.ViewData.Model; Assert.AreEqual("<NAME>", viewModel.Name); } [TestMethod] public void MVC_StudentTests_DisplayPersonalData() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(1)).Returns(student); var controller = new StudentController(corRepMock.Object, scrRepMock.Object, usrRepMock.Object, comRepMock.Object); var controllerContext = new Mock<ControllerContext>(); controllerContext.SetupGet(p => p.HttpContext.Session["userId"]).Returns(1); controllerContext.SetupGet(p => p.HttpContext.Session["email"]).Returns("<EMAIL>"); controller.ControllerContext = controllerContext.Object; var result = controller.PersonalData() as ViewResult; var viewModel = (StudentViewModel)result.ViewData.Model; Assert.AreEqual(student.Email, viewModel.Email); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using StudIS.Models.RepositoryInterfaces; using NHibernate; using NHibernate.Criterion; using StudIS.Models.Users; namespace StudIS.DAL.Repositories { public class ScoreRepository : IScoreRepository { private ISession _session; public ScoreRepository(INHibernateService nhs) { _session = nhs.OpenSession(); } public Score Create(Score score) { using (var transaction = _session.BeginTransaction()) { _session.Save(score); transaction.Commit(); return score; } } public Score Update(Score score) { using (var transaction = _session.BeginTransaction()) { _session.Update(score); transaction.Commit(); return score; } } public Score CreateOrUpdate(Score score) { using (var transaction = _session.BeginTransaction()) { _session.SaveOrUpdate(score); transaction.Commit(); return score; } } public Score GetById(int id) { return _session.Get<Score>(id); } public IList<Score> GetAll() { return _session.QueryOver<Score>().JoinQueryOver<Component>(c => c.Component).List(); } public Score GetByStudentIdAndComponentId(Student student, Component component) { var varijabla = _session.QueryOver<Score>().Where(sc => sc.Student == student).Where(sc => sc.Component == component).SingleOrDefault(); return varijabla; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using StudIS.Web.Api.Models; using StudIS.Services; using StudIS.DAL.Repositories; using StudIS.DAL; using StudIS.Models.Users; using StudIS.Models.RepositoryInterfaces; namespace StudIS.Web.Api.Controllers { public class LoginController : ApiController { private IUserRepository _usrRep; public LoginController(IUserRepository usrRep) { _usrRep = usrRep; } /// <summary> /// Returns simple student model for mobile application, returns null if the data is wrong or a user is not student /// </summary> /// <param name="email"></param> /// <param name="passwordHash"></param> /// <returns></returns> /// [HttpPost] [HttpGet] public SimpleStudentModel Index(String email, String passwordHash) { var service = new LoginService(_usrRep); var user = service.LoginUser(email, passwordHash); if (user == null) return null; else if (UserServices.IsUserStudent(user)) return new SimpleStudentModel((Student)user); else return null; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using NHibernate; using StudIS.DAL.Mappings; using System.Data.SqlClient; using System.IO; using NHibernate.Cfg; namespace StudIS.DAL.Tests { public class NHibernateService2 : INHibernateService { private static ISessionFactory _sessionFactory; private ISession _session; Configuration confg; public NHibernateService2() { OpenSessionFactory(); } public ISession OpenSession() { try { if (_sessionFactory == null) { _sessionFactory = OpenSessionFactory(); } ISession session = _session;//_sessionFactory.OpenSession(_session.Connection); return session; } catch (Exception e) { throw e.InnerException ?? e; } } private ISessionFactory OpenSessionFactory() { var nhConfig = Fluently.Configure() .Diagnostics(diag => diag.Enable().OutputToConsole()) //.Database(SQLiteConfiguration.Standard // .ConnectionString("Data Source=TestNHibernate_fluent.db;Version=3") // .AdoNetBatchSize(100)) .Database(SQLiteConfiguration.Standard .InMemory() // .UsingFile("C:\\Users\\Zlatko\\Source\\Repos\\OO-projekt\\StudIS\\SQLliteConfig\\bin\\Debug\\firstProject.db") ) .Mappings(mappings => mappings.FluentMappings.Add<AdministratorMap>()) .Mappings(mappings => mappings.FluentMappings.Add<LecturerMap>()) .Mappings(mappings => mappings.FluentMappings.Add<UserMap>()) .Mappings(mappings => mappings.FluentMappings.Add<CourseMap>()) .Mappings(mappings => mappings.FluentMappings.Add<ComponentMap>()) .Mappings(mappings => mappings.FluentMappings.Add<ScoreMap>()) .Mappings(mappings => mappings.FluentMappings.Add<StudentMap>()) .ExposeConfiguration(cfg =>confg=cfg) .BuildConfiguration(); var sessionFactory = nhConfig.BuildSessionFactory(); _sessionFactory = sessionFactory; _session = sessionFactory.OpenSession(); new NHibernate.Tool.hbm2ddl.SchemaExport(confg).Execute(true, true, false,_session.Connection,null); return sessionFactory; } /* * //public IDatabase Database { private get; set; } //public NhibernateService(IDatabase database) //{ // Database = database; //} public void CreateDatabaseAndSchema() { _sessionFactory = null; //obriše se eventualni prošli session if (Database == null) { return; } Database.CreateDatabase(Database.DBInfo); CreateSchema(); } private void CreateSchema() { var configuration = Database.GetFluentConfiguration(); configuration.Mappings(m => m.FluentMappings.AddFromAssemblyOf<InspectionMapping>()). ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true)). BuildSessionFactory(); } public ISession CreateSchemaOpenSession(IDatabaseInfo inDB) { _sessionFactory = null; //obriše se eventualni prošli session if (Database == null) { return null; } CreateSchema(); return OpenSession(); } */ } } <file_sep>using StudIS.Models.Users; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace StudIS.Web.Mvc.Models { public class LecturerViewModel { public int Id { get; set; } public string Name { get; set; } public string Surname { get; set; } public string NationalIdentificationNumber { get; set; } public string Email { get; set; } public string FullName { get; set; } public LecturerViewModel() { } public LecturerViewModel(Lecturer lecturer) { Id = lecturer.Id; Name = lecturer.Name; Surname = lecturer.Surname; NationalIdentificationNumber = lecturer.NationalIdentificationNumber; Email = lecturer.Email; FullName = lecturer.FullName; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace StudIS.Web.Mvc.Controllers { public class HomeController : Controller { public ActionResult Index(Boolean error = false) { if ((String)Session["userType"] == "Student") return RedirectToAction("Index", "Student"); else if ((String)Session["userType"] == "Lecturer") return RedirectToAction("Index", "Lecturer"); return View(error); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using StudIS.Models.Users; using FluentNHibernate.Mapping; namespace StudIS.DAL.Mappings { public class LecturerMap : SubclassMap<Lecturer> { public LecturerMap() { DiscriminatorValue("lecturer"); HasManyToMany(x => x.CoursesInChargeOf); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Models.Users { public abstract class User { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual string Surname { get; set; } public virtual string NationalIdentificationNumber { get; set; } //public virtual Credentials UserCredentials { get; set; } public virtual string Email { get; set; } public virtual string PasswordHash { get; set; } public virtual string FullName { get { return Name + " " + Surname; } } } } <file_sep>using StudIS.Models; using StudIS.Models.Users; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace StudIS.Web.Mvc.Models { public class ScoreViewModel { public int Id { get; set; } public float Value { get; set; } public string ComponentName { get; set; } public float ComponentMinToPass { get; set; } public float ComponentMax { get; set; } public ScoreViewModel(Score score) { Id = score.Id; Value = score.Value; ComponentName = score.Component.Name; ComponentMinToPass = score.Component.MinimumPointsToPass; ComponentMax = score.Component.MaximumPoints; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using StudIS.Models.RepositoryInterfaces; using NHibernate; using NHibernate.Criterion; using StudIS.Models.Users; namespace StudIS.DAL.Repositories { public class CourseRepository : ICourseRepository { private ISession _session; public CourseRepository(INHibernateService nhs) { _session = nhs.OpenSession(); } public Course Create(Course course) { using (var transaction = _session.BeginTransaction()) { _session.Save(course); transaction.Commit(); return course; } } public bool DeleteById(int id) { using (var transaction = _session.BeginTransaction()) { var course = GetById(id); if (course == null) return false; _session.Delete(course); transaction.Commit(); return true; } } public bool DeleteByNaturalIdentifier(string naturalIdentifier) { using (var transaction = _session.BeginTransaction()) { var user = GetByNaturalIdentifier(naturalIdentifier); if (user == null) return false; _session.Delete(user); transaction.Commit(); return true; } } public IList<Course> GetAll() { return _session.QueryOver<Course>().List(); } public Course GetById(int id) { return _session.Get<Course>(id); } public Course GetByNaturalIdentifier(string naturalIdentifier) { return _session.CreateCriteria<Course>() .Add(Expression.Like("NaturalIdentifier", naturalIdentifier)) .UniqueResult<Course>(); } public IList<Course> GetByStudentEnroledId(int userId) { var users = _session.QueryOver<Course>() .Right.JoinQueryOver<User>(c => c.StudentsEnrolled) .Where(u => u.Id == userId) .List(); if (users[0] == null) return null; return users; } public IList<Course> GetByLecturerInChargerId(int lecturerId) { var coursesInCharge = _session.QueryOver<Course>() .Right.JoinQueryOver<User>(c => c.LecturersInCharge) .Where(u => u.Id == lecturerId) .List(); if (coursesInCharge[0] == null) return null; return coursesInCharge; } public Course Update(Course course) { using (var transaction = _session.BeginTransaction()) { _session.Update(course); transaction.Commit(); return course; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using StudIS.Models.Users; using FluentNHibernate.Mapping; namespace StudIS.DAL.Mappings { public class StudentMap : SubclassMap<Student> { public StudentMap() { DiscriminatorValue("student"); Map(x => x.StudentIdentificationNumber); //References(x => x.CoursesEnrolledIn); HasManyToMany(x => x.CoursesEnrolledIn); } } } <file_sep>using StudIS.Models; using StudIS.Models.RepositoryInterfaces; using StudIS.Models.Users; using StudIS.Services; using StudIS.Web.Mvc.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Helpers; using System.Web.Mvc; namespace StudIS.Web.Mvc.Controllers { public class LecturerController : Controller { private ICourseRepository _courseRepository; private IScoreRepository _scoreRepository; private IUserRepository _userRepository; private IComponentRepository _componentRepository; public LecturerController(ICourseRepository courseRepository, IScoreRepository scoreRepository, IUserRepository userRepository, IComponentRepository componentRepository) { _courseRepository = courseRepository; _scoreRepository = scoreRepository; _userRepository = userRepository; _componentRepository = componentRepository; } public ActionResult Index() { if (Session["userId"] == null) return RedirectToAction("Index", "Home"); ViewBag.Email = Session["email"]; ViewBag.Title = "Predmeti"; int userId = (int)Session["userId"]; List<LecturerCourseViewModel> courseList = new List<LecturerCourseViewModel>(); var courseServices = new CourseServices(_courseRepository, _userRepository, _componentRepository); var courses = courseServices.GetCoursesByLecturerId(userId); if (courses != null) { foreach (var course in courses) { courseList.Add(new LecturerCourseViewModel(course)); } } return View(courseList); } public ActionResult PersonalData() { if (Session["userId"] == null) return RedirectToAction("Index", "Home"); ViewBag.Email = Session["email"]; ViewBag.Title = "Osobni podaci"; var lecturerId = (int)Session["userId"]; var userServices = new UserServices(_userRepository); var user = userServices.GetUserById(lecturerId); if (user == null || !UserServices.IsUserLecturer(user)) return RedirectToAction("Index", "Home"); return View(new LecturerViewModel((Lecturer)user)); } public ActionResult Component(int id) { if (Session["userId"] == null) return RedirectToAction("Index", "Home"); var courseServices = new CourseServices(_courseRepository, _userRepository, _componentRepository); var course = courseServices.GetCourseById(id); ViewBag.Title = course.Name; ViewBag.Email = Session["email"]; ViewBag.Id = course.Id; if (course == null) return RedirectToAction("Index", "Home"); IList<ComponentViewModel> components = new List<ComponentViewModel>(); foreach (var component in course.Components) { components.Add(new ComponentViewModel(component)); } return View(components); } public ActionResult EditComponent(int id) { if (Session["userId"] == null) return RedirectToAction("Index", "Home"); var componentServices = new ComponentServices(_componentRepository, _courseRepository); var component = componentServices.GetById(id); ViewBag.Title = component.Name + " " + component.Course.Name; ViewBag.Email = Session["email"]; return View(new ComponentViewModel(component)); } [HttpPost] public ActionResult EditComponent(ComponentViewModel comp) { var componentServices = new ComponentServices(_componentRepository, _courseRepository); var component = componentServices.UpdateComponent(comp.Name, comp.Id, comp.MinimumPointsToPass, comp.MaximumPoints); return RedirectToAction("Component", "Lecturer", new { id = comp.CourseId }); } public ActionResult DeleteComponent(int id, bool? error) { if (Session["userId"] == null) return RedirectToAction("Index", "Home"); if (error == true) { ModelState.AddModelError("error", "Ne možete pobrisati komponentu koja ima upisane bodove studentima!"); } var componentServices = new ComponentServices(_componentRepository, _courseRepository); var component = componentServices.GetById(id); ViewBag.Title = component.Name + " " + component.Course.Name; ViewBag.Email = Session["email"]; return View(new ComponentViewModel(component)); } [HttpPost, ActionName("DeleteComponent")] [ValidateAntiForgeryToken] public ActionResult DeleteComponentConfirmed(int id) { if (Session["userId"] == null) return RedirectToAction("Index", "Home"); var componentServices = new ComponentServices(_componentRepository, _courseRepository); if (!componentServices.DeleteComponent(id)) { return RedirectToAction("DeleteComponent", "Lecturer", new { id = id, error = true }); } return RedirectToAction("Index", "Lecturer"); } public ActionResult CreateComponent(int id) { if (Session["userId"] == null) return RedirectToAction("Index", "Home"); ViewBag.Title = "Nova komponenta"; ViewBag.Email = Session["email"]; var courseServices = new CourseServices(_courseRepository, _userRepository, _componentRepository); var course = courseServices.GetCourseById(id); Component newComponent = new Component() { Course = course }; return View(new ComponentViewModel(newComponent)); } [HttpPost] public ActionResult CreateComponent(ComponentViewModel comp) { var courseServices = new CourseServices(_courseRepository, _userRepository, _componentRepository); var course = courseServices.GetCourseById(comp.Id); var componentServices = new ComponentServices(_componentRepository, _courseRepository); var component = componentServices.CreateComponent(comp.Name, comp.CourseId, comp.MinimumPointsToPass, comp.MaximumPoints); return RedirectToAction("Component", "Lecturer", new { id = comp.CourseId }); } public ActionResult StudentsEnrolled(int id, bool? error) { if (Session["userId"] == null) return RedirectToAction("Index", "Home"); ViewBag.Email = Session["email"]; if (error == true) ModelState.AddModelError("prag_error", "Nemoguće unjeti više bodova od maksimalnog broj bodova po komponenti!"); var courseServices = new CourseServices(_courseRepository, _userRepository, _componentRepository); var course = courseServices.GetCourseById(id); ViewBag.Title = course.Name; var studentServices = new StudentServices(_userRepository); var scoreServices = new ScoreServices(_scoreRepository, _courseRepository, _userRepository); IList<Student> enrolledStudents = studentServices.GetStudentsByCourse(course); IList<StudentEnrollementViewModel> enroll = new List<StudentEnrollementViewModel>(); foreach (Student s in enrolledStudents) { IList<Score> score = scoreServices.GetScorebyStudentAndCourse(s.Id, course.Id); enroll.Add(new StudentEnrollementViewModel(score)); } return View(enroll); } [HttpPost] public ActionResult StudentsEnrolled(IEnumerable<StudentEnrollementViewModel> list) { var scoreServices = new ScoreServices(_scoreRepository, _courseRepository, _userRepository); var componentServices = new ComponentServices(_componentRepository, _courseRepository); var userServices = new UserServices(_userRepository); foreach (var s in list) { foreach (var scor in s.scores) { Score ss = new Score() { Id = scor.Id, Value = scor.Value, Component = componentServices.GetById(scor.Component.Id), Student = (Student)userServices.GetUserById(scor.Student.Id) }; if (ss.Value > ss.Component.MaximumPoints) return RedirectToAction("StudentsEnrolled", "Lecturer", new { id = ss.Component.Course.Id, error = true }); else scoreServices.SaveScore(ss); } } return RedirectToAction("Index", "Lecturer"); } public ActionResult ComponentStatistics(int id) { if (Session["userId"] == null) return RedirectToAction("Index", "Home"); ViewBag.Email = Session["email"]; ViewBag.Title = "Statistics"; var courseService = new CourseServices(_courseRepository, _userRepository, _componentRepository); var componentService = new ComponentServices(_componentRepository, _courseRepository); var scoreService = new ScoreServices(_scoreRepository, _courseRepository, _userRepository); var course = courseService.GetCourseById(id); IList<Component> comp = new List<Component>(); foreach (var c in course.Components) { comp.Add(c); } IList<ComponentStatisticsViewModel> results = new List<ComponentStatisticsViewModel>(); foreach (var c in comp) { var scores = scoreService.GetByComponent(c.Id); float sum = 0; float maxSum = 0; foreach (var s in scores) { sum += s.Value; maxSum += c.MaximumPoints; } results.Add(new ComponentStatisticsViewModel(c.Name, maxSum==0?0:(float)sum / maxSum, c.MaximumPoints, c.Course.Id)); } return View(results); } } }<file_sep>using StudIS.Models.Users; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Models.RepositoryInterfaces { public interface IScoreRepository { //IList<Score> GetByStudentAndCourse(int studentId, int CourseId); Score Create(Score score); Score Update(Score score); Score CreateOrUpdate(Score score); Score GetById(int id); Score GetByStudentIdAndComponentId(Student student, Component component); IList<Score> GetAll(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace StudIS.Web.Mvc.Models { public class ScoredCourseViewModel { public String Name { get; set; } public List<ScoreViewModel> scoreList{get;set;} public float cumulativeScore { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using StudIS.Models; using StudIS.Models.Users; using StudIS.Models.RepositoryInterfaces; using StudIS.DAL; using StudIS.DAL.Repositories; using StudIS.Desktop.Controllers; using StudIS.Services; namespace StudIS.Desktop { public partial class UserForm : Form { private readonly UserFormController _userFormController; private User _user; private readonly IList<Course> _courses; public UserForm( UserFormController userFormController, User user, IList<Course> courses) { _userFormController = userFormController; _user = user; _courses = courses; InitializeComponent(); this.Text = user.FullName + " (" + user.Email + ")"; this.nameTextBox.Text = user.Name; this.surnameTextBox.Text = user.Surname; this.nationalIdentificationNumberTextBox.Text = user.NationalIdentificationNumber; this.emailTextBox.Text = _user.Email; var checkedCoursesIds = new List<int>(); if (_user is Student) { this.studentIdentificationNumberTextBox .Text = ((Student)_user).StudentIdentificationNumber; checkedCoursesIds = ((Student)_user) .CoursesEnrolledIn.Select(x => x.Id).ToList(); } else if (_user is Lecturer) { this.studentIdentificationNumberTextBox.Enabled = false; checkedCoursesIds = ((Lecturer)_user) .CoursesInChargeOf.Select(x => x.Id).ToList(); } else { this.studentIdentificationNumberTextBox.Enabled = false; this.coursesCheckedListBox.Enabled = false; this.coursesGroupBox.Enabled = false; } ListBox coursesListBox = coursesCheckedListBox; coursesListBox.DataSource = courses.ToList(); coursesListBox.DisplayMember = "NaturalIdentifier"; for (int i = 0; i < coursesListBox.Items.Count; ++i) { var course = (Course)coursesListBox.Items[i]; if (checkedCoursesIds.Contains(course.Id)) { coursesCheckedListBox.SetItemChecked(i, true); } } } private void saveButton_Click(object sender, EventArgs e) { _user.Name = this.nameTextBox.Text; _user.Surname = this.surnameTextBox.Text; _user.NationalIdentificationNumber = this.nationalIdentificationNumberTextBox.Text; _user.Email = this.emailTextBox.Text; var password = this.passwordTextBox.Text; if (password.Length > 0) { _user.PasswordHash = EncryptionService.EncryptSHA1(password); } if (_user.Email.Length == 0 || _user.Name.Length == 0 || _user.Surname.Length == 0 || _user.NationalIdentificationNumber.Length == 0 || (_user.PasswordHash == null || _user.PasswordHash.Length == 0)) { MessageBox.Show("Nisu popunjena sva polja", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } var checkedCoursesIndices = this.coursesCheckedListBox.CheckedIndices; var checkedCourses = new List<Course>(); foreach (int courseIndex in checkedCoursesIndices) { var courseId = ((Course)this.coursesCheckedListBox.Items[courseIndex]).Id; checkedCourses.Add(_courses.First(x => x.Id == courseId)); } if(_user is Student) { Student student = (Student)_user; student.StudentIdentificationNumber = this.studentIdentificationNumberTextBox.Text; student.CoursesEnrolledIn = checkedCourses; } if(_user is Lecturer) { Lecturer lecturer = (Lecturer)_user; lecturer.CoursesInChargeOf = checkedCourses; } var success = _userFormController.SaveUser(_user); if (success) { this.Close(); } else { MessageBox.Show("Pohrana nije uspjela."); } } private void passwordTextBox_TextChanged(object sender, EventArgs e) { if (this.passwordTextBox.TextLength > 0) { this.passwordLabel.Text = "Lozinka (*)"; } } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using StudIS.Models.RepositoryInterfaces; using StudIS.DAL; using StudIS.Models.Users; using StudIS.Services; using StudIS.DAL.Repositories; using StudIS.Desktop.Controllers; using StudIS.DAL.Tests; namespace StudIS.Desktop.Tests { [TestClass] public class UserFormTests { private readonly IUserRepository _userRepository; private readonly ICourseRepository _courseRepository; private readonly IComponentRepository _componentRepository; private readonly IScoreRepository _scoreRepository; private readonly UserServices _userServices; private readonly CourseServices _courseServices; private readonly ScoreServices _scoreServices; private readonly Student student = new Student() { Email = "<EMAIL>", PasswordHash = "<PASSWORD>", Name = "Sample", Surname = "Sample", NationalIdentificationNumber = "124", StudentIdentificationNumber = "343" }; public UserFormTests() { var nhs = new NHibernateService2(); _userRepository = new UserRepository(nhs); _courseRepository = new CourseRepository(nhs); _componentRepository = new ComponentRepository(nhs); _scoreRepository = new ScoreRepository(nhs); _userServices = new UserServices(_userRepository); _courseServices = new CourseServices(_courseRepository, _userRepository, _componentRepository); _scoreServices = new ScoreServices(_scoreRepository, _courseRepository, _userRepository); } [TestMethod] public void UserForm_CreateUser() { var controller = new UserFormController(_userServices, _courseServices); var success = controller.SaveUser(student); Assert.IsTrue(success); } [TestMethod] public void UserForm_TryDeleteNonExistingUser() { var controller = new UserFormController(_userServices, _courseServices); var success = controller.DeleteUser(student.Email); Assert.IsFalse(success); } [TestMethod] public void UserForm_CreateAndDeleteUser() { this.UserForm_CreateUser(); var controller = new UserFormController(_userServices, _courseServices); var deletionSuccess = controller.DeleteUser("<EMAIL>"); Assert.IsTrue(deletionSuccess); } [TestMethod] public void UserForm_CreateAndEditUser() { this.UserForm_CreateUser(); var controller = new UserFormController(_userServices, _courseServices); var newName = "Pero"; var newSurname = "Djetlic"; student.Name = newName; student.Surname = newSurname; var editSuccess = controller.SaveUser(student); var editedUser = _userRepository.GetByEmail(student.Email); Assert.IsTrue(editSuccess); Assert.AreEqual(newName, editedUser.Name); Assert.AreEqual(newSurname, editedUser.Surname); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models.RepositoryInterfaces; using StudIS.Models; using StudIS.Models.Users; namespace StudIS.Services { public class LoginService { private IUserRepository _userRepositry; public LoginService(IUserRepository userRepository) { _userRepositry = userRepository; } /// <summary> /// Gets the details of the user with corresponding email and password hash /// </summary> /// <param name="email"></param> /// <param name="passwordHash"></param> /// <returns>returns user if user exists, null othervise</returns> public User LoginUser(String email, String passwordHash) { var user = _userRepositry.GetByEmail(email); if (user == null) return null; else if (user.PasswordHash.ToUpper() == passwordHash.ToUpper()) { return user; } else { return null; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using FluentNHibernate.Mapping; using StudIS.Models.Users; namespace StudIS.DAL.Mappings { public class UserMap : ClassMap<User> { public UserMap() { Id(x => x.Id).GeneratedBy.Native(); Map(x => x.Name).Not.Nullable(); Map(x => x.Surname).Not.Nullable(); Map(x => x.NationalIdentificationNumber) .Not.Nullable().Unique(); Map(x => x.Email).Unique().Not.Nullable(); Map(x => x.PasswordHash).Not.Nullable(); DiscriminateSubClassesOnColumn("role"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using FluentNHibernate.Mapping; namespace StudIS.DAL.Mappings { public class ScoreMap : ClassMap<Score> { public ScoreMap() { Id(x => x.Id).GeneratedBy.Native(); Map(x => x.Value).Not.Nullable(); References(x => x.Component).LazyLoad(); References(x => x.Student).LazyLoad(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using StudIS.Models.Users; using FluentNHibernate.Mapping; namespace StudIS.DAL.Mappings { public class AdministratorMap : SubclassMap<Administrator> { public AdministratorMap() { DiscriminatorValue("administrator"); } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using StudIS.Models.RepositoryInterfaces; using Moq; using StudIS.Models.Users; using StudIS.Web.Api.Controllers; using StudIS.Models; using System.Collections.Generic; namespace StudIS.Web.Api.Tests { [TestClass] public class StudentDataControllerTests { [TestMethod] public void Api_GetStudentDataTest_CorrectId() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(It.IsAny<int>())).Returns(new Student()); var controller = new StudentDataController(usrRepMock.Object, corRepMock.Object, scrRepMock.Object, comRepMock.Object); var data =controller.GetStudentData(1); Assert.IsNotNull(data); } [TestMethod] public void Api_GetStudentDataTest_InCorrectUserType() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(It.IsAny<int>())).Returns(new Lecturer()); var controller = new StudentDataController(usrRepMock.Object, corRepMock.Object, scrRepMock.Object, comRepMock.Object); var data = controller.GetStudentData(1); Assert.IsNull(data); } [TestMethod] public void Api_GetStudentDataTest_InCorrectId() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(It.IsAny<int>())).Returns<User>(null); var controller = new StudentDataController(usrRepMock.Object, corRepMock.Object, scrRepMock.Object, comRepMock.Object); var data = controller.GetStudentData(1); Assert.IsNull(data); } [TestMethod] public void Api_GetCoursesByStudentIdTest_Correct() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(It.IsAny<int>())).Returns(new Student()); var courseList = new List<Course>(); courseList.Add(new Course()); corRepMock.Setup(c => c.GetByStudentEnroledId(It.IsAny<int>())).Returns(courseList); var controller = new StudentDataController(usrRepMock.Object, corRepMock.Object, scrRepMock.Object, comRepMock.Object); var data = controller.GetCoursesByStudentId(1); Assert.IsNotNull(data); } [TestMethod] public void Api_GetCoursesByStudentIdTest_InCorrectUser() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(It.IsAny<int>())).Returns(new Administrator()); var courseList = new List<Course>(); courseList.Add(new Course()); corRepMock.Setup(c => c.GetByStudentEnroledId(It.IsAny<int>())).Returns(courseList); var controller = new StudentDataController(usrRepMock.Object, corRepMock.Object, scrRepMock.Object, comRepMock.Object); var data = controller.GetCoursesByStudentId(1); Assert.IsNull(data); } [TestMethod] public void Api_GetCoursesByStudentIdTest_NoCourses() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(It.IsAny<int>())).Returns(new Student()); var courseList = new List<Course>(); corRepMock.Setup(c => c.GetByStudentEnroledId(It.IsAny<int>())).Returns(courseList); var controller = new StudentDataController(usrRepMock.Object, corRepMock.Object, scrRepMock.Object, comRepMock.Object); var data = controller.GetCoursesByStudentId(1); Assert.IsNotNull(data); Assert.IsTrue(data.Count == 0); } } } <file_sep>using StudIS.Models; using StudIS.Models.RepositoryInterfaces; using StudIS.Models.Users; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Services { public class StudentServices { private IUserRepository _userRepository; public StudentServices(IUserRepository userRepository) { _userRepository = userRepository; } public Student getStudentdata(int id) { var user = _userRepository.GetById(id); if (user != null && UserServices.IsUserStudent(user)) return (Student)user; return null; } public IList<Student> GetStudentsByCourse(Course course) { return _userRepository.GetByCourse(course); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using StudIS.Models.Users; namespace StudIS.Models.RepositoryInterfaces { public interface ICourseRepository { IList<Course> GetAll(); Course GetById(int id); Course GetByNaturalIdentifier(string naturalIdentifier); IList<Course> GetByStudentEnroledId(int userId); IList<Course> GetByLecturerInChargerId(int lecturerId); bool DeleteById(int id); bool DeleteByNaturalIdentifier(string naturalIdentifier); Course Update(Course course); Course Create(Course course); } } <file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using StudIS.DAL.Repositories; using StudIS.DAL.Tests; using StudIS.Models; using StudIS.Models.RepositoryInterfaces; using StudIS.Models.Users; using StudIS.Services; using StudIS.Web.Mvc.Controllers; using StudIS.Web.Mvc.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace StudIS.Web.Mvc.Tests { [TestClass] public class ComponentTests { private static readonly Student student = new Student() { Id = 1, Email = "<EMAIL>", PasswordHash = "<PASSWORD>", Name = "Example", Surname = "Examply", NationalIdentificationNumber = "124", StudentIdentificationNumber = "343" }; private static readonly Lecturer lecturer = new Lecturer() { Id = 1, Email = "<EMAIL>", PasswordHash = "<PASSWORD>", Name = "Sample", Surname = "Samply", NationalIdentificationNumber = "124", CoursesInChargeOf = new List<Course>() }; private static readonly Component component = new Component() { Id = 1, Course = course, Name = "Seminari", MaximumPoints = 40, MinimumPointsToPass = 20 }; private static readonly Course course = new Course() { Id = 1, Name = "<NAME>", NaturalIdentifier = "KVARC-FER-2016", EctsCredits = 5, StudentsEnrolled = new List<Student>(), LecturersInCharge = new List<Lecturer>(), Components = new List<Component>() }; private static readonly Score score = new Score() { Id = 1, Component = component, Student = student, Value = 10 }; public ComponentTests() { score.Component = component; score.Student = student; course.StudentsEnrolled.Add(student); course.LecturersInCharge.Add(lecturer); course.Components.Add(component); component.Course = course; lecturer.CoursesInChargeOf.Add(course); } [TestMethod] public void MVC_ComponentTests_DisplayCourseComponents() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(1)).Returns(lecturer); corRepMock.Setup(c => c.GetById(1)).Returns(course); IList<Component> components = new List<Component>(); comRepMock.Setup(c => c.GetAll()).Returns(components); var controller = new LecturerController(corRepMock.Object, scrRepMock.Object, usrRepMock.Object, comRepMock.Object); var controllerContext = new Mock<ControllerContext>(); controllerContext.SetupGet(p => p.HttpContext.Session["userId"]).Returns(1); controllerContext.SetupGet(p => p.HttpContext.Session["email"]).Returns("<EMAIL>"); controller.ControllerContext = controllerContext.Object; var result = controller.Component(1) as ViewResult; var viewModel = (IList<ComponentViewModel>)result.ViewData.Model; Assert.AreEqual(1, viewModel.Count); } [TestMethod] public void MVC_ComponentTests_DisplayComponentStatistics() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); Course course = new Course() { Id = 1, Name = "<NAME>", NaturalIdentifier = "KVARC-FER-2016", EctsCredits = 5, StudentsEnrolled = new List<Student>(), LecturersInCharge = new List<Lecturer>(), Components = new List<Component>() }; usrRepMock.Setup(c => c.GetById(1)).Returns(lecturer); corRepMock.Setup(c => c.GetById(1)).Returns(course); IList<Component> components = new List<Component>(); comRepMock.Setup(c => c.GetAll()).Returns(components); IList<Score> scores = new List<Score>(); scrRepMock.Setup(c => c.GetAll()).Returns(scores); var controller = new LecturerController(corRepMock.Object, scrRepMock.Object, usrRepMock.Object, comRepMock.Object); var controllerContext = new Mock<ControllerContext>(); controllerContext.SetupGet(p => p.HttpContext.Session["userId"]).Returns(1); controllerContext.SetupGet(p => p.HttpContext.Session["email"]).Returns("<EMAIL>"); controller.ControllerContext = controllerContext.Object; var result = controller.ComponentStatistics(1) as ViewResult; var viewModel = (IList<ComponentStatisticsViewModel>)result.ViewData.Model; Assert.AreEqual(0, viewModel.Count); } [TestMethod] public void MVC_ComponentTests_CreateComponent() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(1)).Returns(lecturer); corRepMock.Setup(c => c.GetById(1)).Returns(course); var controller = new LecturerController(corRepMock.Object, scrRepMock.Object, usrRepMock.Object, comRepMock.Object); var controllerContext = new Mock<ControllerContext>(); controllerContext.SetupGet(p => p.HttpContext.Session["userId"]).Returns(1); controllerContext.SetupGet(p => p.HttpContext.Session["email"]).Returns("<EMAIL>"); controller.ControllerContext = controllerContext.Object; var result = controller.CreateComponent(1) as ViewResult; var viewModel = (ComponentViewModel)result.ViewData.Model; Assert.AreEqual(1, viewModel.CourseId); } [TestMethod] public void MVC_ComponentTests_DeleteComponent() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(1)).Returns(lecturer); corRepMock.Setup(c => c.GetById(1)).Returns(course); comRepMock.Setup(c => c.GetById(1)).Returns(component); var controller = new LecturerController(corRepMock.Object, scrRepMock.Object, usrRepMock.Object, comRepMock.Object); var controllerContext = new Mock<ControllerContext>(); controllerContext.SetupGet(p => p.HttpContext.Session["userId"]).Returns(1); controllerContext.SetupGet(p => p.HttpContext.Session["email"]).Returns("<EMAIL>"); controller.ControllerContext = controllerContext.Object; var result = controller.DeleteComponent(1, false) as ViewResult; var viewModel = (ComponentViewModel)result.ViewData.Model; Assert.AreEqual(1, viewModel.Id); } [TestMethod] public void MVC_ComponentTests_EditComponent() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); Mock<ICourseRepository> corRepMock = new Mock<ICourseRepository>(); Mock<IScoreRepository> scrRepMock = new Mock<IScoreRepository>(); Mock<IComponentRepository> comRepMock = new Mock<IComponentRepository>(); usrRepMock.Setup(c => c.GetById(1)).Returns(lecturer); corRepMock.Setup(c => c.GetById(1)).Returns(course); comRepMock.Setup(c => c.GetById(1)).Returns(component); var controller = new LecturerController(corRepMock.Object, scrRepMock.Object, usrRepMock.Object, comRepMock.Object); var controllerContext = new Mock<ControllerContext>(); controllerContext.SetupGet(p => p.HttpContext.Session["userId"]).Returns(1); controllerContext.SetupGet(p => p.HttpContext.Session["email"]).Returns("<EMAIL>"); controller.ControllerContext = controllerContext.Object; var result = controller.EditComponent(1) as ViewResult; var viewModel = (ComponentViewModel)result.ViewData.Model; Assert.AreEqual(1, viewModel.Id); } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using StudIS.Models.RepositoryInterfaces; using Moq; using StudIS.Models.Users; namespace StudIS.Services.Tests { [TestClass] public class LoginServiceTest { [TestMethod] public void LoginUserTest_Correct() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); usrRepMock.Setup(c => c.GetByEmail(It.IsAny<string>())).Returns(new Student() { PasswordHash = "xxx" }); var service = new LoginService(usrRepMock.Object); var result = service.LoginUser("testUser", "xxx"); Assert.IsNotNull(result); } [TestMethod] public void LoginUserTest_InCorrect() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); usrRepMock.Setup(c => c.GetByEmail(It.IsAny<string>())).Returns(new Student() { PasswordHash = "xxx" }); var service = new LoginService(usrRepMock.Object); var result = service.LoginUser("testUser", "yyy"); Assert.IsNull(result); } [TestMethod] public void LoginUserTest_NonExistantUser() { Mock<IUserRepository> usrRepMock = new Mock<IUserRepository>(); usrRepMock.Setup(c => c.GetByEmail(It.IsAny<string>())).Returns<User>(null); var service = new LoginService(usrRepMock.Object); var result = service.LoginUser("testUser", "yyy"); Assert.IsNull(result); } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using StudIS.Models.Users; using StudIS.DAL.Repositories; using StudIS.DAL; using Moq; using StudIS.Models.RepositoryInterfaces; using StudIS.DAL.Tests; namespace StudIS.Services.Tests { [TestClass] public class UserServicesTests { INHibernateService _nhs; public UserServicesTests() { _nhs = new NHibernateService2(); } [TestMethod] public void IsUserAdministrator_True() { Administrator admin = new Administrator(); Assert.IsTrue(UserServices.IsUserAdministrator(admin)); } [TestMethod] public void IsUserAdministrator_False() { Student student = new Student(); Assert.IsFalse(UserServices.IsUserAdministrator(student)); } [TestMethod] public void IsUserStudent_True() { Student student = new Student(); Assert.IsTrue(UserServices.IsUserStudent(student)); } [TestMethod] public void IsUserStudent_False() { Administrator admin = new Administrator(); Assert.IsFalse(UserServices.IsUserStudent(admin)); } [TestMethod] public void IsUserLecturer_True() { Lecturer lecturer = new Lecturer(); Assert.IsTrue(UserServices.IsUserLecturer(lecturer)); } [TestMethod] public void IsUserLecturer_False() { Administrator admin = new Administrator(); Assert.IsFalse(UserServices.IsUserLecturer(admin)); } [TestMethod] public void CreateUser_ReturnsSavedUser() { var student = new Student() { Name = "Zlatko", Surname = "Hrastić", Email = "<EMAIL>", NationalIdentificationNumber = "343999999", StudentIdentificationNumber = "0036476522", CoursesEnrolledIn = null, PasswordHash = "xxx" }; Mock<IUserRepository> usrRep = new Mock<IUserRepository>(); usrRep.Setup(r => r.Create(It.IsAny<User>())).Returns(student); var userServices = new UserServices(usrRep.Object); var saved = userServices.CreateUser(student); Assert.IsNotNull(saved); Assert.IsNotNull(saved.Id); } } } <file_sep>using StudIS.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace StudIS.Web.Mvc.Models { public class StudentCourseViewModel { public int Id { get; set; } public string NaturalIdentifier { get; set; } public string Name { get; set; } public int EctsCredits { get; set; } public StudentCourseViewModel() { } public StudentCourseViewModel(Course course) { Id = course.Id; NaturalIdentifier = course.NaturalIdentifier; Name = course.Name; EctsCredits = course.EctsCredits; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Models { public class Course { public virtual int Id { get; set; } public virtual string NaturalIdentifier { get; set; } public virtual string Name { get; set; } public virtual int EctsCredits { get; set; } public virtual IList<Users.Lecturer> LecturersInCharge { get; set; } public virtual IList<Users.Student> StudentsEnrolled { get; set; } public virtual IList<Component> Components { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using StudIS.Models; using StudIS.Models.Users; using StudIS.Desktop.Controllers; namespace StudIS.Desktop { public partial class CourseForm : Form { private readonly CourseFormController _courseFormController; private Course _course; private readonly IList<Lecturer> _lecturers; private readonly IList<Student> _students; public CourseForm( CourseFormController courseFormController, Course course, IList<Lecturer> lecturers, IList<Student> students) { _courseFormController = courseFormController; _course = course; _lecturers = lecturers; _students = students; InitializeComponent(); this.Name = _course.Name + "("+ _course.NaturalIdentifier + ")"; this.nameTextBox.Text = _course.Name; this.naturalIdentifierTextBox.Text = _course.NaturalIdentifier; this.ectsCreditsNumericUpDown.Value = _course.EctsCredits; ((ListBox)lecturersCheckedListBox).DataSource = _lecturers; ((ListBox)lecturersCheckedListBox).DisplayMember = "FullName"; var checkedLecturersIds = course.LecturersInCharge .Select(x => x.Id).ToList(); for (int i = 0; i < lecturersCheckedListBox.Items.Count; ++i) { var lecturer = (User)lecturersCheckedListBox.Items[i]; if (checkedLecturersIds.Contains(lecturer.Id)) { lecturersCheckedListBox.SetItemChecked(i, true); } } ((ListBox)studentsCheckedListBox).DataSource = _students; ((ListBox)studentsCheckedListBox).DisplayMember = "FullName"; var checkedStudentsIds = course.StudentsEnrolled .Select(x => x.Id).ToList(); for (int i = 0; i < studentsCheckedListBox.Items.Count; ++i) { var lecturer = (User)studentsCheckedListBox.Items[i]; if (checkedStudentsIds.Contains(lecturer.Id)) { studentsCheckedListBox.SetItemChecked(i, true); } } } private void saveButton_Click(object sender, EventArgs e) { _course.Name = this.nameTextBox.Text; _course.NaturalIdentifier = this.naturalIdentifierTextBox.Text; _course.EctsCredits = (int)this.ectsCreditsNumericUpDown.Value; _course.LecturersInCharge = new List<Lecturer>(); if (_course.Name.Length == 0 || _course.NaturalIdentifier.Length == 0) { MessageBox.Show("Nisu popunjena sva obavezna polja", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } var checkedLecturersIndices = this.lecturersCheckedListBox.CheckedIndices; var checkedLecturers = new List<Lecturer>(); foreach (int lecturerIndex in checkedLecturersIndices) { var lecturerId = ((Lecturer)this.lecturersCheckedListBox.Items[lecturerIndex]).Id; checkedLecturers.Add(_lecturers.First(x => x.Id == lecturerId)); } var checkedStudentsIndices = this.studentsCheckedListBox.CheckedIndices; var checkedStudents = new List<Student>(); foreach (int studentIndex in checkedStudentsIndices) { var studentId = ((Student)this.studentsCheckedListBox.Items[studentIndex]).Id; checkedStudents.Add(_students.First(x => x.Id == studentId)); } _course.LecturersInCharge = checkedLecturers; _course.StudentsEnrolled = checkedStudents; var success = _courseFormController.SaveCourse(_course); if (success) { this.Close(); } else { MessageBox.Show("Pohrana nije uspjela"); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Models { public class Score { public virtual int Id { get; set; } public virtual float Value { get; set; } public virtual Component Component { get; set; } public virtual Users.Student Student { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using StudIS.Models.Users; namespace StudIS.Models.RepositoryInterfaces { public interface IUserRepository { IList<User> GetAll(); IList<Administrator> GetAllAdministrators(); IList<Lecturer> GetAllLecturers(); IList<Student> GetAllStudents(); User GetById(int id); User GetByEmail(string email); User GetByNationalIdentificationNumbe(string nationalIdentificationNumbe); IList<Student> GetByCourse(Course course); bool DeleteById(int id); bool DeleteByNationalIdentificationNumber(string nationalIdentificationNumbe); User Update(User user); User Create(User user); } } <file_sep>using StudIS.Models; using StudIS.Models.RepositoryInterfaces; using StudIS.Models.Users; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Services { public class ScoreServices { private IScoreRepository _scoreRepository; private ICourseRepository _courseRepository; private IUserRepository _userRepository; public ScoreServices(IScoreRepository scoreRepository, ICourseRepository courseRepository, IUserRepository userRepository) { _scoreRepository = scoreRepository; _courseRepository = courseRepository; _userRepository = userRepository; } public IList<Score> GetByComponent(int componentId) { var scores = _scoreRepository.GetAll(); IList<Score> rightScores = new List<Score>(); foreach (var s in scores) { if (s.Component.Id == componentId) rightScores.Add(s); } return rightScores; } public IList<Score> GetScorebyStudentAndCourse(int studentId, int courseId) { var student = _userRepository.GetById(studentId); if (student == null || !UserServices.IsUserStudent(student)) return new List<Score>(); var course = _courseRepository.GetById(courseId); var componentList = course.Components; if (componentList == null) return new List<Score>(); var scoreList = new List<Score>(); foreach (var component in componentList) { var score = _scoreRepository.GetByStudentIdAndComponentId((Student)student, component); if (score == null) { var defaultScore = new Score() { Student = (Student)student, Component = component, Value = 0, }; score = _scoreRepository.CreateOrUpdate(defaultScore); } scoreList.Add(score); } return scoreList; } public bool SaveScore(Score score) { var newScore = _scoreRepository.CreateOrUpdate(score); if (newScore != null) return true; else return false; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace StudIS.Services { public static class EncryptionService { public static String EncryptSHA1(String password) { using (SHA1Managed sha1 = new SHA1Managed()) { var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(password)); var sb = new StringBuilder(hash.Length * 2); foreach (byte b in hash) { // can be "x2" if you want lowercase sb.Append(b.ToString("X2")); } return sb.ToString(); } } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using StudIS.Models.RepositoryInterfaces; using StudIS.DAL; using StudIS.Models; using StudIS.Models.Users; using StudIS.Services; using StudIS.DAL.Repositories; using StudIS.Desktop.Controllers; using System.Collections.Generic; using StudIS.DAL.Tests; namespace StudIS.Desktop.Tests { [TestClass] public class CourseFormTests { private readonly IUserRepository _userRepository; private readonly ICourseRepository _courseRepository; private readonly IComponentRepository _componentRepository; private readonly IScoreRepository _scoreRepository; private readonly UserServices _userServices; private readonly CourseServices _courseServices; private readonly ScoreServices _scoreServices; private static readonly Student student = new Student() { Email = "<EMAIL>", PasswordHash = "<PASSWORD>", Name = "Sample", Surname = "Sample", NationalIdentificationNumber = "124", StudentIdentificationNumber = "343" }; private static readonly Lecturer lecturer = new Lecturer() { Email = "<EMAIL>", PasswordHash = "<PASSWORD>", Name = "Sample2", Surname = "Sample2", NationalIdentificationNumber = "124" }; private static readonly Course course = new Course() { Name = "Objektno oblikovanje", NaturalIdentifier = "OO-FER-2016", EctsCredits = 5, StudentsEnrolled = new List<Student>() { student }, LecturersInCharge = new List<Lecturer>() { lecturer } }; public CourseFormTests() { var nhs = new NHibernateService2(); _userRepository = new UserRepository(nhs); _courseRepository = new CourseRepository(nhs); _componentRepository = new ComponentRepository(nhs); _scoreRepository = new ScoreRepository(nhs); _userServices = new UserServices(_userRepository); _courseServices = new CourseServices(_courseRepository, _userRepository, _componentRepository); _scoreServices = new ScoreServices(_scoreRepository, _courseRepository, _userRepository); } [TestMethod] public void CourseForm_CreateCourse() { var controller = new UserFormController(_userServices, _courseServices); var success = controller.SaveUser(student); Assert.IsTrue(success); } [TestMethod] public void CourseForm_TryDeleteNonExistingCourse() { var controller = new CourseFormController(_courseServices, _userServices); var success = controller.DeleteCourse(course.Id); Assert.IsFalse(success); } [TestMethod] public void CourseForm_TryCreateAndDeleteCourseWithLecturersAndStudents() { this.CourseForm_CreateCourse(); var controller = new CourseFormController(_courseServices, _userServices); var deletionSuccess = controller.DeleteCourse(course.Id); Assert.IsFalse(deletionSuccess); } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using StudIS.Models; using StudIS.DAL.Repositories; using StudIS.Models.RepositoryInterfaces; namespace StudIS.DAL.Tests { [TestClass] public class ComponentRepositoryTests { INHibernateService _nhs; ICourseRepository _corRep; IComponentRepository _comRep; public ComponentRepositoryTests() { _nhs = new NHibernateService2(); _corRep = new CourseRepository(_nhs); _comRep = new ComponentRepository(_nhs); } [TestMethod] public void ComponentRepository_Create_Success() { Course course = new Course() { Name = "<NAME>", NaturalIdentifier = "KVARC-FER-2016", EctsCredits = 5, Components = null, LecturersInCharge = null, StudentsEnrolled = null }; var savedCourse = _corRep.Create(course); Component component = new Component() { Course = savedCourse, Name = "Seminari", MaximumPoints = 40, MinimumPointsToPass = 20 }; var created = _comRep.Create(component); Assert.IsNotNull(created); Assert.AreEqual(created.Name, "Seminari"); } [TestMethod] public void ComponentRepository_Create_Fail() { Course course = new Course() { Name = "<NAME>", NaturalIdentifier = "KVARC-FER-2016", EctsCredits = 5, Components = null, LecturersInCharge = null, StudentsEnrolled = null }; Component component = new Component() { Course = course, Name = "Seminari", MaximumPoints = 40, MinimumPointsToPass = 20 }; try { var created = _comRep.Create(component); Assert.Fail("No exception thrown"); } catch (Exception ex) { Assert.IsTrue(ex is NHibernate.TransientObjectException); } } [TestMethod] public void ComponentRepository_Update_Success() { Course course = new Course() { Name = "<NAME>", NaturalIdentifier = "KVARC-FER-2016", EctsCredits = 5, Components = null, LecturersInCharge = null, StudentsEnrolled = null }; var savedCourse = _corRep.Create(course); Component component = new Component() { Course = savedCourse, Name = "Seminari", MaximumPoints = 40, MinimumPointsToPass = 20 }; var created = _comRep.Create(component); created.Name = "NewName"; var updated = _comRep.Update(created); Assert.IsNotNull(updated); Assert.AreEqual(updated.Name, "NewName"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using StudIS.Models.RepositoryInterfaces; using StudIS.Models.Users; using StudIS.Services; using StudIS.DAL; using StudIS.DAL.Repositories; namespace StudIS.Desktop.Controllers { public class CourseFormController { private readonly CourseServices _courseServices; private readonly UserServices _userServices; public CourseFormController(CourseServices courseServices, UserServices userServices) { _courseServices = courseServices; _userServices = userServices; } private void getLecturersAndStudents(out IList<Lecturer> lecturers, out IList<Student> students) { lecturers = _userServices.GetAllLecturers(); students = _userServices.GetAllStudents(); } public void OpenFormNewCourse() { var course = new Course(); course.LecturersInCharge = new List<Lecturer>(); course.StudentsEnrolled = new List<Student>(); course.Components = new List<Component>(); IList<Lecturer> lecturers; IList<Student> students; getLecturersAndStudents(out lecturers, out students); var courseForm = new CourseForm(this, course, lecturers, students); courseForm.Show(); } public void OpenFormEditCourse(int id) { var course = _courseServices.GetCourseById(id); IList<Lecturer> lecturers; IList<Student> students; getLecturersAndStudents(out lecturers, out students); var courseForm = new CourseForm(this, course, lecturers, students); courseForm.Show(); } public bool UpdateCourse(Course course) { _courseServices.UpdateCourse(course.Id, course.Name, course.Name, course.EctsCredits); return true; } public bool SaveCourse(Course course) { try { if (_courseServices.GetCourseById(course.Id) == null) { var courseId = _courseServices.CreateCourse(course.Name, course.NaturalIdentifier, course.EctsCredits).Id; _courseServices.UpdateLecturers(courseId, course.LecturersInCharge); _courseServices.UpdateStudents(courseId, course.StudentsEnrolled); } else { _courseServices.UpdateCourse(course.Id, course.Name, course.NaturalIdentifier, course.EctsCredits); _courseServices.UpdateLecturers(course.Id, course.LecturersInCharge); _courseServices.UpdateStudents(course.Id, course.StudentsEnrolled); } return true; } catch (Exception ex) { return false; } } public bool DeleteCourse(int id) { var course = _courseServices.GetCourseById(id); if(course == null) { return false; } else { try { return _courseServices.DeleteCourse(id); } catch (Exception ex) { return false; } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StudIS.Models; using FluentNHibernate; using FluentNHibernate.Data; using NHibernate; using StudIS.Models.RepositoryInterfaces; using NHibernate.Criterion; using StudIS.DAL; using StudIS.Models.Users; namespace StudIS.DAL.Repositories { public class UserRepository : IUserRepository { private ISession _session; public UserRepository(INHibernateService nhs) { _session = nhs.OpenSession(); } public IList<User> GetAll() { return _session.QueryOver<User>().List(); } public IList<Administrator> GetAllAdministrators() { return _session.QueryOver<Administrator>().List(); } public IList<Lecturer> GetAllLecturers() { return _session.QueryOver<Lecturer>().List(); } public IList<Student> GetAllStudents() { return _session.QueryOver<Student>().List(); } public User Create(User user) { using (var transaction = _session.BeginTransaction()) { _session.Save(user); transaction.Commit(); return user; } } public bool DeleteById(int id) { using (var transaction = _session.BeginTransaction()) { var user = GetById(id); if (user == null) return false; _session.Delete(user); transaction.Commit(); return true; } } public bool DeleteByNationalIdentificationNumber(string nationalIdentificationNumber) { using (var transaction = _session.BeginTransaction()) { var user = GetByNationalIdentificationNumbe(nationalIdentificationNumber); if (user == null) return false; _session.Delete(user); transaction.Commit(); return true; } } public IList<Student> GetByCourse(Course course) { var users =_session.QueryOver<Student>() .Right.JoinQueryOver<Course>(x => x.CoursesEnrolledIn) .Where(c => c.Id==course.Id) .List(); return users; } public User GetByEmail(string email) { return _session.CreateCriteria<User>() .Add(Expression.Like("Email", email)) .UniqueResult<User>(); } public User GetById(int id) { return _session.Get<User>(id); } public User GetByNationalIdentificationNumbe(string nationalIdentificationNumber) { return _session.CreateCriteria<User>() .Add(Expression.Like("NationalIdentificationNumber", nationalIdentificationNumber)) .UniqueResult<User>(); } public User Update(User user) { using (var transaction = _session.BeginTransaction()) { _session.Update(user); transaction.Commit(); return user; } } ~UserRepository() { _session.Close(); _session.Dispose(); _session = null; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using NHibernate; using StudIS.DAL.Mappings; using System.Data.SqlClient; using System.IO; namespace StudIS.DAL { public class NHibernateService : INHibernateService { private static ISessionFactory _sessionFactory; public ISession OpenSession() { try { if (_sessionFactory == null) { _sessionFactory = OpenSessionFactory(); } ISession session = _sessionFactory.OpenSession(); return session; } catch (Exception e) { throw e.InnerException ?? e; } } private ISessionFactory OpenSessionFactory() { var rawStr = "Data Source = (LocalDB)\\MSSQLLocalDB; Integrated Security = True"; var path = "C:\\Users\\Public\\databases"; var conBuilder = new SqlConnectionStringBuilder(rawStr); conBuilder.AttachDBFilename = Path.GetFullPath( Path.Combine(path, "StudIS_DB.mdf")); var nhConfig = Fluently.Configure() .Diagnostics(diag => diag.Enable().OutputToConsole()) //.Database(SQLiteConfiguration.Standard // .ConnectionString("Data Source=TestNHibernate_fluent.db;Version=3") // .AdoNetBatchSize(100)) .Database(MsSqlConfiguration.MsSql2012 .ConnectionString(conBuilder.ToString()) .AdoNetBatchSize(100)) .Mappings(mappings => mappings.FluentMappings.Add<AdministratorMap>()) .Mappings(mappings => mappings.FluentMappings.Add<LecturerMap>()) .Mappings(mappings => mappings.FluentMappings.Add<UserMap>()) .Mappings(mappings => mappings.FluentMappings.Add<CourseMap>()) .Mappings(mappings => mappings.FluentMappings.Add<ComponentMap>()) .Mappings(mappings => mappings.FluentMappings.Add<ScoreMap>()) .Mappings(mappings => mappings.FluentMappings.Add<StudentMap>()) //.ExposeConfiguration(cfg => new NHibernate.Tool.hbm2ddl.SchemaExport(cfg).Execute(true, true, false)) .BuildConfiguration(); var sessionFactory = nhConfig.BuildSessionFactory(); return sessionFactory; } /* * //public IDatabase Database { private get; set; } //public NhibernateService(IDatabase database) //{ // Database = database; //} public void CreateDatabaseAndSchema() { _sessionFactory = null; //obriše se eventualni prošli session if (Database == null) { return; } Database.CreateDatabase(Database.DBInfo); CreateSchema(); } private void CreateSchema() { var configuration = Database.GetFluentConfiguration(); configuration.Mappings(m => m.FluentMappings.AddFromAssemblyOf<InspectionMapping>()). ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true)). BuildSessionFactory(); } public ISession CreateSchemaOpenSession(IDatabaseInfo inDB) { _sessionFactory = null; //obriše se eventualni prošli session if (Database == null) { return null; } CreateSchema(); return OpenSession(); } */ } } <file_sep>using System.Collections.Generic; using StudIS.DAL; using StudIS.Models; using StudIS.Models.Users; using StudIS.DAL.Repositories; using StudIS.Services; namespace StudIS.DatabaseSeed { class Program { static void Main(string[] args) { var nhService = new NHibernateService(); var userRepository = new UserRepository(nhService); var courseRepository = new CourseRepository(nhService); var componentRepository = new ComponentRepository(nhService); var scoreRepository = new ScoreRepository(nhService); #region Seeding var lecturer = new Lecturer() { Email = "<EMAIL>", PasswordHash = EncryptionService.EncryptSHA1("<PASSWORD>"), Name = "Tibor", Surname = "Žukina", NationalIdentificationNumber = "12345" }; var administrator = new Administrator() { Email = "<EMAIL>", PasswordHash = EncryptionService.EncryptSHA1("<PASSWORD>"), Name = "Željko", Surname = "Baranek", NationalIdentificationNumber = "123456" }; var student = new Student() { Name = "Zlatko", Surname = "Hrastić", Email = "<EMAIL>", NationalIdentificationNumber = "343999999", StudentIdentificationNumber = "0036476522", CoursesEnrolledIn = new List<Course>(), PasswordHash = EncryptionService.EncryptSHA1("<PASSWORD>") }; Component medjuispit = new Component() { MaximumPoints = 30, MinimumPointsToPass = 0, Name = "Međuispit" }; Component zavrsni = new Component() { MaximumPoints = 40, MinimumPointsToPass = 14, Name = "Završni ispit" }; var componentList = new List<Component>(); componentList.Add(medjuispit); componentList.Add(zavrsni); Course MockCourse = new Course() { Id = 1, Name = "<NAME>", NaturalIdentifier = "ObjOblFER2016OO", EctsCredits = 5, Components = componentList, LecturersInCharge = new List<Lecturer>(), StudentsEnrolled = new List<Student>() }; Course MockCourse2 = new Course() { Id = 2, Name = "Napredni algoritmi i strukture podataka", NaturalIdentifier = "NASP-FER-2016OO", EctsCredits = 5, Components = null, LecturersInCharge = new List<Lecturer>(), StudentsEnrolled = new List<Student>() }; var score = new Score() { Component = medjuispit, Student = student, Value = 20 }; var service = new UserServices(userRepository); service.CreateUser(student); service.CreateUser(lecturer); service.CreateUser(administrator); MockCourse.StudentsEnrolled.Add(student); MockCourse.LecturersInCharge.Add(lecturer); courseRepository.Create(MockCourse); courseRepository.Create(MockCourse2); scoreRepository.CreateOrUpdate(score); #endregion System.Console.WriteLine("Seed successfully completed."); System.Console.Read(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using StudIS.Models.Users; using StudIS.DAL; using StudIS.DAL.Repositories; using StudIS.Services; using StudIS.Desktop.Controllers; namespace StudIS.Desktop { public partial class LoginForm : Form { private readonly LoginFormController _controller; public LoginForm(LoginFormController controller) { _controller = controller; InitializeComponent(); } public bool LoginResult { get; set; } = false; private void submitButton_Click(object sender, EventArgs e) { var email = this.emailTextBox.Text; var password = this.passwordTextBox.Text; if (email.Length == 0 || password.Length == 0) { MessageBox.Show("E-mail adresa i/ili lozinka nisu uneseni", "Unesite podatke za prijavu", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } var loginResult = _controller.Login(email, password); if (loginResult) { this.LoginResult = true; this.Close(); } } private void studIsLabel_Click(object sender, EventArgs e) { } } } <file_sep>using NHibernate; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.DAL { public interface INHibernateService { ISession OpenSession(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace StudIS.Web.Mvc.Models { public class ComponentStatisticsViewModel { public virtual string ComponentName { get; set; } public virtual float Average { get; set; } public virtual float Max { get; set; } public virtual float Percentage { get; set; } public virtual int CourseId { get; set; } public ComponentStatisticsViewModel(string ComponentName, float Average, float Max, int CourseId) { this.ComponentName = ComponentName; this.Average = Average * Max; this.Max = Max; this.Percentage = (float)Average * 100; this.CourseId = CourseId; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudIS.Models.RepositoryInterfaces { public interface IComponentRepository { Component GetById(int id); bool DeleteById(int id); Component Update(Component component); Component Create(Component component); IList<Component> GetAll(); } }
04fa368661e3c2494a1b38fa0ce0bf10b7a4f195
[ "Markdown", "C#" ]
74
C#
zelbar/oo-projekt
b78cf8782323912a4fa8150907d00433267bf638
84fa85dceba7bcb63450fe1f80c87cfbdad581ec
refs/heads/main
<repo_name>ndadashi62/QuizApp<file_sep>/app/src/main/java/com/example/quizapp/MainActivity.kt package com.example.quizapp import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import com.example.quizapp.QuizQuestionsActivity import com.example.quizapp.R import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.activity_quiz_questions.* import kotlinx.android.synthetic.main.activity_quiz_questions.view.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnStart.setOnClickListener { if (editTextName.text.toString().isEmpty()) { Toast.makeText(this@MainActivity, "Please enter your name", Toast.LENGTH_SHORT) .show() } else { val intent = Intent(this@MainActivity, QuizQuestionsActivity::class.java) intent.putExtra(Constants.USER_NAME,editTextName.text.toString()) startActivity(intent) finish() } } } }<file_sep>/app/src/main/java/com/example/quizapp/Question.kt package com.example.quizapp data class Question ( val id:Int, val question:String, val image: Int , val optionOne :String , val optionTwo:String , val optionThree:String , val optionFour :String , val correctAnswer:Int ) <file_sep>/app/src/main/java/com/example/quizapp/Constants.kt package com.example.quizapp object Constants { const val USER_NAME:String="user_name" const val TOTAL_QUESTIONS:String="total_question" const val CORRECT_ANSWERS:String="correct answer" fun getQuestions(): ArrayList<Question> { val questionList = ArrayList<Question>() val que1 = Question( 1, "what country does this flag belong to?", R.drawable.ic_flag_of_iran, optionOne = "Iran", optionTwo = "Canada", optionThree = "England", optionFour = "Brazil", 1 ) questionList.add(que1) val que2 = Question( 2, "what country does this flag belong to?", R.drawable.ic_flag_of_france, optionOne = "Argantina", optionTwo = "France", optionThree = "Germany", optionFour = "Brazil", correctAnswer = 2 ) questionList.add(que2) val que3 = Question( 3, "what country does this flag belong to?", R.drawable.ic_flag_of_canada, optionOne = "China", optionTwo = "Irland", optionThree = "Swiss", optionFour = "Canada", 4 ) questionList.add(que3) val que4 = Question( 5, "what country does this flag belong to?", R.drawable.ic_flag_of_brazil, optionOne = "Brazil", optionTwo = "canada", optionThree = "Oman", optionFour = "Germany", 1 ) questionList.add(que4) val que6 = Question( 6, "what country does this flag belong to?", R.drawable.ic_flag_of_england, optionOne = "Ghatar", optionTwo = "Pakistan", optionThree = "England", optionFour = "Italia", 3 ) questionList.add(que6) val que7 = Question( 7, "what country does this flag belong to?", R.drawable.ic_flag_of_usa, optionOne = "Iran", optionTwo = "Eygept", optionThree = "england", optionFour = "USA", 4 ) questionList.add(que7) return questionList } }
0c135307982d4a5d75ef6577272a78f6a948f2b0
[ "Kotlin" ]
3
Kotlin
ndadashi62/QuizApp
741b83564a5c33431ba440c217a9e816f6931977
b1862a7923ae158d9af88ae5dc3a958b74351f9f
refs/heads/master
<file_sep>from pig_util import outputSchema # # This is where we write python UDFs (User-Defined Functions) that we can call from pig. # Pig needs to know the schema of the data coming out of the function, # which we specify using the @outputSchema decorator. # @outputSchema('example_udf:int') def example_udf(input_str): """ A simple example function that just returns the length of the string passed in. """ return len(input_str) if input_str else None @outputSchema('extract_user:chararray') def extract_user(event_map): if 'actor' in event_map: return event_map['actor'] else: return None @outputSchema('extract_repo_identifier:chararray') def extract_repo_identifier(event_map): if 'repository' in event_map: if 'organization' in event_map['repository']: owner = event_map['repository']['organization'] else: owner = event_map['repository']['owner'] repo = event_map['repository']['name'] return "%s/%s" % (owner, repo) else: return None
619664c1eeb1f4416d37af24928da00271d8860a
[ "Python" ]
1
Python
pombredanne/github-sna
a9be83de43be677b3ec6fd1ba701c35c025c5888
12aab3aa587449c903c08b1a69ddf24f7d5605d1
refs/heads/master
<file_sep>package anz.services; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; /** * Concrete implementation of {@link AuthenticationProvider} that extracts * the {@link UserDetails} from the Spring Security Context */ @Service public class AuthenticationProviderImpl implements AuthenticationProvider { @Override public UserDetails getAuthenticatedUser() { final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { return (UserDetails) principal; } if (principal instanceof String) { return User.withDefaultPasswordEncoder() .username((String) principal) .password("foo") .roles("USER") .build(); } throw new IllegalStateException("Unknown Principal type"); } } <file_sep>package anz.application; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.OAuth2Request; import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.RequestPostProcessor; /** * Test that we have wired in OAuth2 correctly * This test does not use the "test" profile as it uses Spring Security */ @ExtendWith(SpringExtension.class) @SpringBootTest @AutoConfigureMockMvc class OAuthIntegrationTest { @Autowired private AuthorizationServerTokenServices tokenServices; @Autowired private MockMvc mockMvc; @Test void testOAuthSecurity() throws Exception { // A request with no token should be unauthorised mockMvc.perform(post("/account/list") .contentType(MediaType.APPLICATION_JSON) .content("{}")) .andExpect(status().isUnauthorized()); // A request with a valid token should be authorised mockMvc.perform(post("/account/list") .with(addOAuthToken("alice")) .contentType(MediaType.APPLICATION_JSON) .content("{}")) .andExpect(status().isOk()); } /** * Builds a {@link RequestPostProcessor} that adds an OAuth2 token to the request for the provided username */ private RequestPostProcessor addOAuthToken(final String username) { return mockRequest -> { // Build a token and set it as the authorisation header final OAuth2Request oauth2Request = new OAuth2Request(null, "anz-example", null, true, null, null, null, null, null); final Authentication authentication = new TestingAuthenticationToken(username, null, "USER"); final OAuth2Authentication oauth2auth = new OAuth2Authentication(oauth2Request, authentication); final OAuth2AccessToken token = tokenServices.createAccessToken(oauth2auth); // Set Authorization header to use Bearer mockRequest.addHeader("Authorization", "Bearer " + token.getValue()); return mockRequest; }; } } <file_sep>package anz.repository; import java.util.List; import java.util.UUID; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import anz.model.Account; /** * JPA repository for {@link Account} objects */ public interface AccountRepository extends JpaRepository<Account, UUID> { List<Account> findByUsername(final String username, final Pageable pageable); } <file_sep>package anz.application; import java.util.List; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; import anz.model.Account; import anz.model.Transaction; import anz.services.DataAccessLayer; /** * Rest API resource for {@link Transaction} objects. */ @RestController public class TransactionResource { private final DataAccessLayer dataAccessLayer; @Autowired public TransactionResource(final DataAccessLayer dataAccessLayer) { this.dataAccessLayer = dataAccessLayer; } /** * Fetches all transactions in the provided account for the logged in user */ @PostMapping("/transaction/list") public List<Transaction> transactionList(@RequestBody final TransactionRequest request, final Pageable pageable) { final Account account = dataAccessLayer.getAccount(request.getAccountId()); if (account == null) { throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Transaction not found"); } return dataAccessLayer.getTransactions(account.getId(), pageable); } /** * Simple, extendable bean that holds search parameters for listing transactions */ public static class TransactionRequest { private UUID accountId; UUID getAccountId() { return accountId; } public void setAccountId(final UUID accountId) { this.accountId = accountId; } } } <file_sep>package anz.model; import java.time.Instant; import java.util.Currency; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * Entity representing an account * * Plenty of assumptions here for simplicity: * - Instants for dates? Assuming a server stores UTC timestamps - the UI can translate * - Balance as a double? Would be some sort of fixed point decimal to correctly store fractional cents I imagine */ @Entity public final class Account { @Id @GeneratedValue @Column private UUID id; @Column private int accountNumber; @Column private String accountName; @Column private String username; @Column private AccountType accountType; @Column private Instant balanceDate; @Column private Currency currency; @Column private double balance; public enum AccountType { SAVINGS, CURRENT } public UUID getId() { return id; } public Account setId(final UUID id) { this.id = id; return this; } public int getAccountNumber() { return accountNumber; } public Account setAccountNumber(final int accountNumber) { this.accountNumber = accountNumber; return this; } public String getAccountName() { return accountName; } public Account setAccountName(final String accountName) { this.accountName = accountName; return this; } public String getUsername() { return username; } public Account setUsername(final String username) { this.username = username; return this; } public AccountType getAccountType() { return accountType; } public Account setAccountType(final AccountType accountType) { this.accountType = accountType; return this; } public Instant getBalanceDate() { return balanceDate; } public Account setBalanceDate(final Instant balanceDate) { this.balanceDate = balanceDate; return this; } public Currency getCurrency() { return currency; } public Account setCurrency(final Currency currency) { this.currency = currency; return this; } public double getBalance() { return balance; } public Account setBalance(final double balance) { this.balance = balance; return this; } } <file_sep>package anz.model; import java.time.Instant; import java.util.Currency; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; /** * Entity representing a transaction in an account. Some similar assumptions to {@link Account} * for simplicity. */ @Entity public class Transaction { @Id @GeneratedValue @Column private UUID id; @ManyToOne @JoinColumn(name = "account_Id") private Account account; @Column private Instant valueDate; @Column private Currency currency; @Column private double amount; @Column private TransactionType transactionType; @Column private String transactionNarrative; public enum TransactionType { DEBIT, CREDIT } public UUID getId() { return id; } public Transaction setId(final UUID id) { this.id = id; return this; } public Account getAccount() { return account; } public Transaction setAccount(final Account account) { this.account = account; return this; } public Instant getValueDate() { return valueDate; } public Transaction setValueDate(final Instant valueDate) { this.valueDate = valueDate; return this; } public Currency getCurrency() { return currency; } public Transaction setCurrency(final Currency currency) { this.currency = currency; return this; } public double getAmount() { return amount; } public Transaction setAmount(final double amount) { this.amount = amount; return this; } public TransactionType getTransactionType() { return transactionType; } public Transaction setTransactionType(final TransactionType transactionType) { this.transactionType = transactionType; return this; } public String getTransactionNarrative() { return transactionNarrative; } public Transaction setTransactionNarrative(final String transactionNarrative) { this.transactionNarrative = transactionNarrative; return this; } } <file_sep>package anz.services; import org.springframework.security.core.userdetails.UserDetails; /** * Abstraction to wrap the authenticated user from Spring Security */ public interface AuthenticationProvider { UserDetails getAuthenticatedUser(); } <file_sep>package anz.services; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.closeTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static anz.ModelDataTestUtil.createSavingsAccount; import static anz.ModelDataTestUtil.createTransaction; import java.util.List; import org.assertj.core.util.Lists; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.test.context.junit.jupiter.SpringExtension; import anz.model.Account; import anz.model.Transaction; import anz.repository.AccountRepository; import anz.repository.TransactionRepository; /** * Simple tests to make sure the JPA repositories are working as expected */ @ExtendWith(SpringExtension.class) @DataJpaTest class DataAccessServiceIntegrationTest { @Autowired private AccountRepository accountRepository; @Autowired private TransactionRepository transactionRepository; private DataAccessLayer dataAccess; @BeforeEach void init() { dataAccess = new DataAccessService(accountRepository, transactionRepository); } @Test void testSaveAndLoadAccount() { final Account account = accountRepository.save(createSavingsAccount(12345)); final Account loadedAccount = dataAccess.getAccount(account.getId()); assertThat(loadedAccount.getId(), is(account.getId())); assertThat(loadedAccount.getAccountName(), is(account.getAccountName())); } @Test void testLoadTransactionsViaAccount() { // Load transactions final Account account = accountRepository.save(createSavingsAccount(1533)); transactionRepository.saveAll(Lists.list( createTransaction(account, 23.6), createTransaction(account, 28.1), createTransaction(account, -13.3))); // Ensure they can be read List<Transaction> loadedTransactions = dataAccess.getTransactions(account.getId(), Pageable.unpaged()); assertThat(loadedTransactions, hasSize(3)); assertThat(loadedTransactions.stream() .mapToDouble(t -> t.getTransactionType() == Transaction.TransactionType.CREDIT ? t.getAmount() : -t.getAmount()) .sum(), closeTo(38.4, 1E-6)); // Ensure they can be paged loadedTransactions = dataAccess.getTransactions(account.getId(), PageRequest.of(0, 1)); assertThat(loadedTransactions, hasSize(1)); } } <file_sep>package anz.application; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.assertj.core.util.Lists; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import anz.ModelDataTestUtil; import anz.model.Account; import anz.services.AuthenticationProvider; import anz.services.DataAccessLayer; /** * Integration test for {@link AccountResource}, testing end-to-end HTTP requests and responses. * Given the resource class itself is so simple we've opted just for integration tests to make sure * the app is all wired up and behaving correctly: usually there would be accompanying unit tests as well. */ @ExtendWith(SpringExtension.class) @SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") class AccountResourceIntegrationTest { private static final String USERNAME = "user"; private static final int ACCOUNT_NUMBER = 12345; @Autowired private MockMvc mockMvc; @MockBean private AuthenticationProvider authenticationProvider; @MockBean private DataAccessLayer dataAccessLayer; @BeforeEach void init() { // Always ensure a logged in user final UserDetails userDetails = mock(UserDetails.class); when(userDetails.getUsername()).thenReturn(USERNAME); when(authenticationProvider.getAuthenticatedUser()).thenReturn(userDetails); } @Test void testListAccountsReturnsCorrectJson() throws Exception { final Account account1 = ModelDataTestUtil.createSavingsAccount(ACCOUNT_NUMBER); final Account account2 = ModelDataTestUtil.createSavingsAccount(ACCOUNT_NUMBER+1); final Account account3 = ModelDataTestUtil.createSavingsAccount(ACCOUNT_NUMBER+2); when(dataAccessLayer.getAccounts(eq(USERNAME), any())).thenReturn(Lists.list(account1, account2, account3)); // Ensure we get the 3 accounts correctly returned mockMvc.perform(post("/account/list") .contentType(MediaType.APPLICATION_JSON) .content("{}")) .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(3))) .andExpect(jsonPath("$[0].accountNumber", equalTo(account1.getAccountNumber()))) .andExpect(jsonPath("$[1].accountNumber", equalTo(account2.getAccountNumber()))) .andExpect(jsonPath("$[2].accountNumber", equalTo(account3.getAccountNumber()))); } } <file_sep>package anz.services; import java.util.List; import java.util.UUID; import org.springframework.data.domain.Pageable; import anz.model.Account; import anz.model.Transaction; /** * Abstraction interface representing service that allows access to data in persistence. */ public interface DataAccessLayer { /** * Gets the account with the provided account number for the given user */ Account getAccount(final UUID accountId); /** * Fetches all accounts for the given user. */ List<Account> getAccounts(final String username, final Pageable pageable); /** * Fetches all transactions for the provided account and user */ List<Transaction> getTransactions(final UUID accountId, final Pageable pageable); }
1f52fedbdc4cead456dadbd9ef0919e480f9609a
[ "Java" ]
10
Java
leigh-whiting/anz-institutional
47adba48b40016965e09158cf64e6109c54c47dc
2bce0e17f3f1a3e1c979c6f67d3b3186a9cfe2c9
refs/heads/master
<repo_name>Jzhengel/minimumEditDistance<file_sep>/MED.py import numpy as np import time start =time.clock() def mini(delete,insert,keep): if delete<insert and delete <keep: return delete,"delete" elif insert<delete and insert<keep: return insert,"insert" else: return keep,"keep" def mini2(delete,insert,replace): if delete<insert and delete <replace: return delete,"delete" elif insert<delete and insert<replace: return insert,"insert" else: return replace,"replace" def miniEditDistance(str1,str2): len1=len(str1); len2=len(str2); List=[]; matrix=np.zeros((len1+1,len2+1)) for row in range(1,len1+1): matrix[row][0]=row; for col in range(1,len2+1): matrix[0][col]=col; for row in range(1,len1+1): for col in range(1,len2+1): if str1[row-1]==str2[col-1]: matrix[row,col],temp=mini(matrix[row-1,col]+1,matrix[row,col-1]+1,matrix[row-1,col-1]) List.append(temp); else: matrix[row,col],temp=mini2(matrix[row-1,col]+1,matrix[row,col-1]+1,matrix[row-1,col-1]+1) List.append(temp); row =len1; col =len2; while row !=0 and col !=0: if List[(row-1)*len2+col-1]=="delete": print('%-10s'%str1[0:row],'%-10s'%str2[0:col],"delete ",str1[row]); row=row-1; col=col; continue if List[(row-1)*len2+col-1]=="insert": print('%-10s'%str1[0:row],'%-10s'%str2[0:col],"insert a ",str2[col]); row=row; col=col-1; continue if List[(row-1)*len2+col-1]=="keep": print('%-10s'%str1[0:row],'%-10s'%str2[0:col],"keep the same"); row=row-1; col=col-1; continue if List[(row-1)*len2+col-1]=="replace": print('%-10s'%str1[0:row],'%-10s'%str2[0:col],"replace ",str1[row-1],"with ",str2[col-1]); row=row-1; col=col-1; continue print(matrix[-1][-1]) miniEditDistance('expection','intention') end = time.clock() print('Running time: %s Seconds'%(end-start)) <file_sep>/README.md ## 最小编辑距离实验报告 **人工智能82班 李家正 2184111493** ### 问题的引入 编辑距离(Edit Distance),又称Levenshtein距离,是指两个字串之间,由一个转成另一个所需的最少编辑操作次数。许可的编辑操作包括将一个字符替换成另一个字符,插入一个字符,删除一个字符。一般来说,编辑距离越小,两个串的相似度越大。我们需要使用DP(动态规划)或者迭代来进行具体的实现。 ### 数学形式化 对于两个字符串,一共存在着四种操作: - 删除一个字符 a) Insert a character $matrix[i][j]=matrix[i-1][j]+1$ - 插入一个字符 b) Delete a character $matrix[i][j]=matrix[i][j-1]+1$ - 修改一个字符 c) Replace a character $matrix[i][j]=matrix[i-1][j]+flag$ - 保留一个字符 d) Keep a character $matrix[i][j]=matrix[i-1][j]$ 根据这四种操作的性质并且结合操作实际,我们总是选择最小的距离,我们有把字符串str1转换到字符串str2,我们会得到分段函数: $$ matrix[i,j]= \begin{cases} 0, & \text{if $i$=0,$j$=0}\\ j,& \text{if $i$=0,$j$>0 }\\ i,& \text{if $i$>0,$j$=0}\\ min(matrix[i-1][j]+1,matrix[i][j-1]+1,matrix[i-1][j-1]+flag)& \text{if $i$,$j$>0} \end{cases} $$ $$ flags= \begin{cases} 0 & \text{if str1[i]==str2[j]}&\\ 1,& \text{if str1[i]!=str2[j]} \end{cases} $$ ### 计算形式化 可以利用迭代或者动态规划,建立$matrix[i][j]$矩阵来存放每一点的MED,并且记录他的上一步操作是什么,在第一次迭代的时候把所有可能路径的操作放在List列表中,在计算出结果后只需遍历List即可找回当时的操作记录。不需要重新对$matrix$进行二次遍历,提高了效率。 ![1600616496378](C:\Users\admin\AppData\Roaming\Typora\typora-user-images\1600616496378.png) ### 编程实现 ```python import numpy as np def mini(delete,insert,keep): if delete<insert and delete <keep: return delete,"delete" elif insert<delete and insert<keep: return insert,"insert" else: return keep,"keep" def mini2(delete,insert,replace): if delete<insert and delete <replace: return delete,"delete" elif insert<delete and insert<replace: return insert,"insert" else: return replace,"replace" def miniEditDistance(str1,str2): len1=len(str1); len2=len(str2); List=[]; matrix=np.zeros((len1+1,len2+1)) for row in range(1,len1+1): matrix[row][0]=row; for col in range(1,len2+1): matrix[0][col]=col; for row in range(1,len1+1): for col in range(1,len2+1): if str1[row-1]==str2[col-1]: matrix[row,col],temp=mini(matrix[row-1,col]+1,matrix[row,col-1]+1,matrix[row-1,col-1]) List.append(temp); else: matrix[row,col],temp=mini2(matrix[row-1,col]+1,matrix[row,col-1]+1,matrix[row-1,col-1]+1) List.append(temp); row =len1; col =len2; while row !=0 and col !=0: if List[(row-1)*len2+col-1]=="delete": print('%-10s'%str1[0:row],'%-10s'%str2[0:col],"delete ",str1[row]); row=row-1; col=col; continue if List[(row-1)*len2+col-1]=="insert": print('%-10s'%str1[0:row],'%-10s'%str2[0:col],"insert a ",str2[col]); row=row; col=col-1; continue if List[(row-1)*len2+col-1]=="keep": print('%-10s'%str1[0:row],'%-10s'%str2[0:col],"keep the same"); row=row-1; col=col-1; continue if List[(row-1)*len2+col-1]=="replace": print('%-10s'%str1[0:row],'%-10s'%str2[0:col],"replace ",str1[row-1],"with ",str2[col-1]); row=row-1; col=col-1; continue print(matrix[-1][-1]) miniEditDistance('expection','intention') ``` ```markdown expection intention keep the same expectio intentio keep the same expecti intenti keep the same expect intent keep the same expec inten replace t with t expe inte keep the same exp int replace e with e ex in replace p with t e i replace x with n ``` ### 评估 #### 1.准确性 在进行了多次实验后,结果均是正确。证明了MED动态规划的有效性 #### 2.复杂度 ``` Running time: 0.17652879999999993 Seconds Running time: 0.25646545111555555 Seconds ``` 由上可知,我们降低了时间复杂度,但是程序建立了List来存储,所以提高了空间复杂度。
662de6ed7f0511f2e542c22ec16f784660a68f22
[ "Markdown", "Python" ]
2
Python
Jzhengel/minimumEditDistance
84f13b38bf095780d95fe1e9519bd9b1467b3f11
3a7986c0ca3b4d97df7439a76a82397807720a4a
refs/heads/master
<file_sep>$( document ).ready(function() { $('div:has(img[alt="www.000webhost.com"])').css("display","none"); });
2b92f56f2434a504ecacd7946d74c31d9675c7dd
[ "JavaScript" ]
1
JavaScript
skt0501/programfactory
8ccd5fdcabd3f9deec4307070e769b3cdd0f0f37
ed78bdca28f266399083beb0b1a05154cd27da74
refs/heads/master
<repo_name>AOTeam/BaiBaoDai<file_sep>/README.md # - 百宝袋项目 <file_sep>/百宝袋/FistType.h // // Created by apple on 15/11/24. // Copyright © 2015年 zhangzhimin. All rights reserved. // #ifndef FistType_h #define FistType_h typedef enum FistType { FistType_jiandao = 1, FistType_shitou = 2, FistType_bu = 3, }FistType; #endif /* FistTyper_h */
4970737e7d220ee6a17060bb1a56f50d9dff7c34
[ "Markdown", "C" ]
2
Markdown
AOTeam/BaiBaoDai
7b8418f3629586e7f3c9c04f7f1e6c1b06576ea0
3d1bdd56e652700dbc96babb616dc78a46f3ba77
refs/heads/master
<repo_name>hujiejeff/blog<file_sep>/app/Http/Middleware/Activity.php <?php /** * Created by PhpStorm. * User: hujie * Date: 17-7-12 * Time: 下午6:53 */ namespace App\Http\Middleware; use Closure; class Activity { public function handle($request,Closure $next) { if(time()<strtotime('2017-07-01')){ return redirect('activity0'); } return $next($request); } }<file_sep>/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use App\Articles; use App\Cats; use App\Tags; 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\Http\Response */ public function index() { return view('home.index', [ 'actions' => 'admin', 'action' => 'index', 'action_name' => '网站分析' ]); } public function createArticle(Request $request) { if ($request->isMethod('get')) { $cats = Cats::all()->toArray(); $tags = Tags::all()->toArray(); return view('home.create_article', [ 'cats' => $cats, 'tags' => $tags, 'tagss' => [], 'actions' => 'article', 'action' => 'create', 'action_name' => '新建文章', ]); } else { $this->validate($request, [ 'title' => 'bail|required|max:225', 'content' => 'required', 'cat_id' => 'required', 'tags' => 'nullable|array' ]); $article = new Articles(); $article->cat_id = $request->input('cat_id'); $article->title = $request->input('title'); $article->content = $request->input('content'); $tags = $request->input('tags'); if ($article->save()) { if ($tags) { foreach ($tags as $tag) { $article->tags()->attach($tag,['created_at' => time(),'updated_at' => time()]); } } return redirect()->route('article'); } } return true; } public function deleteArticle($id) { $article = Articles::find($id); if ($article->delete()) { $article->tags()->detach(); return redirect()->back(); } else { return redirect()->back(); } } public function updateArticle(Request $request, $id) { $article = Articles::find($id); if ($request->isMethod('get')) { $cats = Cats::all()->toArray(); $tags = Tags::all()->toArray(); $model_tags = $article->tags->toArray(); $article_tag = []; foreach ($model_tags as $el){ $article_tag[] = $el['id']; } return view('home.update_article', [ 'cats' => $cats, 'tags' => $tags, 'tagss' => $article_tag, 'article' => $article, 'actions' => 'article', 'action' => 'update', 'action_name' => '更新文章' ]); } else { $this->validate($request, [ 'title' => 'bail|required|max:225', 'content' => 'required', 'cat_id' => 'required', ]); $article->cat_id = $request->input('cat_id'); $article->title = $request->input('title'); $article->content = $request->input('content'); $tags = $request->input('tags'); if ($article->save()) { if($tags){ $times = ['created_at' => time(),'updated_at' => time()]; $arr = array_fill_keys($tags,$times); $article->tags()->sync($arr); } return redirect()->route('article'); } } return true; } public function selectArticle() { $articles = Articles::all(); return view('home.select_article', [ 'actions' => 'article', 'action' => 'index', 'action_name' => '文章显示', 'articles' => $articles ]); } public function createCat(Request $request) { if ($request->isMethod('get')) { return view('home.create_cat', [ 'actions' => 'cat', 'action' => 'create', 'action_name' => '新建分类' ]); } else { $this->validate($request, [ 'name' => 'bail|required|max:255' ]); $cat = new Cats(); $cat->name = $request->input('name'); if ($cat->save()) { return redirect()->route('cat'); } } return true; } public function deleteCat($id) { if (Cats::find($id)->delete()) { return redirect()->back(); } else { return redirect()->back(); } } public function updateCat(Request $request, $id) { $cat = Cats::find($id); if ($request->isMethod('get')) { return view('home.update_cat', [ 'actions' => 'cat', 'action' => 'update', 'action_name' => '更新分类', 'cat' => $cat, ]); } else { $this->validate($request, ['name' => 'bail|required|max:255']); $cat->name = $request->input('name'); if ($cat->save()) { return redirect()->route('cat'); } } return true; } public function selectCat() { $cats = Cats::all(); return view('home.select_cat', [ 'actions' => 'cat', 'action' => 'index', 'action_name' => '分类显示', 'cats' => $cats ]); } public function createTag(Request $request) { if ($request->isMethod('get')) { return view('home.create_tag', [ 'actions' => 'tag', 'action' => 'create', 'action_name' => '新建标签', ]); } else { $this->validate($request, [ 'name' => 'bail|required|max:25', ]); $tag = new Tags(); $tag->name = $request->input('name'); if ($tag->save()) { return redirect()->route('tag'); } } return true; } public function deleteTag($id) { if (Tags::find($id)->delete()) { return redirect()->back(); } else { return redirect()->back(); } } public function updateTag(Request $request, $id) { $tag = Tags::find($id); if ($request->isMethod('get')) { return view('home.update_tag', [ 'actions' => 'tag', 'action' => 'update', 'action_name' => '更新标签', 'tag' => $tag ]); } else { $this->validate($request, [ 'name' => 'bail|required|max:25' ]); $tag->name = $request->input('name'); if ($tag->save()) { return redirect()->route('tag'); } } return true; } public function selectTag() { $tags = Tags::all(); return view('home.select_tag', [ 'actions' => 'tag', 'action' => 'index', 'action_name' => '标签显示', 'tags' => $tags ]); } } <file_sep>/app/Http/Controllers/StudentController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use App\Student; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Session; class StudentController { public function test1() { //查询 // $students = DB::select('select * from student'); //插入 // $bool = DB::insert('insert into student (name,age) value (?,?)', // ['hujie',20]); // var_dump($bool); //更新 // $num = DB::update('update student set age = ? where name = ?', // [30, 'hujie']); // var_dump($num); // dd($students); //删除 $num = DB::delete('delete from student where id > ?', [1001]); } public function query1() { //插入 // $bool = DB::table('student')->insert([ // 'name' => 'hujie2', // 'age' => '18' // ]); // dd($bool); //插入返回id // $id = DB::table('student')->insertGetId([ // 'name' => 'hujie3', // 'age' => 20 // ]); // dd($id); //插入多条 $bool = DB::table('student')->insert([ ['name' => 'jeff', 'age' => 30], ['name' => 'hujiejeff', 'age' => 12] ]); dd($bool); } public function query2() { //更新数据 // $num = DB::table('student') // ->where('id',1001) // ->update(['name' => 'kk']); // dd($num); //自增 // $num = DB::table('student')->increment('age'); $num = DB::table('student') ->where('age', 29) ->decrement('age', 1, ['sex' => 20]); } public function query3() { //删除数据 // $num = DB::table('student') // ->where('id', 1001) // ->delete(); //多条删除 $num = DB::table('student') ->where('id', '>=', 1006) ->delete(); dd($num); //删除整个表 // DB::table('student')->truncate(); } public function query4() { //获得所有 get // $students = DB::table('student')->get(); //获取第一条 first // $students = DB::table('student') // ->orderBy('id','desc') // ->first(); // where // $students = DB::table('student') // ->where('id','>=',1004) // ->get(); //whereRaw // $students = DB::table('student') // ->whereRaw('id > ? and age > ?',[1001,19]) // ->get(); //pluck 投影 // $students = DB::table('student') // ->pluck('name'); //select // $students = DB::table('student') // ->select('name', 'age') // ->get(); //chunk $students = DB::table('student')->orderBy('id', 'desc')->chunk(1, function ($students) { echo '<pre/>'; var_dump($students); }); // dd($students); } public function query5() { //聚合函数 //count $num = DB::table('student')->count(); //max $max = DB::table('student')->max('age'); //min avg sum dd($max); } public function orm1() { // $students = Student::all(); // dd($students); // $student = Student::findOrFail(1009); // dd($student); $students = Student::get(); dd($students); } public function orm2() { // $student = new Student(); // $student->name = 'orm'; // $student->age = 18; // $bool = $student->save(); // dd($bool); // $student = Student::find(1007); // dd($student->created_at); // $student = Student::create(['name' => 'lll', 'age' => 99]); // dd($student); //firstOrCreate 以属性查找,没有则新建记录 //firstOrNew 以属性查找,没有则新建对象,需要自己保存记录 } public function orm3() { $student = Student::find(1007); $student->name = 'chang'; $bool = $student->save(); dd($bool); } public function blade() { return view('student.test', [ 'name' => 'hujie1', ]); } public function request1(Request $request) { //取值 $name = $request->input('name', 'kong'); echo $name; } public function session1(Request $request) { //1 http session // $request->session()->put('name','hujie'); //2 session() // session()->put('name','hujie2'); //3 Session // Session::put('name','hujie3'); //数组存放 // Session::put(['name' => 'huje4']); //存数组 Session::push('name1', 'hujie5'); Session::push('name1', 'kkkkkk'); } public function session2(Request $request) { // dd($request->session()->get('name1')); // Session::pull('name1');取完删除 return Session::get('message', 'null'); // dd(Session::all()); //has 判断 // Session::has('name'); //删除 // Session::forget('name'); //清空session // Session::flush(); //flash 暂存数据 只会出现在第一次 //Session::flash(); } public function response1() { //相应json // $data = ['name' => 'hujie', 'age' => 18]; // return response()->json($data); //重定向 with 快闪数据 // return redirect('session2')->with('message','test'); //action // return redirect()->back(302); } public function activity0() { // return '活动快要开始了,敬请期待'; abort(503); } public function activity1() { return '活动进行中'; } public function mail() { // Mail::raw('邮件内容 测试2', function ($message) { // $message->from('<EMAIL>','胡杰'); // $message->subject('主题 测试'); // $message->to('<EMAIL>'); // }); Mail::send('index.index',['name' => 'hujie'],function ($message){ $message->to('<EMAIL>'); }); } }<file_sep>/app/Http/Middleware/VisitedRecord.php <?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Log; class VisitedRecord { public function handle($request,Closure $next) { return $next($request); } }<file_sep>/app/Http/Controllers/IndexController.php <?php namespace App\Http\Controllers; use App\Articles; use App\Cats; use App\Tags; use Illuminate\Http\Request; class IndexController extends Controller { private $arr; public function __construct() { $this->middleware('visited_record'); $this->arr = [ 'articles_num' => Articles::all()->count(), 'cats_num' => Cats::all()->count(), 'tags_num' => Tags::all()->count(), ]; } public function index(Request $request) { $articles = Articles::orderBy('created_at', 'desc')->paginate(3); return view('index.index', ['articles' => $articles, 'arr' => $this->arr]); } public function archives() { $articles = Articles::orderBy('created_at', 'desc')->paginate(8); return view('index.archives', ['articles' => $articles, 'arr' => $this->arr]); } public function article($id = 1) { $article = Articles::find($id); $article->read_num++; $article->save(); return view('index.view', ['article' => $article, 'arr' => $this->arr]); } public function cats() { $cats = Cats::all(); return view('index.cats', ['cats' => $cats, 'arr' => $this->arr]); } public function cat($id = 1) { $cat_name = Cats::find($id)->name; $articles = Articles::where('cat_id', $id)->orderBy('created_at', 'desc')->paginate(8); return view('index.cat', ['articles' => $articles, 'cat_name' => $cat_name, 'arr' => $this->arr]); } public function tags() { $tags = Tags::all(); return view('index.tags', ['tags' => $tags,'arr' => $this->arr]); } public function tag($id) { $tag = Tags::find($id); $tag_name = $tag->name; $articles = $tag->articles->reverse(); return view('index.tag', ['articles' => $articles,'arr' => $this->arr,'tag_name' => $tag_name]); } public function search(Request $request) { $key_word = $request->input('key_word',null); $before_time = microtime(true); if($key_word) { $articles = Articles::where('content', 'like', '%' . $key_word . '%')->get(['id','title'])->all(); }else{ $articles = null; } $after_time = microtime(true); $articles['time'] = ($after_time -$before_time)*1000; $articles['length'] = count($articles)-1; return response()->json($articles); } }<file_sep>/dbsql/articles.sql CREATE TABLE `cats`( `id` INT PRIMARY KEY AUTO_INCREMENT, `name` VARCHAR (255) NOT NULL , `creartd_at` INT (11) NOT NULL , ` updated_at` INT (11) NOT NULL )ENGINE=InnoDB; CREATE TABLE `articles`( `id` INT(11) PRIMARY KEY AUTO_INCREMENT, `user_id` INT NOT NULL , `cat_id` INT NOT NULL , `title` VARCHAR(255) NOT NULL , `content` TEXT NOT NULL , `created_at` INT(11) NOT NULL , `updated_at` INT(11) NOT NULL, FOREIGN KEY (cat_id) REFERENCES cats(id) ON DELETE RESTRICT )ENGINE=InnoDB; CREATE TABLE `laravel`.`article_tag` ( `id` INT NOT NULL AUTO_INCREMENT, `article_id` INT NOT NULL , `tag_id` INT NOT NULL , `created_at` INT(11) NOT NULL , `updated_at` INT(11) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB; CREATE TABLE `laravel`.`tags` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL , `created_at` INT(11) NOT NULL , `updated_at` INT(11) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;<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! | */ //Route::get('/', function () { // return view('welcome'); //}); //基础路由 //Route::get('hello', function () { // return "hello world"; //}); // //Route::post('log', function () { // return "hello post"; //}); ////多路由 //Route::match(['post', 'get'], 'match', function () { // return "match request"; //}); //全部 //Route::any('any', function () { // return 'any'; //}); //路由参数 //Route::get('user/{id}', function ($id) { // return 'user - ' . $id; //}); //路由正则匹配 //Route::get('user/{username?}', function ($username = 'hujie') { // return 'user:' . $username; //})->where('username', '[a-z]+'); //多参数 //Route::get('{username}/{id}', function ($username, $id) { // return $username . 'of' . $id; //}); //路由别名 //Route::get('login/test', ['as' => 'login_test', function () { // return route('login_test'); //}]); //路由群组 //Route::group //路由模板 //路由控制器 //Route::get('index/test','IndexController@test'); //Route::any('index/test', [ // 'uses' => 'IndexController@test', // 'as' => 'test' // ]); //Route::any('test1', ['uses' => 'StudentController@test1']); //Route::any('query1', ['uses' => 'StudentController@query1']); //Route::any('query2', ['uses' => 'StudentController@query2']); //Route::any('query3', ['uses' => 'StudentController@query3']); //Route::any('query4', ['uses' => 'StudentController@query4']); //Route::any('query5', ['uses' => 'StudentController@query5']); //Route::any('orm1', ['uses' => 'StudentController@orm1']); //Route::any('orm2', ['uses' => 'StudentController@orm2']); //Route::any('orm3', ['uses' => 'StudentController@orm3']); //Route::any('blade', ['uses' => 'StudentController@blade']); //Route::any('request1', ['uses' => 'StudentController@request1']); //Route::group(['middleware' => ['web']], function () { // Route::any('session1', ['uses' => 'StudentController@session1']); // Route::any('session2', ['uses' => 'StudentController@session2']); //}); //Route::any('response1', ['uses' => 'StudentController@response1']); //Route::any('activity0', ['uses' => 'StudentController@activity0']); //Route::any('activity1', ['uses' => 'StudentController@activity1']); //Route::any('mail', ['uses' => 'StudentController@mail']); // // //Route::group(['middleware' => ['activity']], function () { // Route::any('activity1', ['uses' => 'StudentController@activity1']); //}); // // //Auth::routes(); /* * Auth for admin */ Route::get('login', 'Auth\LoginController@showLoginForm')->name('login'); Route::post('login', 'Auth\LoginController@login'); Route::post('logout', 'Auth\LoginController@logout')->name('logout'); Route::get('/admin', 'HomeController@index')->name('admin'); //Route::get('api/students/{student}',function(\App\Student $student){ // return response()->json($student->getAttributes()); //}); /* * front for everyone */ Route::get('', 'IndexController@index'); Route::get('article/{id?}', 'IndexController@article'); Route::get('archives', 'IndexController@archives'); Route::get('cats', 'IndexController@cats'); Route::get('cat/{id?}', 'IndexController@cat'); Route::get('tags', 'IndexController@tags'); Route::get('tag/{id?}', 'IndexController@tag'); Route::get('search', 'IndexController@search')->name('search'); /* * article's CURD for admin */ Route::group(['prefix' => 'admin'], function () { Route::match(['post', 'get'], 'articles/create', 'HomeController@createArticle')->name('article_create'); Route::match(['post', 'get'], 'articles/update/{id?}', 'HomeController@updateArticle')->name('article_update'); Route::post('articles/delete/{id?}', 'HomeController@deleteArticle')->name('article_delete'); Route::match(['post', 'get'], 'articles/index', 'HomeController@selectArticle')->name('article'); /* * cat's CURD for admin */ Route::match(['post', 'get'], 'cats/create', 'HomeController@createCat')->name('cat_create'); Route::match(['post', 'get'], 'cats/update/{id}', 'HomeController@updateCat')->name('cat_update'); Route::post('cats/delete/{id}', 'HomeController@deleteCat')->name('cat_delete'); Route::match(['post', 'get'], 'cats/index', 'HomeController@selectCat')->name('cat'); /* * tag's CURD for admin */ Route::match(['post', 'get'], 'tags/create', 'HomeController@createTag')->name('tag_create'); Route::match(['post', 'get'], 'tags/update/{id}', 'HomeController@updateTag')->name('tag_update'); Route::post('/tags/delete/{id}', 'HomeController@deleteTag')->name('tag_delete'); Route::match(['post', 'get'], 'tags/index', 'HomeController@selectTag')->name('tag'); }); Route::group(['prefix' => 'chat'], function () { Route::get('index','ChatController@index')->name('chat'); });<file_sep>/app/Article_tag.php <?php namespace App; use Illuminate\Database\Eloquent\Relations\Pivot; class Article_tag extends Pivot { protected $table = 'article_tag'; protected $primaryKey = 'id'; public $timestamps = true; protected function getDateFormat() { return time(); } }<file_sep>/app/Tags.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Tags extends Model { protected $table = 'tags'; protected $primaryKey = 'id'; public $timestamps = true; protected function getDateFormat() { return time(); } public function articles() { return $this->belongsToMany( 'App\Articles', 'article_tag', 'tag_id', 'article_id'); // return $this->belongsToMany('App\Articles')->withTimestamps()->using('App\Article_tag'); } }<file_sep>/app/Articles.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Articles extends Model { protected $table = 'articles'; protected $primaryKey = 'id'; public $timestamps = true; protected function getDateFormat() { return time(); } // protected function asDateTime($value) // { // return date('Y-m-d H:i:s',$value); // } public function cat() { return $this->hasOne('App\Cats', 'id', 'cat_id'); } public function next() { return Articles::find($this->id + 1); } public function pre() { return Articles::find($this->id - 1); } public function getYear() { return date('Y', $this->getAttributes()['created_at']); } public function tags() { return $this->belongsToMany( 'App\Tags', 'article_tag', 'article_id', 'tag_id'); // return $this->belongsToMany('App\Tags')->withTimestamps()->using('App\Article_tag'); } }<file_sep>/app/Cats.php <?php /** * Created by PhpStorm. * User: hujie * Date: 17-7-20 * Time: 下午4:55 */ namespace App; use Illuminate\Database\Eloquent\Model; class Cats extends Model { protected $table = 'cats'; protected $primaryKey = 'id'; public $timestamps = true; protected function getDateFormat() { return time(); } public function articles() { return $this->hasMany('App\Articles','cat_id','id'); } }<file_sep>/public/tets.php <?php /** * Created by PhpStorm. * User: hujie * Date: 17-7-9 * Time: 下午9:14 */ echo time();
e0d540ae6b2a40486b721703da18268eae4e86a7
[ "SQL", "PHP" ]
12
PHP
hujiejeff/blog
886353e31266f370ce7060c7cc8e4d8a3a64a29d
d570af545b5bb9d83b3e1573b6763744d5820fe9
refs/heads/master
<file_sep>## About Tracker VueJs System Tracker VueJs System is system to mange projects and tasks and handle users based on Laravel frameworke & Vuejs. ## How to Setup the system - Clone the system. - Copy .env.example & rename it to .env. - Create new database. - Connect with your new database. - Migrate database. <file_sep><?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! | */ Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Route::group(['middleware' => ['auth'], 'namespace' => 'Api', 'prefix' => 'api'], function(){ Route::apiResources([ 'user' => 'UserController', 'project' => 'ProjectController', 'task' => 'TaskController' ]); Route::get('{project}/tasks/get', 'TaskController@getProjectTasks')->name('project.tasks'); Route::get('projects/option', 'TaskController@ProjectOption')->name('project.option'); Route::get('dashboard', 'SettingController@dashboard')->name('dashoard'); }); Route::get('{path}',"HomeController@index")->where( 'path', '([A-z\d-\/_.]+)?' );
458d8c3ae508d585a974ea6c63178e05864f189c
[ "Markdown", "PHP" ]
2
Markdown
ma7salem/tracker-vue
4062e893f515c769d7df6be2385b4e9fa4bbdb52
f3f004727cf992b29b8fbae86a06b263156a4372
refs/heads/master
<repo_name>robin7654/BA<file_sep>/src/CollectedData.java import java.util.HashMap; import java.util.Map; public class CollectedData { private int actionPreFlop; private int playerBB; private int cardRating; private int wasRaisedBySomeoneElse; private int button; private int potSizeAtPreFlop; static Map<CollectedData, RewardEntry> map = new HashMap<CollectedData, RewardEntry>(); public int getActionPreFlop() { return actionPreFlop; } public int getPlayerBB() { return playerBB; } public int getCardRating() { return cardRating; } public int getWasRaisedBySomeoneElse() { return wasRaisedBySomeoneElse; } public int getButton() { return button; } public int getPotSizeAtPreFlop() { return potSizeAtPreFlop; } public CollectedData(int a, int b, int c, int d, int e, int f){ this.actionPreFlop = a; this.playerBB = b; this.cardRating = c; this.wasRaisedBySomeoneElse = d; this.button = e; this.potSizeAtPreFlop = f; } public CollectedData() { } public void createEntry(int value, int a, int b, int c, int d, int e, int f){ //CollectedData collectedData = new CollectedData(cardRating, button, playerBB, potSizeAtPreFlop, wasRaisedBySomeoneElse, actionPreFlop); try { RewardEntry rewEnt = map.get(new CollectedData(a,b,c,d,e,f)); rewEnt.addEntry(value); map.put(new CollectedData(a,b,c,d,e,f), rewEnt); }catch(Exception z) { map.put(new CollectedData(a,b,c,d,e,f), new RewardEntry(value)); } } public RewardEntry getEntry(int a, int b, int c, int d, int e, int f){ RewardEntry mapValue = map.get(new CollectedData(a,b,c,d,e,f)); return mapValue; } @Override public boolean equals(Object obj){ if (obj != null && obj instanceof CollectedData){ CollectedData dataObj = (CollectedData) obj; boolean propertyA = actionPreFlop == dataObj.getActionPreFlop(); boolean propertyB = playerBB == dataObj.getPlayerBB(); boolean propertyC = cardRating == dataObj.getCardRating(); boolean propertyD = wasRaisedBySomeoneElse == dataObj.getWasRaisedBySomeoneElse(); boolean propertyE = button == dataObj.getButton(); boolean propertyF = potSizeAtPreFlop == dataObj.getPotSizeAtPreFlop(); return propertyA && propertyB && propertyC && propertyD && propertyE && propertyF; } return false ; } @Override public int hashCode(){ int hash = 17; hash = hash * 31 * actionPreFlop; hash = hash * 31 * playerBB; hash = hash * 31 * cardRating; hash = hash * 31 * wasRaisedBySomeoneElse; hash = hash * 31 * button; hash = hash * 31 * potSizeAtPreFlop; return hash; } } <file_sep>/src/PokerKI.java import java.awt.Color; import java.awt.Font; import javax.swing.*; import java.awt.event.ActionListener; import java.io.IOException; import java.awt.event.ActionEvent; public class PokerKI { public JFrame frame; private JTextField textField; JLabel lblBoard0 = new JLabel("Board0"); JLabel lblBoard1 = new JLabel("Board1"); JLabel lblBoard2 = new JLabel("Board2"); JLabel lblBoard3 = new JLabel("Board3"); JLabel lblBoard4 = new JLabel("Board4"); JLabel lblHole0 = new JLabel("Hole1"); JLabel lblHole1 = new JLabel("Hole2"); JLabel lblHole2 = new JLabel("Hole3"); JLabel lblHole3 = new JLabel("Hole4"); JLabel lblHole4 = new JLabel("Hole5"); JLabel lblHole5 = new JLabel("Hole6"); ImageIcon testimg = new ImageIcon("C:/Users/robin7654/Desktop/pokerkartenklein/" + 1 + ".jpg"); public JLabel lblDealerButton = new JLabel(""); public JLabel lblBalancePlayer0 = new JLabel("$0"); public JLabel lblBalancePlayer1 = new JLabel("$0"); public JLabel lblBalancePlayer2 = new JLabel("$0"); public JLabel lblBet0 = new JLabel(""); public JLabel lblBet1 = new JLabel(""); public JLabel lblBet2 = new JLabel(""); public JLabel lblPot = new JLabel(""); public JLabel lblLog = new JLabel(""); public JScrollPane spLog = new JScrollPane(lblLog); JScrollBar vertical; Font fontTextField = new Font("SansSerif", Font.BOLD, 15); Font fontMain = new Font("SansSerif", Font.BOLD, 15); Font fontValues = new Font("SansSerif", Font.BOLD, 25); Font fontLog = new Font("SansSerif",Font.PLAIN, 12); int moneyHeight = 20; int buttonWidth = 120; int betWidth = 100; String log = ""; String logStart = "<html>"; String logEnd = "</html>"; public void setBalanceColorPositive(int i) { if(i == 0) lblBalancePlayer0.setForeground(Color.GREEN); if(i == 1) lblBalancePlayer1.setForeground(Color.GREEN); if(i == 2) lblBalancePlayer2.setForeground(Color.GREEN); } public void setBalanceColorNeutral(int i) { if(i == 0) lblBalancePlayer0.setForeground(Color.WHITE); if(i == 1) lblBalancePlayer1.setForeground(Color.WHITE); if(i == 2) lblBalancePlayer2.setForeground(Color.WHITE); } static JButton btnFold; static JButton btnCall; static JButton btnRaise; JButton btnStartNewHand; static JButton btnStartNewGame; static JButton btnExit; static JButton btnPlayX; static JButton btnLoadFromTxt; static JButton btnTest; public void setCCButton() { if(!GameController.activeGame) { btnCall.setBackground(Color.GRAY); btnFold.setBackground(Color.GRAY); btnRaise.setBackground(Color.GRAY); btnStartNewHand.setBackground(Color.GRAY); return; } if(GameController.activeHand) { btnCall.setBackground(Color.GREEN); btnFold.setBackground(Color.GREEN); btnRaise.setBackground(Color.GREEN); btnStartNewHand.setBackground(Color.GRAY); } else{ btnCall.setBackground(Color.GRAY); btnFold.setBackground(Color.GRAY); btnRaise.setBackground(Color.GRAY); if(GameController.gameState == 5) btnStartNewHand.setBackground(Color.GREEN); } if(GameController.highestBet == GameController.player[0].bet) btnCall.setText("Check"); else btnCall.setText("Call $" + (GameController.highestBet-GameController.player[0].bet)); } public void setStartNewHandButton() { if(GameController.activeHand) btnStartNewHand.setBackground(Color.GRAY); else if(GameController.gameState == 5 && GameController.activeGame) btnStartNewHand.setBackground(Color.GREEN); } public void setButtons() { setCCButton(); setStartNewHandButton(); } /** * Launch the application. */ /*public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { PokerKI window = new PokerKI(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }*/ /*public void run() { EventQueue.invokeLater(new Runnable() { public void run() { try { PokerKI window = new PokerKI(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }*/ /** * Create the application. */ public PokerKI() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(0, 0, 1304, 799); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setUndecorated(true); frame.getContentPane().setLayout(null); frame.getContentPane().setBackground(Color.decode("#555555")); frame.setContentPane(new JLabel(new ImageIcon("src/images/pokertisch.jpg"))); btnTest = new JButton("TEST"); btnTest.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int[] testkarten = {0,51,47,43,38}; //int x = DetermineWinner.isStraightDraw(testkarten); //int y = DetermineWinner.mostCommonSuiteCount(testkarten); boolean y = DetermineWinner.isStraight(testkarten) != null; //System.out.println(x); System.out.println(y); } }); btnTest.setBounds(200, 200, 80, 60); btnTest.setBackground(Color.PINK); btnTest.setFont(fontMain); frame.getContentPane().add(btnTest); btnRaise = new JButton("Raise"); btnRaise.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(GameController.gameState > 3 || textField.getText().isEmpty()) return; int amount = Integer.parseInt(textField.getText()); GameController.player[0].raise(amount); textField.setText(""); while(GameController.activeHand && GameController.player[GameController.activePlayer].bot) GameController.getNextMove(); if(GameController.player[GameController.activePlayer].acted == true) { GameController.changeGameState(); } } }); btnRaise.setBounds(frame.getWidth() - 20 - buttonWidth, frame.getHeight()-120, buttonWidth, 24); btnRaise.setBackground(Color.GRAY); btnRaise.setFont(fontMain); frame.getContentPane().add(btnRaise); textField = new JTextField(); textField.setBounds(btnRaise.getX() - 20 - buttonWidth, frame.getHeight()-120, buttonWidth, 24); textField.setColumns(10); textField.setFont(fontTextField); frame.getContentPane().add(textField); btnCall = new JButton("Call"); btnCall.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(GameController.gameState > 3) return; GameController.player[0].call(); while(GameController.activeHand && GameController.player[GameController.activePlayer].bot) GameController.getNextMove(); if(GameController.player[GameController.activePlayer].acted == true) { GameController.changeGameState(); } } }); btnCall.setBounds(textField.getX() - 20 - buttonWidth, frame.getHeight()-120, buttonWidth, 24); btnCall.setBackground(Color.GRAY); btnCall.setFont(fontMain); frame.getContentPane().add(btnCall); btnFold = new JButton("Fold"); btnFold.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(GameController.gameState > 3) return; GameController.player[0].fold(); while(GameController.activeHand && GameController.player[GameController.activePlayer].bot) GameController.getNextMove(); if(GameController.player[GameController.activePlayer].acted == true) { GameController.changeGameState(); } } }); btnFold.setBounds(btnCall.getX() - 20 - buttonWidth, frame.getHeight()-120, buttonWidth, 24); btnFold.setBackground(Color.GRAY); btnFold.setFont(fontMain); frame.getContentPane().add(btnFold); btnExit = new JButton("Exit"); btnExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); btnExit.setBounds(frame.getWidth() - 100, frame.getHeight() - 48, 100, 48); btnExit.setBackground(Color.RED); btnExit.setFont(fontMain); frame.getContentPane().add(btnExit); btnPlayX = new JButton("Play X Games"); btnPlayX.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { long tStart = System.currentTimeMillis(); GameController.playX(100); long tEnd = System.currentTimeMillis(); System.out.println(((tEnd-tStart)/1000) + " s"); } }); btnPlayX.setBounds(frame.getWidth() - 200, 0, 200, 48); btnPlayX.setBackground(Color.BLUE); btnPlayX.setFont(fontMain); frame.getContentPane().add(btnPlayX); btnLoadFromTxt = new JButton("Load"); btnLoadFromTxt.setBounds(0,0,100,48); btnLoadFromTxt.setFont(fontMain); btnLoadFromTxt.setBackground(Color.BLUE); btnLoadFromTxt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { long tStart = System.currentTimeMillis(); GameController.readFromTxt(); System.out.println("Everything alright"); long tEnd = System.currentTimeMillis(); System.out.println(((tEnd - tStart)/1000) + "s"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); frame.getContentPane().add(btnLoadFromTxt); lblBoard2.setBounds((frame.getWidth()/2) - 83/2, frame.getHeight()/4, 83, 117); frame.getContentPane().add(lblBoard2); lblBoard1.setBounds(lblBoard2.getX() - lblBoard2.getWidth() - 2, lblBoard2.getY(), 83, 117); frame.getContentPane().add(lblBoard1); lblBoard0.setBounds(lblBoard1.getX() - lblBoard1.getWidth() - 2, lblBoard2.getY(), 83, 117); frame.getContentPane().add(lblBoard0); lblBoard3.setBounds(lblBoard2.getX() + lblBoard2.getWidth() + 8, lblBoard2.getY(), 83, 117); frame.getContentPane().add(lblBoard3); lblBoard4.setBounds(lblBoard3.getX() + lblBoard3.getWidth() + 8, lblBoard2.getY(), 83, 117); frame.getContentPane().add(lblBoard4); lblHole0.setBounds((frame.getWidth()/2 - 83 - 1), frame.getHeight()*4/7, 83, 117); frame.getContentPane().add(lblHole0); lblHole1.setBounds((frame.getWidth()/2 + 1), lblHole0.getY(), 83, 117); frame.getContentPane().add(lblHole1); lblHole2.setBounds(frame.getWidth()/5, lblBoard2.getY() - 117 - 30, 83, 117); frame.getContentPane().add(lblHole2); lblHole3.setBounds(lblHole2.getX() - 83 - 2, lblBoard2.getY() - 117 - 30, 83, 117); frame.getContentPane().add(lblHole3); lblHole4.setBounds(frame.getWidth()*5/7, lblBoard2.getY() - 117 - 30, 83, 117); frame.getContentPane().add(lblHole4); lblHole5.setBounds(lblHole4.getX() + 83 + 2, lblBoard2.getY() - 117 - 30, 83, 117); frame.getContentPane().add(lblHole5); setCardLabel(0,52); setCardLabel(1,52); setCardLabel(2,52); setCardLabel(3,52); setCardLabel(4,52); setCardLabel(5,52); setCardLabel(6,52); setCardLabel(7,52); setCardLabel(8,52); setCardLabel(9,52); setCardLabel(10,52); btnStartNewHand = new JButton("Next Hand"); btnStartNewHand.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(GameController.gameState < 5 || GameController.activeGame == false) return; GameController.startNewHand(); drawButton(GameController.button); } }); btnStartNewHand.setBounds(btnRaise.getX() + btnRaise.getWidth() - 120, btnRaise.getY() - 48 - 12, 120, 48); btnStartNewHand.setBackground(Color.GRAY); btnStartNewHand.setFont(fontMain); frame.getContentPane().add(btnStartNewHand); btnStartNewGame = new JButton("Start New Game"); btnStartNewGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { GameController.startNewGame(); drawButton(GameController.button); } }); btnStartNewGame.setBounds(0, frame.getHeight() - 48, 180, 48); btnStartNewGame.setBackground(Color.GREEN); btnStartNewGame.setFont(fontMain); frame.getContentPane().add(btnStartNewGame); lblDealerButton.setBounds(347, 506, 46, moneyHeight); lblDealerButton.setForeground(Color.RED); lblDealerButton.setFont(new Font("SansSerif", Font.BOLD, 22)); frame.getContentPane().add(lblDealerButton); lblBalancePlayer0.setBounds(lblHole0.getX(), lblHole0.getY() + 117 + 8, lblHole0.getWidth()*2 + 2, moneyHeight); lblBalancePlayer0.setHorizontalAlignment(JLabel.CENTER); lblBalancePlayer0.setForeground(Color.WHITE); lblBalancePlayer0.setFont(fontValues); frame.getContentPane().add(lblBalancePlayer0); lblBalancePlayer1.setBounds(lblHole3.getX(), lblHole3.getY() - 14 - 12, lblHole0.getWidth()*2 + 2, moneyHeight); lblBalancePlayer1.setHorizontalAlignment(JLabel.CENTER); lblBalancePlayer1.setForeground(Color.WHITE); lblBalancePlayer1.setFont(fontValues); frame.getContentPane().add(lblBalancePlayer1); lblBalancePlayer2.setBounds(lblHole4.getX(), lblHole4.getY() - 14 - 12, lblHole0.getWidth()*2 + 2, moneyHeight); lblBalancePlayer2.setHorizontalAlignment(JLabel.CENTER); lblBalancePlayer2.setForeground(Color.WHITE); lblBalancePlayer2.setFont(fontValues); frame.getContentPane().add(lblBalancePlayer2); lblBet0.setBounds(lblBalancePlayer0.getX(), lblHole0.getY() - 14 - 12, lblHole0.getWidth()*2 + 2, moneyHeight); lblBet0.setForeground(Color.WHITE); lblBet0.setHorizontalAlignment(JLabel.CENTER); lblBet0.setFont(fontValues); frame.getContentPane().add(lblBet0); lblBet1.setBounds(lblHole2.getX() + lblHole2.getWidth() + 8, lblHole2.getY() + (lblHole2.getHeight()/2 - 14/2), betWidth, moneyHeight); lblBet1.setForeground(Color.WHITE); lblBet1.setHorizontalAlignment(JLabel.CENTER); lblBet1.setFont(fontValues); frame.getContentPane().add(lblBet1); lblBet2.setBounds(lblHole4.getX() - 8 - betWidth, lblHole4.getY() + (lblHole4.getHeight()/2 - 14/2), betWidth, moneyHeight); lblBet2.setForeground(Color.WHITE); lblBet2.setHorizontalAlignment(JLabel.CENTER); lblBet2.setFont(fontValues); frame.getContentPane().add(lblBet2); lblPot.setBounds(lblBoard0.getX(), lblBoard2.getY() + lblBoard2.getHeight() + 8, lblBoard0.getWidth()*5 + 2*2 + 2*8, moneyHeight); lblPot.setForeground(Color.WHITE); lblPot.setHorizontalAlignment(JLabel.CENTER); lblPot.setFont(fontValues); frame.getContentPane().add(lblPot); spLog.setBounds(10, btnStartNewGame.getY() - btnStartNewGame.getHeight() - 100, 300, 100); frame.getContentPane().add(spLog); vertical = spLog.getVerticalScrollBar(); lblLog.setBackground(Color.BLACK); lblLog.setOpaque(true); lblLog.setForeground(Color.WHITE); lblLog.setFont(fontLog); lblLog.setVerticalAlignment(JLabel.TOP); lblLog.setText(log); } protected void updatePlayerBet() { if(GameController.player[0].bet == 0) lblBet0.setText(""); else lblBet0.setText("$" + Integer.toString(GameController.player[0].bet)); if(GameController.player[1].bet == 0) lblBet1.setText(""); else lblBet1.setText("$" + Integer.toString(GameController.player[1].bet)); if(GameController.player[2].bet == 0) lblBet2.setText(""); else lblBet2.setText("$" + Integer.toString(GameController.player[2].bet)); lblBet0.setText("$" + Integer.toString(GameController.player[0].bet)); lblBet1.setText("$" + Integer.toString(GameController.player[1].bet)); lblBet2.setText("$" + Integer.toString(GameController.player[2].bet)); } protected void updatePlayerBalance() { lblBalancePlayer0.setText("$" + Integer.toString(GameController.player[0].balance)); lblBalancePlayer1.setText("$" + Integer.toString(GameController.player[1].balance)); lblBalancePlayer2.setText("$" + Integer.toString(GameController.player[2].balance)); } protected void updatePot() { lblPot.setText("$" + Integer.toString(GameController.mainPot)); } protected void updateBotCards() { if(!GameController.player[1].activeInHand && GameController.gameState < 4) { setCardLabel(7, 53); setCardLabel(8, 53); } if(!GameController.player[2].activeInHand && GameController.gameState < 4) { setCardLabel(9,53); setCardLabel(10,53); } } public void updateAll() { updatePlayerBet(); updatePlayerBalance(); updatePot(); updateBotCards(); } public void addToLog(String s) { log += s + "<br/>"; lblLog.setText(logStart + log + logEnd); vertical.setValue(vertical.getMaximum()); } public void drawButton(int x) { lblDealerButton.setText("D"); switch (x) { case 0: lblDealerButton.setBounds(lblHole1.getX() + lblHole1.getWidth() + 8, lblHole1.getY() - 14 - 8, lblDealerButton.getWidth(), lblDealerButton.getHeight()); lblDealerButton.setHorizontalAlignment(JLabel.LEFT); break; case 1: lblDealerButton.setBounds(lblBet1.getX(), lblBet1.getY() + lblBet1.getHeight() + 8, lblDealerButton.getWidth(), lblDealerButton.getHeight()); lblDealerButton.setHorizontalAlignment(JLabel.LEFT); break; case 2: lblDealerButton.setBounds(lblBet2.getX() + lblBet2.getWidth() - 46, lblBet2.getY() + lblBet2.getHeight() + 8, lblDealerButton.getWidth(), lblDealerButton.getHeight()); lblDealerButton.setHorizontalAlignment(JLabel.RIGHT); break; } } public void openCards(int x){ switch (x){ case 0: setCardLabel(0,52); setCardLabel(1,52); setCardLabel(2,52); setCardLabel(3,52); setCardLabel(4,52); setCardLabel(5,52); setCardLabel(6,52); setCardLabel(7,52); setCardLabel(8,52); setCardLabel(9,52); setCardLabel(10,52); setCardLabel(5,GameController.cardDeck[5]); setCardLabel(6,GameController.cardDeck[6]); break; case 1: setCardLabel(0, GameController.cardDeck[0]); setCardLabel(1, GameController.cardDeck[1]); setCardLabel(2, GameController.cardDeck[2]); break; case 2: setCardLabel(3, GameController.cardDeck[3]); break; case 3: setCardLabel(4, GameController.cardDeck[4]); break; case 4: setCardLabel(7, GameController.cardDeck[7]); setCardLabel(8, GameController.cardDeck[8]); setCardLabel(9, GameController.cardDeck[9]); setCardLabel(10, GameController.cardDeck[10]); break; } } public void setCardLabel(int x, int y){ switch (x) { case 0: ImageIcon imgBoard = new ImageIcon("src/images/" + y + ".jpg"); lblBoard0.setIcon(imgBoard); break; case 1: ImageIcon imgBoard_1 = new ImageIcon("src/images/" + y + ".jpg"); lblBoard1.setIcon(imgBoard_1); break; case 2: ImageIcon imgBoard_2 = new ImageIcon("src/images/" + y + ".jpg"); lblBoard2.setIcon(imgBoard_2); break; case 3: ImageIcon imgBoard_3 = new ImageIcon("src/images/" + y + ".jpg"); lblBoard3.setIcon(imgBoard_3); break; case 4: ImageIcon imgBoard_4 = new ImageIcon("src/images/" + y + ".jpg"); lblBoard4.setIcon(imgBoard_4); break; case 5: ImageIcon imgHole = new ImageIcon("src/images/" + y + ".jpg"); lblHole0.setIcon(imgHole); break; case 6: ImageIcon imgHole_1 = new ImageIcon("src/images/" + y + ".jpg"); lblHole1.setIcon(imgHole_1); break; case 7: ImageIcon imgHole_2 = new ImageIcon("src/images/" + y + ".jpg"); lblHole2.setIcon(imgHole_2); break; case 8: ImageIcon imgHole_3 = new ImageIcon("src/images/" + y + ".jpg"); lblHole3.setIcon(imgHole_3); break; case 9: ImageIcon imgHole_4 = new ImageIcon("src/images/" + y + ".jpg"); lblHole4.setIcon(imgHole_4); break; case 10: ImageIcon imgHole_5 = new ImageIcon("src/images/" + y + ".jpg"); lblHole5.setIcon(imgHole_5); break; } } } <file_sep>/src/MonteCarloSimulation.java import java.util.stream.IntStream; public class MonteCarloSimulation { public int winProbabilityOnRiver(int cards[], int playerNumber, int opponent){ int[] winners = GameController.evaluate(cards); if (winners[playerNumber] > winners[opponent]){ return 1; } if (winners[playerNumber] == winners[opponent]){ return 2; } return 0; } public int winProbabilityOnRiver(int cards[], int playerNumber, int opponent1, int opponent2){ int[] winners = GameController.evaluate(cards); //verlierer if (winners[playerNumber] < winners[opponent1] | winners[playerNumber] < winners[opponent2]){ return 0; } //gewinner if (winners[playerNumber] > winners[opponent1] & winners[playerNumber] > winners[opponent2]){ return 1; } //split 3 if (winners[playerNumber] == winners[opponent1] & winners[opponent1] == winners[opponent2]){ return 3; } //split 2 if (winners[playerNumber] > winners[opponent1] | winners[playerNumber] > winners[opponent2]){ return 2; } return -1; } public int winProbabilityOnTurn(int cards[], int playerNumber, int opponent1, int opponent2){ int [] cardsWithoutRiver = cards.clone(); cardsWithoutRiver[4] = -1; double wins = 0; for (int i = 0; i < 52; i++){ int a = i; if (IntStream.of(cardsWithoutRiver).anyMatch(x -> x == a) == false){ cardsWithoutRiver[4]= i; int winProbabilityOnRiver = winProbabilityOnRiver(cardsWithoutRiver, playerNumber, opponent1, opponent2); if (winProbabilityOnRiver != 0)wins = wins + 1/winProbabilityOnRiver; } } return (int) (100*wins/42) ; } public int winProbabilityOnTurn(int cards[], int playerNumber, int opponent){ int [] cardsWithoutRiver = cards.clone(); cardsWithoutRiver[4] = -1; double wins = 0; for (int i = 0; i < 52; i++){ int a = i; if (IntStream.of(cardsWithoutRiver).anyMatch(x -> x == a) == false){ cardsWithoutRiver[4]= i; int winProbabilityOnRiver = winProbabilityOnRiver(cardsWithoutRiver, playerNumber, opponent); if (winProbabilityOnRiver != 0)wins = wins + 1/winProbabilityOnRiver; } } return (int) (100*wins/42) ; } public int winProbabilityOnFlop(int cards[], int playerNumber, int opponent1, int opponent2){ int [] cardsWithoutTurn = cards.clone(); cardsWithoutTurn[4] = -1; cardsWithoutTurn[3] = -1; double wins = 0; for (int i = 0; i < 52; i++){ int a = i; if (IntStream.of(cardsWithoutTurn).anyMatch(x -> x == a) == false){ cardsWithoutTurn[3]= i; int winProbabilityOnTurn = winProbabilityOnTurn(cardsWithoutTurn, playerNumber, opponent1, opponent2); if (winProbabilityOnTurn != 0)wins = wins + winProbabilityOnTurn; } } return (int) (wins/43) ; } public int winProbabilityOnFlop(int cards[], int playerNumber, int opponent){ int [] cardsWithoutTurn = cards.clone(); cardsWithoutTurn[4] = -1; cardsWithoutTurn[3] = -1; double wins = 0; for (int i = 0; i < 52; i++){ int a = i; if (IntStream.of(cardsWithoutTurn).anyMatch(x -> x == a) == false){ cardsWithoutTurn[3]= i; int winProbabilityOnTurn = winProbabilityOnTurn(cardsWithoutTurn, playerNumber, opponent); if (winProbabilityOnTurn != 0)wins = wins + winProbabilityOnTurn; } } return (int) (wins/43) ; } } <file_sep>/src/Player.java import java.util.Random; public class Player { String playerName; int playerNum; int balance; int bet; boolean activeInGame; boolean activeInHand; boolean allIn; boolean bot; boolean rand; boolean acted; boolean playsForSidePot = false; //int balance = 0; int bbThird = 0; int potSizeInBBThird = 0; int action = 0; int hasButton = 0; int wasRaisedBySomeoneElse = 0; int card0, card1; int timesF = 0; int timesC = 0; int timesR = 0; int[] flop = new int[3]; int[] turn = new int[4]; int[] river = new int[5]; int flopCombination, turnCombination, riverCombination; int highestFlopCardIsInHandCombination, highestTurnCardIsInHandCombination, highestRiverCardIsInHandCombination; int flushDrawOnFlop, flushDrawOnTurn; int straightDrawOnFlop, straightDrawOnTurn; public Player(boolean b, boolean r, String pName, int pNum){ playerName = pName; playerNum = pNum; bot = b; rand = r; balance = 500; activeInGame = true; activeInHand = true; bet = 0; allIn = false; acted = false; } public void raise(int n) { if(balance + bet > n) { balance += bet; bet = n; balance -= bet; } else { bet += balance; balance = 0; allIn = true; } for(int i = 0; i < GameController.player.length; i++) { GameController.player[i].acted = false; } this.acted = true; action = 2; GameController.highestBet = bet; //System.out.println(playerName + " raised to " + bet); GameController.changeActivePlayer(); } public void call() { if(bet < GameController.highestBet && balance + bet > GameController.highestBet) { balance += bet; bet = GameController.highestBet; balance -= bet; //System.out.println(playerName + " called " + bet); }else if(balance + bet <= GameController.highestBet) { bet += balance; balance = 0; allIn = true; }else { //System.out.println(playerName + " checked"); } this.acted = true; action = 1; GameController.changeActivePlayer(); } public void fold(){ activeInHand = false; this.acted = true; //System.out.println(playerName + " folded"); int[] bets = new int[3]; for(int i = 0; i < GameController.player.length; i++) { bets[i] = GameController.player[i].bet; } if(GameController.minWithoutZero(bets) >= bet) { boolean b = true; for(int i = 0; i < 3; i++) { if(GameController.player[i].balance + GameController.player[i].bet < bet && GameController.player[i].activeInGame) { b = false; } } if(b) { GameController.mainPot += bet; bet = 0; } } GameController.changeActivePlayer(); action = 0; } public void setBlind(int n) { if(balance + bet < n) { bet += balance; balance = 0; allIn = true; acted = true; }else { balance += bet; bet = n; balance -= bet; } } public void decideMove() { saveVar(); if(!rand && GameController.gameState == 0) { findBestMovePreFlop(); }else if(!rand && GameController.gameState == 1) { findBestMoveOnFlop(); }else if(!rand && GameController.gameState == 2) { findBestMoveOnTurn(); } else if(!rand && GameController.gameState == 3) { findBestMoveOnRiver(); } else { Random randomGenerator = new Random(); int rand = randomGenerator.nextInt(10); if(rand < 0 && GameController.highestBet > bet) { fold(); return; } else if(rand < 0) { if(balance + bet <= GameController.highestBet) call(); else if(GameController.highestBet == 0) raise(GameController.blind); else { raise(GameController.highestBet*2); return; } } else { call(); } } } public void printOutSituationFound(int n) { String state = ""; if(GameController.gameState == 0) state = "PreFlop"; else if(GameController.gameState == 1) state = "Flop"; else if(GameController.gameState == 2) state = "Turn"; else if(GameController.gameState == 3) state = "River"; if(n != 0) { //System.out.println("Situation found on " + state); }//else System.out.println("Situation not found on " + state); } public void decideMove(int max, int j) { printOutSituationFound(max); Random randomGenerator = new Random(); int rand = randomGenerator.nextInt(100); if(rand < 70) { j = ((j+1) + (rand%2))%3; } if(j == 0) { if(GameController.highestBet > bet) fold(); else call(); } else if(j == 1) { call(); } else { if(GameController.highestBet == 0) raise(GameController.blind*4); else raise(GameController.highestBet*4); } } public void findBestMovePreFlop() { int max = Integer.MIN_VALUE; int n = 0; int j = 0; for(int i = 0; i < 3; i++) { n = getSimilarSituationAveragePreFlop( i, bbThird, GameController.dsW.getRating(card0, card1), wasRaisedBySomeoneElse, hasButton, potSizeInBBThird); if(n > max) { max = n; j = i; } } decideMove(max, j); } public void findBestMoveOnFlop() { int max = Integer.MIN_VALUE; int n = 0; int j = 0; for(int i = 0; i < 3; i++) { n = getSimilarSituationAverageOnFlop( i, flopCombination, bbThird, wasRaisedBySomeoneElse, highestFlopCardIsInHandCombination, potSizeInBBThird, flushDrawOnFlop, straightDrawOnFlop); if(n > max) { max = n; j = i; } } decideMove(max, j); } public void findBestMoveOnTurn() { int max = Integer.MIN_VALUE; int n = 0; int j = 0; for(int i = 0; i < 3; i++) { n = getSimilarSituationAverageOnTurn( i, turnCombination, bbThird, wasRaisedBySomeoneElse, highestTurnCardIsInHandCombination, potSizeInBBThird, flushDrawOnTurn, straightDrawOnTurn); if(n > max) { max = n; j = i; } } decideMove(max, j); } public void findBestMoveOnRiver() { int max = Integer.MIN_VALUE; int n = 0; int j = 0; for(int i = 0; i < 3; i++) { n = getSimilarSituationAverageOnRiver( i, riverCombination, bbThird, wasRaisedBySomeoneElse, highestRiverCardIsInHandCombination, potSizeInBBThird); if(n > max) { max = n; j = i; } } decideMove(max, j); } public int getSimilarSituationAveragePreFlop(int a, int b, int c, int d, int e, int f) { if(getSimilarButtonSituationAveragePreFlop(a, b, c, d, e, f) == Integer.MIN_VALUE) return 0; return getSimilarButtonSituationAveragePreFlop(a, b, c, d, e, f); } public int getSimilarButtonSituationAveragePreFlop(int a, int b, int c, int d, int e, int f) { if(getSimilarPotSituationAveragePreFlop(a,b,c,d,e,f) > Integer.MIN_VALUE) { return getSimilarPotSituationAveragePreFlop(a,b,c,d,e,f); }else if(getSimilarPotSituationAveragePreFlop(a,b,c,d,1 - e,f) > Integer.MIN_VALUE){ return getSimilarPotSituationAveragePreFlop(a,b,c,d,1 - e,f); } return Integer.MIN_VALUE; } public int getSimilarPotSituationAveragePreFlop(int a, int b, int c, int d, int e, int f) { for(int i = 0; i < 3; i++) { if(GameController.cD.getEntry(a,b,c,d,e,f+i) != null) return GameController.cD.getEntry(a,b,c,d,e,f+i).getRewardAverage(); if(GameController.cD.getEntry(a,b,c,d,e,f-i) != null) return GameController.cD.getEntry(a,b,c,d,e,f-i).getRewardAverage(); } return Integer.MIN_VALUE; } public int getSimilarSituationAverageOnFlop(int a, int b, int c, int d, int e, int f, int g, int h) { if(getSimilarPotSituationAverageOnFlop(a,b,c,d,e,f,g,h) == Integer.MIN_VALUE) return 0; return getSimilarPotSituationAverageOnFlop(a,b,c,d,e,f,g,h); } public int getSimilarPotSituationAverageOnFlop(int a, int b, int c, int d, int e, int f, int g, int h) { for(int i = 0; i < 3; i++) { if(getSimilarFlushDrawSituationOnFlop(a,b,c,d,e,f+i,g,h) > Integer.MIN_VALUE) return getSimilarFlushDrawSituationOnFlop(a,b,c,d,e,f,g+i,h); if(getSimilarFlushDrawSituationOnFlop(a,b,c,d,e,f-i,g,h) > Integer.MIN_VALUE) return getSimilarFlushDrawSituationOnFlop(a,b,c,d,e,f,g-i,h); } return Integer.MIN_VALUE; } public int getSimilarFlushDrawSituationOnFlop(int a, int b, int c, int d, int e, int f, int g, int h) { if(getSimilarStraightDrawSituationOnFlop(a,b,c,d,e,f,g,h) > Integer.MIN_VALUE) return getSimilarStraightDrawSituationOnFlop(a,b,c,d,e,f,g,h); else if(getSimilarStraightDrawSituationOnFlop(a,b,c,d,e,f,1-g,h) > Integer.MIN_VALUE) return getSimilarStraightDrawSituationOnFlop(a,b,c,d,e,f,1-g,1-h); return Integer.MIN_VALUE; } public int getSimilarStraightDrawSituationOnFlop(int a, int b, int c, int d, int e, int f, int g, int h) { if(GameController.cDF.getEntry(a, b, c, d, e, f, g, h) != null) return GameController.cDF.getEntry(a, b, c, d, e, f, g, h).getRewardAverage(); else if(GameController.cDF.getEntry(a, b, c, d, e, f, g,1- h) != null) return GameController.cDF.getEntry(a, b, c, d, e, f, g,1- h).getRewardAverage(); return Integer.MIN_VALUE; } public int getSimilarSituationAverageOnTurn(int a, int b, int c, int d, int e, int f, int g, int h) { if(getSimilarPotSituationAverageOnTurn(a,b,c,d,e,f,g,h) == Integer.MIN_VALUE) return 0; return getSimilarPotSituationAverageOnTurn(a,b,c,d,e,f,g,h); } public int getSimilarPotSituationAverageOnTurn(int a, int b, int c, int d, int e, int f, int g, int h) { for(int i = 0; i < 3; i++) { if(getSimilarFlushDrawSituationOnTurn(a,b,c,d,e,f+i,g,h) > Integer.MIN_VALUE) return getSimilarFlushDrawSituationOnTurn(a,b,c,d,e,f,g+i,h); if(getSimilarFlushDrawSituationOnTurn(a,b,c,d,e,f-i,g,h) > Integer.MIN_VALUE) return getSimilarFlushDrawSituationOnTurn(a,b,c,d,e,f,g-i,h); } return Integer.MIN_VALUE; } public int getSimilarFlushDrawSituationOnTurn(int a, int b, int c, int d, int e, int f, int g, int h) { if(getSimilarStraightDrawSituationOnTurn(a,b,c,d,e,f,g,h) > Integer.MIN_VALUE) return getSimilarStraightDrawSituationOnTurn(a,b,c,d,e,f,g,h); else if(getSimilarStraightDrawSituationOnTurn(a,b,c,d,e,f,1-g,h) > Integer.MIN_VALUE) return getSimilarStraightDrawSituationOnTurn(a,b,c,d,e,f,1-g,1-h); return Integer.MIN_VALUE; } public int getSimilarStraightDrawSituationOnTurn(int a, int b, int c, int d, int e, int f, int g, int h) { if(GameController.cDT.getEntry(a, b, c, d, e, f, g, h) != null) return GameController.cDT.getEntry(a, b, c, d, e, f, g, h).getRewardAverage(); else if(GameController.cDT.getEntry(a, b, c, d, e, f, g,1- h) != null) return GameController.cDT.getEntry(a, b, c, d, e, f, g,1- h).getRewardAverage(); return Integer.MIN_VALUE; } public int getSimilarSituationAverageOnRiver(int a, int b, int c, int d, int e, int f) { if(getSimilarPotSituationAverageOnRiver(a,b,c,d,e,f) == Integer.MIN_VALUE) return 0; return getSimilarPotSituationAverageOnRiver(a,b,c,d,e,f); } public int getSimilarPotSituationAverageOnRiver(int a, int b, int c, int d, int e, int f) { for(int i = 0; i < 3; i++) { if(GameController.cDR.getEntry(a, b, c, d, e, f+i) != null) return GameController.cDR.getEntry(a, b, c, d, e, f+i).getRewardAverage(); if(GameController.cDR.getEntry(a, b, c, d, e, f-i) != null) GameController.cDR.getEntry(a, b, c, d, e, f-i).getRewardAverage(); } return Integer.MIN_VALUE; } public void saveVar() { if(playerNum == 0) { card0 = GameController.cardDeck[5]; card1 = GameController.cardDeck[6]; } else if(playerNum == 1) { card0 = GameController.cardDeck[7]; card1 = GameController.cardDeck[8]; } else { card0 = GameController.cardDeck[9]; card1 = GameController.cardDeck[10]; } for(int i = 0; i < 3; i++) { flop[i] = GameController.cardDeck[i]; turn[i] = GameController.cardDeck[i]; river[i] = GameController.cardDeck[i]; } //System.out.println(card0 + " " + card1); turn[3] = GameController.cardDeck[3]; river[3] = GameController.cardDeck[3]; river[4] = GameController.cardDeck[4]; flopCombination = GameController.dsW.cardCombination(flop, card0, card1); turnCombination = GameController.dsW.cardCombination(turn, card0, card1); riverCombination = GameController.dsW.cardCombination(river, card0, card1); highestFlopCardIsInHandCombination = GameController.dsW.highestBoardCardIsInHandCombination(flop, card0, card1); highestTurnCardIsInHandCombination = GameController.dsW.highestBoardCardIsInHandCombination(turn, card0, card1); highestRiverCardIsInHandCombination = GameController.dsW.highestBoardCardIsInHandCombination(river, card0, card1); flushDrawOnFlop = DetermineWinner.isFlushDraw(card0, card1, flop); flushDrawOnTurn = DetermineWinner.isFlushDraw(card0, card1, turn); straightDrawOnFlop = DetermineWinner.isStraightDraw(card0, card1, flop); straightDrawOnTurn = DetermineWinner.isStraightDraw(card0, card1, turn); if(GameController.button == playerNum) hasButton = 1; else hasButton = 0; bbThird = (balance/GameController.blind)/3; potSizeInBBThird = GameController.mainPot + GameController.sidePot; for(int i = 0; i < 3; i++) { potSizeInBBThird += GameController.player[i].bet; } potSizeInBBThird = potSizeInBBThird/(GameController.blind*3); if(GameController.highestBet > bet) wasRaisedBySomeoneElse = 1; else wasRaisedBySomeoneElse = 0; } } <file_sep>/src/FlopCollectedData.java import java.util.HashMap; import java.util.Map; public class FlopCollectedData { private int action; private int cardCombination; private int playerBB; private int wasRaisedBySomeoneElse; private int highestBoardCardIsInHandCombination; private int potSize; private int flushDraw; private int straightDraw; static Map<FlopCollectedData, RewardEntry> map = new HashMap<FlopCollectedData, RewardEntry>(); public int getAction() { return action; } public int getcardCombination() { return cardCombination; } public int getPlayerBB() { return playerBB; } public int getWasRaisedBySomeoneElse() { return wasRaisedBySomeoneElse; } public int getHighestBoardCardIsInHandCombination() { return highestBoardCardIsInHandCombination; } public int getPotSizeAtFlop() { return potSize; } public int getFlushDraw() { return flushDraw; } public int getStraightDraw() { return straightDraw; } public FlopCollectedData(int a, int b, int c, int d, int e, int f, int g, int h){ this.action = a; this.cardCombination = b; this.playerBB = c; this.wasRaisedBySomeoneElse = d; this.highestBoardCardIsInHandCombination = e; this.potSize = f; this.flushDraw = g; this.straightDraw = h; } public FlopCollectedData() { } public void createEntry(int value, int a, int b, int c, int d, int e, int f, int g, int h){ try { RewardEntry rewEnt = map.get(new FlopCollectedData(a,b,c,d,e,f,g,h)); rewEnt.addEntry(value); map.put(new FlopCollectedData(a,b,c,d,e,f,g,h), rewEnt); }catch(Exception z) { map.put(new FlopCollectedData(a,b,c,d,e,f,g,h), new RewardEntry(value)); } } public RewardEntry getEntry(int a, int b, int c, int d, int e, int f, int g, int h){ RewardEntry mapValue = map.get(new FlopCollectedData(a,b,c,d,e,f,g,h)); return mapValue; } @Override public boolean equals(Object obj){ if (obj != null && obj instanceof FlopCollectedData){ FlopCollectedData dataObj = (FlopCollectedData) obj; boolean propertyA = action == dataObj.getAction(); boolean propertyB = cardCombination == dataObj.getcardCombination(); boolean propertyC = playerBB == dataObj.getPlayerBB(); boolean propertyD = wasRaisedBySomeoneElse == dataObj.getWasRaisedBySomeoneElse(); boolean propertyE = highestBoardCardIsInHandCombination == dataObj.getHighestBoardCardIsInHandCombination(); boolean propertyF = potSize == dataObj.getPotSizeAtFlop(); boolean propertyG = flushDraw == dataObj.getFlushDraw(); boolean propertyH = straightDraw == dataObj.getStraightDraw(); return propertyA && propertyB && propertyC && propertyD && propertyE && propertyF && propertyG && propertyH ; } return false ; } @Override public int hashCode(){ int hash = 17; hash = hash * 31 * action; hash = hash * 31 * cardCombination; hash = hash * 31 * playerBB; hash = hash * 31 * wasRaisedBySomeoneElse; hash = hash * 31 * highestBoardCardIsInHandCombination; hash = hash * 31 * potSize; hash = hash * 31 * flushDraw; hash = hash * 31 * straightDraw; return hash; } }
872bcfe5bef92ae630897461dd552e5aca77e4a0
[ "Java" ]
5
Java
robin7654/BA
c54ed3be50c6fc2c2b41de3e6ad2b138c70371a9
dfd53ce166077b2dcf0a2bf67a52f80b4a472990
refs/heads/master
<repo_name>Claudiagari/calculadora-react<file_sep>/README.md # Calculadora Realizar una calculadora utilizando React y Redux. ## Desarrollo * Usando create-app de React se implementó el repositorio. * Se creo los componentes necesarios y el diseño. * Se fijo el state inicial ,las actions y funciones. * Una vez definido se paso el evento con las actions a los diferentes botones. ## Vista ![calculadora](https://user-images.githubusercontent.com/32285734/37260588-27a71dba-2563-11e8-8d7e-5ba6a21813a4.jpg) ## Tecnologias Usadas * React. * Redux. * Javascript. * CSS3. * HTML5. ## Integrantes - **<NAME>** - [@aurorex](https://github.com/aurorex) - **<NAME>** - [@valeriavelles](https://github.com/valeriavalles) - **<NAME>** - [@carlacentenor](https://github.com/carlacentenor) - **<NAME>** - [@claudiagari](https://github.com/claudiagari) <file_sep>/src/actions/calculate.js // Obtener números export const actionNumber1 = { type: 'NUMBER_1' }; export const actionNumber2 = { type: 'NUMBER_2' }; export const actionNumber3 = { type: 'NUMBER_3' }; export const actionNumber4 = { type: 'NUMBER_4' }; export const actionNumber5 = { type: 'NUMBER_5' }; export const actionNumber6 = { type: 'NUMBER_6' }; export const actionNumber7 = { type: 'NUMBER_7' }; export const actionNumber8 = { type: 'NUMBER_8' }; export const actionNumber9 = { type: 'NUMBER_9' }; export const actionNumber0 = { type: 'NUMBER_0' }; // Obtener operadores export const actionSum = { type: 'SUM' }; export const actionRest = { type: 'REST' }; export const actionMulti = { type: 'MULTI' }; export const actionDivi = { type: 'DIVI' }; export const actionEqual = { type: 'EQUAL' }; export const actionReset = { type: 'RESET' }; export const actionDelete = { type: 'DELETE' }; export const actionPoint = { type: 'POINT' };<file_sep>/src/reducers/index.js import {createStore } from 'redux'; // Estados Iniciales const initialState = { number : 0, numberCalculator :0, operator:null, historial:[], }; // Reducer const reducer = (state = initialState,action) =>{ console.log(action.type , state.number); switch (action.type){ case 'NUMBER_1' : return { ...state , number :state.number+'1' } ; case 'NUMBER_2' : return { ...state , number :state.number+'2' }; case 'NUMBER_3' : return { ...state , number :state.number+'3' }; case 'NUMBER_4' : return { ...state , number :state.number+'4' }; case 'NUMBER_5' : return { ...state , number :state.number+'5' }; case 'NUMBER_6' : return { ...state , number :state.number+'6' }; case 'NUMBER_7' : return { ...state , number :state.number+'7' }; case 'NUMBER_8' : return { ...state , number :state.number+'8' }; case 'NUMBER_9' : return { ...state , number :state.number+'9' }; case 'NUMBER_0' : return { ...state , number :state.number+'0' }; case 'POINT' : return { ...state , number :state.number+'.' }; case 'SUM' : return { ...state,numberCalculator: state.number, number:0,operator:'+',historial:historial( parseFloat(state.number),state.historial) }; case 'REST' : return { ...state,numberCalculator: state.number, number:0,operator:'-',historial:historial( parseFloat(state.number),state.historial) }; case 'MULTI' : return { ...state,numberCalculator: state.number, number:0,operator:'*',historial:historial(parseFloat(state.number),state.historial) }; case 'DIVI' : return { ...state,numberCalculator: state.number, number:0,operator:'/',historial:historial(parseFloat(state.number),state.historial) }; case 'EQUAL' : return { ...state,number:opera(parseFloat(state.numberCalculator),parseFloat(state.number),state.operator) ,historial:historial(parseFloat(state.number),state.historial)}; case 'RESET' : return { ...state,number:0 }; case 'DELETE': return {...state,number:deleteNum(state.number)}; default : return state; } return state; } function opera(num1, num2, operator) { switch (operator) { case '+': return num1 + num2; case '-': return num1 - num2; case '*': return num1 * num2; case '/': if (num2 !== 0) { return num1 / num2; } else { return 0; } default: return num1; } } function historial(num, array) { let arrayHistorial = array; arrayHistorial.push(num); console.log(arrayHistorial); return arrayHistorial } function deleteNum(num) { let number = num.toString() if (number.length > 1) { let arrayNumber = Array.from(number); arrayNumber.splice(arrayNumber.length - 1, 1) let preNumber = arrayNumber.join('') return parseInt(preNumber) } else { return 0 } } const store = createStore(reducer); export default store;
0f762219bd6d4d1cfffdcd0befa5d7bbe9ae918b
[ "Markdown", "JavaScript" ]
3
Markdown
Claudiagari/calculadora-react
05ae60bdccd2c51bfb035304451bc9b9fbdaf2f6
e73bb1be3d08db0dfaeed02f4bac53a0bc8e4008
refs/heads/master
<file_sep>class Chassis: def logon(self, password:str): return "C_LOGON \"{0}\"".format(password) def logoff(self): return "C_LOGOFF" def setOwner(self, name:str): truncated_name = (name[:6] + '..') if len(name) > 8 else name return "C_OWNER \"{0}\"".format(truncated_name) def getOwner(self): return "C_OWNER ?" class ChassisOwner: def __init__(self, response:str): data = response.split() self._owner = data[1] @property def owner(self): return self._owner class Data: def __init__(self, data:list): self._first = data[0] self._second = data[1] self._thrid = data[2] @property def first(self): return self._first @property def second(self): return self._second @property def third(self): return self._thrid if __name__ == '__main__': respone = "C_OWNER \"xena\"" a = ChassisOwner(respone).owner print(a) <file_sep># L4-7 XENA SCRIPTING [Introduction](/Introduction.md) [Command Syntax](/Introduction.md#command-syntax) [Command Naming](/Introduction.md#command-naming) [Multi-User](/Introduction.md#multi-user) [L47 Port States](/Introduction.md#l47-port-states) [Connection Groups](/Introduction.md#connection-groups) [Data Types](/Introduction.md#data-types) [Chassis Commands](/ChassisCommands.md) <file_sep>## Chassis Commands The chassis commands deal with basic information about, and configuration of, the chassis itself (rather than its modules and test ports), as well as overall control of the scripting session. The chassis parameter names all have the form C_xxx and use neither a module index nor a port index. The following chassis commands are supported by the L47 chassis, and are all identical to the commands supported by the L23 products: --- ### `C_LOGON <password>` #### Description You log on to the chassis by setting the value of this parameter to the correct password for the chassis. All other commands will fail if the session has not been logged on. #### Summary set only, value type: S #### Parameters `<password>`: string, containing the correct password value. #### Example ``` --> C_LOGON "xena" <-- <OK> ``` --- ### `C_LOGOFF` #### Description Terminates the current scripting session. Courtesy only, the chassis will also handle disconnection at the TCP/IP level. #### Summary set only. #### Parameters None. #### Example ``` --> C_LOGOFF <-- <OK> ``` --- ### `C_OWNER <username>` #### Description Identify the owner of the scripting session. The name can be any short quoted string up to eight characters long. This name will be used when reserving ports prior to updating their configuration. There is no authentication of the users, and the chassis does not have any actual user accounts. Multiple concurrent connections may use the same owner name, but only one connection can have any particular resource reserved at any given time. Until an owner is specified the chassis configuration can only be read. Once specified, the session can reserve ports for that owner, and will inherit any existing reservations for that owner retained at the chassis. #### Summary set and get, value type: O #### Parameters `<username>`: string, containing the name of the owner of this session. #### Example ``` --> C_OWNER "John" <-- <OK> --> C_OWNER ? <-- C_OWNER "John" ``` --- ### `C_RESERVATION <action>` #### Description You set this parameter to reserve, release, or relinquish the chassis itself. The chassis must be reserved before any of the chassis-level parameters can be changed.The owner of the session must already have been specified. Reservation will fail if any modules or ports are reserved to other users. #### Summary set or get, value type: B #### Parameters `<action>`: coded byte, containing the operation to perform: RELEASE RESERVE RELINQUISH The reservation parameters are slightly asymmetric with respect to set/get. When querying for the current reservation state, the chassis will use these values: RELEASED RESERVED_BY_YOU RESERVED_BY_OTHER #### Example ``` --> C_RESERVATION RESERVE <-- <OK> --> C_RESERVATION ? <-- C_RESERVATION RESERVED_BY_YOU ``` --- ### `C_RESERVEDBY <username>` #### Description Identify the user who has the chassis reserved. The empty string if the chassis is not currently reserved. #### Summary get only, value type: O #### Parameters `<username>`: string, containing the name of the current owner of the chassis. #### Example ``` --> C_RESERVEDBY ? <-- C_RESERVEDBY "John"` ``` --- ### `C_DOWN <magic> <action>` #### Description Shuts down the chassis, and either restarts it in a clean state or leaves it powered off. #### Summary set only, value types: I, B #### Parameters `<magic>`: integer, must be the special value -1480937026. `<whattodo>`: coded byte, what to do after shutting chassis down: RESTART POWEROFF #### Example ``` --> C_DOWN -1480937026 RESTART ``` --- ### `C_MODEL <model>` #### Description Obtains the specific model of this Xena chassis. #### Summary get only, value type: S #### Parameters `<model>`: string, the Xena model designation for the chassis. #### Example ``` --> C_MODEL ? <-- C_MODEL "C1-M6SFP" ``` --- ### `C_SERIALNO <serialno>` #### Description Obtains the unique serial number of this particular Xena chassis. #### Summary get only, value type: I #### Parameters `<serialno>`: integer, the serial number of this chassis. #### Example ``` --> C_SERIALNO ? <-- C_SERIALNO 12345678 ``` --- ### `C_VERSIONNO <chassis_majorvers> <driver_vers>` #### Description Obtains the major version numbers for the chassis firmware and the Xena PCI driver installed on the chassis. #### Summary get only, value types: I, I #### Parameters `<chassis_majorvers>`: integer, the chassis firmware major version number. `<driver_vers>`: integer, the Xena PCI driver version number. #### Example ``` --> C_VERSIONNO ? <-- C_VERSIONNO 200 30 ``` --- ### `C_PORTCOUNTS <portcount> <portcount> ...` #### Description Obtains the number of ports in each module slot of the chassis, and indirectly the number of slots and modules. Note: CFP modules return the number 8 which is the maximum number of 10G ports, but the actual number of ports can be configured dynamically using the M_CFPCONFIG command. #### Summary get only, value types: B* #### Parameters `<portcoun>`: byte, the number of ports, typically 2 or 6, or 0 for an empty slot. #### Example ``` --> C_PORTCOUNTS ? <-- C_PORTCOUNTS 2 ``` --- ### `C_CONFIG` #### Description Multi-parameter query, obtaining all the settable parameters of the chassis. #### Summary get only. #### Parameters None #### Example ``` --> C_CONFIG ? <-- C_NAME ”Lab ABC” <-- C_COMMENT ”This chassis belongs to the XYZ project.” <-- C_PASSWORD ”<PASSWORD>” <-- C_IPADDRESS 192.168.1.200 255.255.255.0 192.168.1.1 ``` --- ### `C_INFO` #### Description Multi-parameter query, obtaining all the non-settable parameters for the chassis. #### Summary get only. #### Parameters None #### Example ``` --> C_INFO ? <-- C_RESERVATION RESERVED_BY_YOU <-- C_RESERVEDBY ”HH” <-- C_PORTCOUNTS 2 <-- C_MODEL ”C1-M2SFP+” <-- C_SERIALNO 12345678 <-- C_VERSIONNO 200 30 ``` --- ### `C_NAME <chassisname>` #### Description The name of the chassis, as it appears at various places in the Manager user-interface. The name is also used to distinguish the various chassis contained within a testbed and in files containing the configuration for an entire test-case. #### Summary set and get, value type: S #### Parameters None #### Example ``` --> C_NAME "Lab ABC" <-- <OK> --> C_NAME ? <-- C_NAME "Lab ABC" ``` --- ### `C_COMMENT <comment>` #### Description The description of the chassis. #### Summary set and get, value type: S #### Parameters `<comment>`: string, containing the description of the chassis. #### Example ``` --> C_COMMENT "This chassis belongs to the XYZ project." <-- <OK> --> C_COMMENT ? <-- C_COMMENT "This chassis belongs to the XYZ project." ``` --- ### `C_PASSWORD <password>` #### Description The password of the chassis, which must be provided when logging on to the chassis. #### Summary set and get, value type: S #### Parameters `<password>`: string, containing the password for the chassis. #### Example ``` --> C_PASSWORD "<PASSWORD>" <-- <OK> --> C_PASSWORD ? <-- C_PASSWORD "<PASSWORD>" ``` --- ### `C_TIMEOUT <seconds>` #### Description The maximum number of idle seconds allowed before the connection is timed out by the tester #### Summary set and get, value type: I #### Parameters `<seconds>`: integer, the maximum idle interval, default is 130 seconds. #### Example ``` --> C_TIMEOUT 999 <-- <OK> --> C_TIMEOUT ? <-- C_TIMEOUT 999 ``` --- <file_sep># L4-7 XENA SCRIPTING ## Introduction The Xena L47 Scripting Commands are very similar to the L23 Scripting Commands. In a few cases the commands are identical, however many new L47 specific commands have been created. Commands are logically grouped in a hierarchy. At the top level we have a _Chassis_. Currently there are two different L47 Chassis: **XenaAppliance** and **XenaScale**. For XenaAppliance and XenaScale, the entire chassis is considered one L47 _Module_, however in the future a chassis may have several L47 modules. A L47 _Module_ have several _Ports_ (currently between 1 and 12). Like on L23, each _Port_ must be reserved before it can be configured and traffic can be started, allowing multiple users to work with the L47 product at the same time. In addition to _Ports_ a L47 _Module_ contains a number of _Packet Engines_ (PE), which generates and handles the TCP traffic. As default each port is allocated one PE, however more PEs can be allocated to a Port increasing the performance on that port. Packet Engines are a shared resource between the Ports on a module. Currently Xena Appliance contains 5 PEs and Xena Scale contains 2 groups of 14 PEs. The Stream concept in L23 scripting has been replaced by _Connection Groups_ (CG). A CG specifies a number of concurrent TCP connections or UDP streams (2 million per PE). Several CGs can be configured on a Port (currently up to 200). A CG has a configured _Load Profile_, which defines the ramp-up start time along with the durations of the ramp-up, steady-state and ramp-down periods. A CG is configured with an _Application Type_ and an _Application Scenario_. The Application Type defines the type of data transmitted by the TCP connections, and the Application Scenario defines the data flow between _Servers_ and _Clients_. By combining several CGs on a Port, it is possible to create a mixture of different traffic types and scenarios, and to create complex resulting load profiles. L47 Scripting Commands are divided into groups, that deals with the different resources and aspects of the L47 products: In terms of command syntax, there are four groups of scripting commands: * [Chassis Commands](/ChassisCommands.md) * Module Commands * Port Commands * Connection Group Commands However, to make it easier to get an overview of all the scripting commands, some of the module, port and connection group commands are separated in a number of other groups in this document. * Packet Engine Commands * Traffic Command * Statistics Commands * Capture Commands ## Command Syntax A Scripting Command can either be a get or a set command. ### Get Command Syntax The general format of a get command is: ``` <addressing> <command_name> <index> ? ``` where <addressing> specifies module and port numbers as appropriate and <index> specifies for example connection group number. The response to a get command has the format: ``` <addressing> <command_name> <index> <parameters> ``` where `<parameters>` are the values of the parameters requested by the get command Example: ``` --> 1/0 P4_FW_VER ? <-- 1/0 P4_FW_VER 4 22 ``` ### Set Command Syntax The general format of a set command is: ``` <addressing> <command_name> <index> <parameters> ``` where `<parameters>` are the values of the parameters set by the command. A few set commands has no parameters as they are action commands rather than commands to configure parameters (e.g. a command to clear counters). The response to a set command has the format: ``` <status> ``` where `<status>` can have the following values. ``` <OK> ok <NOCONNECTIONS> chassis has no available user connections <NOTLOGGEDON> no command can be submitted before logon <NOTRESERVED> parameter cannot be set because resource not reserved <NOTWRITABLE> parameter is read-only <NOTREADABLE> parameter is write-only <NOTVALID> operation not valid in current state <BADCOMMAND> invalid command <BADPARAMETER> invalid parameter code <BADMODULE> invalid module index <BADPORT> invalid port index <BADINDEX> invalid connection group index <BADSIZE> invalid size of data <BADVALUE> invalid value of data <FAILED> failed to perform operation <MEMORYFAILURE> failed to allocate memory <NOLICPE> no free PE licence <NOLICPORT> no free port licence ``` Example: ``` --> 1/0 P4_CLEAR <-- <OK> ``` ## Command Naming ### Chassis commands Chassis commands has the format: `C_XXX` Examples: ``` C_LOGON "xena" C_OWNER ? ``` ### Module commands Module commands has the format `<module> M_XXX` or `<module> M4_XXX` for L47 specific module commands, where <module> specifies the module number. Examples: ``` 0 M_SERIALNO ? 0 M4_SYSTEMID ? ``` ### Port commands Port commands have the format: `<module>/<port> P_XXX` or `<module>/<port> P4_XXX` for L47 specific module commands, where <module> specifies the module number and <port> specifies the port number. Examples: ``` 1/0 P_SPEED ? 1/0 P4_TRAFFIC on ``` ### Connection Group commands Connection Group commands have the format `<module>/<port> P4G_XXX [index]` where <module> specifies the module number, <port> specifies the port number and index specifies the connection group number. Examples: ``` 1/0 P4G_CREATE [0] 1/0 P4G_CLIENT_RANGE [0] ? ``` ### Packet Engine commands Packet Engine commands is a collection of port and module commands, and have the format `<module> M4E_XXX` or `<module>/<port> P4E_XXX` where <module> specifies the module number and <port> specifies the port number. Examples: ``` 0 M4E_MODE ? 1/0 P4E_ALLOCATE 2 ``` ## Multi-User Multiple users can operate on the Chassis simultaneously. To ensure smooth operation, access restrictions apply. All parameters can be read by anyone as long as that user has logged on using the C_LOGON command. In order to set parameters on a Chassis, Module, or Port, the corresponding resource must be reserved by that user. Users are identified by name, which is configured using the C_OWNER command. Reservation state query and reservations can be done using the C/M/P_RESERVATION and C/M/P_RESERVEDBY commands. Example: Logging on to a chassis and reserving port 0 and 1 is done by the following commands. ``` C_LOGON "xena" C_OWNER "JohnDoe" 1/0 P_RESERVATION reserve 1/1 P_RESERVATION reserve ``` Resources reserved by a user can be released by the same user using the command ``` 1/0 P_RESERVATION release ``` Resources can also be released by other users using the command ``` 1/0 P_RESERVATION relinquish ``` A description of what a resource is used for can be given using `C_COMMENT` or `P_COMMENT`. Example: ``` C_COMMENT "Live demo chassis. Resources can be relinquished without warning." ``` or ``` 1/0 P_COMMENT "Port used until 5pm sat oct. 5, after which it can be relinquished." 1/1 P_COMMENT "Port used until 5pm sat oct. 5, after which it can be relinquished." ``` ## L47 Port States The Xena L47 test execution engine has seven states: _OFF_, _PREPARE_, _PREPARE_RDY_, _PRERUN_, _PRERUN_RDY_, _RUNNING_ and _STOPPED_. Traffic is generated in the prerun and running states only, and configuration of parameters is only valid in state off except for a few runtime options. Port traffic commands can be given with `P4_TRAFFIC` and port state queried by `P4_STATE`. ![Image of Yaktocat](https://github.com/hyuxenanetworks/l47-api/blob/master/L47PortStateDiagram.png) ### OFF Default state. Entered from STOPPED or PREPARE on `P4_TRAFFIC OFF` command. This is the only state that allows configuration commands. `P4_RESET` is also considered a configuration command. Upon entering off state, some internal "house cleaning" is done. For example: freeing TCP Connections, clearing test specific counters etc. ### PREPARE This state is entered from state OFF on `P4_TRAFFIC OFF` command. Here internal data structures relevant for the test configuration are created. When done the state changes to PREPARE_RDY or PREPARE_FAIL and, a `P4_STATE PREPARE_RDY` or `P4_STATE PREPARE_FAIL` notification is sent to all users logged on to the chassis. ### PREPARE_RDY Entered automatically after activities in prepare have completed successfully. ### PREPARE_FAIL Entered automatically from prepare, if an error occurs. An error could for example be failure to load a configured replay file. ### PRERUN Entered from prepare_ready on `P4_TRAFFIC PRERUN` command. If enabled, this is where ARP and NDP requests are sent. When done the state changes to PREPARE_RDY and a `P4_TRAFFIC PREPARE_RDY` notification is sent to all users logged on to the chassis. ### PRERUN_RDY Entered automatically after activities in prerun has completed. ### RUNNING Entered either from PREPARE_RDY or PRERUN_RDY on `P4_TRAFFIC ON` command. This is where TCP connections/UDP streams are established/created, payload is generated and connections are closed again. ### STOPPING Entered from RUNNING, PRERUN_RDY or PRERUN on `P4_TRAFFIC STOP` command. Stops Rx/Tx traffic. In STOPPING state, post-test data are calculated and captured packets are saved to files. ### STOPPED Entered automatically after activities in STOPPING are complete. This is where you can read post-test statistics and extract captured packets. ## Connection Groups A Connection Group (CG) is the basic building block when creating L47 traffic. A Connection Group consists of a number of TCP connections - between one and millions. The CG has a role, which is either client or server. In order to create TCP connections between two ports on a L47 Chassis, two matching CGs must be configured - one on each port - one configured as client and the other configured as server. The number of connections in a CG, is defined by the server range and the client range. A server/client range is a number of TCP connection endpoints defined by a number of IP addresses and a number of TCP ports. A server/client range is configured by specifying a start IP address, a number of IP addresses, a start TCP port and a number of TCP addresses. The number of clients are the number of client IP addresses times the number of client TCP ports, and the same goes for the number of servers. The number of TCP connections in a CG is the number of clients times the number of servers, that is TCP connections are created from all clients in the CG to all servers in the CG. Example: A Connection Group containing 100 clients on port 0 and 10 servers on port 1 can be configured the following way: ``` 1/0 P4G_CREATE [0] 1/1 P4G_CREATE [0] 1/0 P4G_ROLE [0] CLIENT 1/1 P4G_ROLE [0] SERVER 1/0 P4G_CLIENT_RANGE [0] 10.0.1.1 10 5000 10 1/0 P4G_SERVER_RANGE [0] 10.0.2.1 10 80 1 1/1 P4G_CLIENT_RANGE [0] 10.0.1.1 10 5000 10 1/1 P4G_SERVER_RANGE [0] 10.0.2.1 10 80 1 ``` **NOTE: Connection Group index must start from 0.** Now Port 0 contains 100 clients - 10 different TCP ports on 10 different IP addresses, and Port 1 contains 10 servers - 1 TCP port on 10 different IP addresses. When starting traffic on Port 0 and 1, 1000 TCP connections will be established - from all clients to all servers. **NOTE: When configuring a CG, both client AND server range must be configured on both CGs - that is, the server CG must also know the client range and vice versa.** The Connection Group must be configured with a Load Profile, which is an envelope over the TCP connections lifetime. The connections in a connection group goes through three phases. The Load Profile defines a start time and a duration of each of these phases. During the ramp-up phase connections are established at a rate defined by the number of connections divided by the ramp-up duration. During the steady-state phase connections may transmit and receive payload data, depending on the configuration of test application and test scenario for the CG. During the ramp-down phase connections are closed at a rate defined by the number of connections divided by the ramp-up duration, if they were not already closed as a result of the traffic scenario configured. Example: The 1000 connections configured above will be ramped up in 1 second - starting immediately - will live for 10 seconds, and will be ramped down in 2 seconds with the following configuration: ``` 1/0 P4G_LP_TIME_SCALE [0] SECONDS 1/1 P4G_LP_TIME_SCALE [0] SECONDS 1/0 P4G_LP_SHAPE [0] 0 1 10 2 1/1 P4G_LP_SHAPE [0] 0 1 10 2 ``` **NOTE: Just like client and server range, both the client and server CG must be configured with the Load Profile.** Next the CG must be configured with a test application, which defines what kind of traffic is transported in the TCP payload. Currently there are two kinds of test applications: NONE, which means that no payload is sent on the TCP connections. This test application is suitable for a test, where the only purpose is to measure TCP connection open and close rates. RAW, which means that the TCP connections transmits and receives user defined raw data. The contents of the raw TCP payload can be configured using P4G_RAW_PAYLOAD command. Raw TCP payload can also be specified as random and incrementing data. Using test application RAW, the CG must also be configured with a test scenario, which defines the data flow between the TCP client and server. Currently the following test scenarios can be configured: Download, upload, both and echo. Example: The Connection Group defined above is configured to transmit random payload data from the servers to the clients after the clients have transmitted (and the servers received) a download request, with the following commands: ``` 1/0 P4G_TEST_APPLICATION [0] RAW 1/1 P4G_TEST_APPLICATION [0] RAW 1/0 P4G_RAW_TEST_SCENARIO [0] DOWNLOAD 1/1 P4G_RAW_TEST_SCENARIO [0] DOWNLOAD 1/0 P4G_RAW_HAS_DOWNLOAD_REQ [0] YES 1/1 P4G_RAW_HAS_DOWNLOAD_REQ [0] YES 1/0 P4G_RAW_PAYLOAD_TYPE [0] RANDOM 1/1 P4G_RAW_PAYLOAD_TYPE [0] RANDOM ``` By combining several Connection Groups on a port, it is possible to create more complex traffic scenarios and more complex Load Profile shapes than the individual Connection Group allows. Examples of combinations of CGs can be found in the Scripting Examples section. ## Data Types * Integer (I): decimal integer, in the 32-bit range, e.g. 1234567. * Long (L): decimal integer, in the 64-bit range, e.g. 123456789123. * Byte (B): decimal integer, in the 8-bit range, e.g. 123. * Hex (H): two hexadecimal digits prefixed by 0x, e.g. 0xF7. * String (S): printable 7-bit ASCII characters enclosed in ", e.g. "A string". Characters with values outside the 32-126 range and the " character itself are specified by their decimal value, outside the quotation marks and separated by commas, e.g.: "A line",13,10,"and the next line". * Owner (O): a short string used to identify an owner, used for reservation. * Address (A): a dot-separated IP address, e.g. 192.168.1.200.
669c30b46fefd8b20f3457c34263bb2e4d0d2adc
[ "Markdown", "Python" ]
4
Python
hyuxenanetworks/l47-api
d2287b1b1d499b89c42d15e6e244125d3d7c407d
20948f6bafaafaa4c254362ed36917135d3ac70e
refs/heads/master
<file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\plan; use hiqdev\DataMapper\Attribute\JsonAttribute; class PlanReadModelAttribution extends PlanAttribution { public function attributes() { return array_merge(parent::attributes(), [ 'data' => JsonAttribute::class, ]); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\target\ChangePlan\Strategy; use DateTimeImmutable; use hiqdev\php\billing\Exception\ConstraintException; use hiqdev\php\billing\sale\SaleInterface; final class OncePerMonthPlanChangeStrategy implements PlanChangeStrategyInterface { /** * {@inheritdoc} * * Prevents plan change in the current month. */ public function ensureSaleCanBeClosedForChangeAtTime(SaleInterface $activeSale, DateTimeImmutable $desiredCloseTime): void { if (($closeTime = $activeSale->getCloseTime()) !== null) { $saleCloseMonth = $closeTime->modify('first day of this month midnight'); if ($saleCloseMonth->format('Y-m-d') === $desiredCloseTime->format('Y-m-d')) { // If sale is closed at the first day of month, then the whole month is available $nextPeriodStart = $saleCloseMonth; } else { // Otherwise - next month $nextPeriodStart = $saleCloseMonth->modify('next month'); } } else { $nextPeriodStart = $activeSale->getTime()->modify('first day of next month midnight'); } if ($desiredCloseTime < $nextPeriodStart) { throw new ConstraintException(sprintf( 'Plan can not be changed earlier than %s', $nextPeriodStart->format(DATE_ATOM) )); } $desiredCloseMonth = $desiredCloseTime->modify('first day of this month midnight'); if ($desiredCloseTime > $desiredCloseMonth) { throw new ConstraintException(sprintf( 'Plan change in the middle of month is prohibited, as there will be multiple active sales in the same month. ' . 'Either change plan at %s in this month, or change it next month at %s.', $desiredCloseMonth->format(DATE_ATOM), $desiredCloseMonth->modify('next month')->format(DATE_ATOM) )); } } public function calculateTimeInPreviousSalePeriod(SaleInterface $activeSale, DateTimeImmutable $desiredCloseTime): DateTimeImmutable { return $desiredCloseTime->modify('first day of previous month midnight'); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\target; use hiqdev\php\billing\customer\CustomerInterface; use hiqdev\php\billing\target\Target; /** * Class RemoteTarget. */ class RemoteTarget extends Target { /** * @var CustomerInterface */ public $customer; /** * @var string */ public $remoteid; public function getCustomer(): ?CustomerInterface { return $this->customer; } public function getRemoteId(): ?string { return $this->remoteid; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature\Purchase; use hiapi\Core\Endpoint\BuilderFactory; use hiapi\Core\Endpoint\Endpoint; use hiapi\Core\Endpoint\EndpointBuilder; use hiapi\endpoints\Module\Multitenant\Tenant; use hiqdev\billing\hiapi\customer\CustomerLoader; use hiqdev\billing\hiapi\feature\Feature; use hiqdev\billing\hiapi\target\TargetLoader; use hiqdev\billing\hiapi\tools\PerformBillingMiddleware; final class Builder { public function __invoke(BuilderFactory $build): Endpoint { return $this->create($build)->build(); } public function create(BuilderFactory $build): EndpointBuilder { return $build->endpoint(self::class) ->description('Purchase a feature') ->exportTo(Tenant::ALL) ->take(Command::class) ->middlewares( CustomerLoader::class, [ '__class' => TargetLoader::class, 'isRequired' => true, ], [ '__class' => PerformBillingMiddleware::class, 'checkCredit' => false, ], $build->call(Action::class) ) ->return(Feature::class); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\charge; use hiqdev\billing\hiapi\plan\GroupingPlan; use hiqdev\billing\hiapi\type\TypeSemantics; use hiqdev\php\billing\charge\ChargeInterface; use hiqdev\php\billing\target\TargetInterface; use hiqdev\php\billing\type\TypeInterface; use hiqdev\php\units\Quantity; use hiqdev\php\units\QuantityInterface; /** * @author <NAME> <<EMAIL>> */ class Generalizer extends \hiqdev\php\billing\charge\Generalizer { /** * @var TypeSemantics */ private $typeSemantics; public function __construct(TypeSemantics $typeSemantics) { $this->typeSemantics = $typeSemantics; } public function generalizeTime(ChargeInterface $charge): \DateTimeImmutable { $time = $charge->getAction()->getTime(); if ($this->typeSemantics->isOncePerMonth($charge->getType())) { $time = $time->modify('first day of this month midnight'); } return $time; } public function generalizeType(ChargeInterface $charge): TypeInterface { if ($this->typeSemantics->isDeposit($charge->getType())) { return $charge->getType(); } if ($charge->getParent() !== null) { $chargeType = $charge->getParent()->getPrice()->getType(); } else { $chargeType = $charge->getPrice()->getType(); } if ($this->typeSemantics->isSwapToMonthlyAllowed($chargeType)) { return $this->typeSemantics->createMonthlyType(); } return $chargeType; } public function generalizeQuantity(ChargeInterface $charge): QuantityInterface { $action = $charge->getAction(); if ($action->getSale() !== null && $this->typeSemantics->isMonthly($action->getType())) { $actionMonth = $action->getTime()->modify('first day of this month 00:00'); $saleMonth = $action->getSale()->getTime()->modify('first day of this month 00:00'); if ($saleMonth > $actionMonth) { $amount = 0; } elseif ($actionMonth > $saleMonth) { $amount = 1; } else { $saleDay = $action->getSale()->getTime()->format('d'); $daysInMonth = $action->getSale()->getTime()->format('t'); $amount = 1 - (($saleDay - 1) / $daysInMonth); } return Quantity::create('items', $amount); } return parent::generalizeQuantity($charge); } public function generalizeTarget(ChargeInterface $charge): TargetInterface { $plan = $charge->getPrice()->getPlan(); if ($plan instanceof GroupingPlan) { return $plan->convertToTarget(); } return $this->moreGeneral($charge->getAction()->getTarget(), $charge->getPrice()->getTarget()); /* Sorry, to be removed later, older variants * 1: if (in_array($charge->getTarget()->getType(), ['certificate', 'domain'], TRUE)) { $priceTarget = $charge->getPrice()->getTarget(); if ($priceTarget->getId()) { return $priceTarget; } } return parent::generalizeTarget($charge); * 2: return $priceTarget->getId() ? $priceTarget : new Target($charge->getSale()->getPlan()->getId(), 'plan'); */ } public function moreGeneral(TargetInterface $first, TargetInterface $other) { return $this->isMoreGeneral($first, $other) || !$other->hasId() ? $first : $other; } public function specializeTarget(TargetInterface $first, TargetInterface $other): TargetInterface { return $this->isMoreGeneral($first, $other) || !$first->hasId() ? $other : $first; } public function isMoreGeneral(TargetInterface $first, TargetInterface $other) { $i = 0; $order = [ 'domain' => ++$i, 'zone' => ++$i, 'certificate' => ++$i, 'type' => ++$i, 'part' => ++$i, 'server' => ++$i, 'device' => $i, 'tariff' => ++$i, 'ref' => ++$i, '' => ++$i, ]; $lhs = $order[(string) $first->getType()] ?? 0; $rhs = $order[(string) $other->getType()] ?? 0; return $lhs > $rhs; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\plan; use hiqdev\billing\mrdp\Target\Tariff\TariffTarget; use hiqdev\php\billing\plan\Plan; use hiqdev\php\billing\target\TargetInterface; class GroupingPlan extends Plan { public function convertToTarget(): TargetInterface { return new TariffTarget($this->getId(), 'tariff', $this->getName()); } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\target\ChangePlan; use DateTimeImmutable; use hiapi\commands\BaseCommand; use hiapi\validators\IdValidator; use hiapi\validators\UsernameValidator; use hiqdev\DataMapper\Validator\DateTimeValidator; use hiqdev\php\billing\customer\Customer; use hiqdev\php\billing\plan\PlanInterface; use hiqdev\php\billing\target\TargetInterface; class Command extends BaseCommand { public $customer_username; public $customer_id; public ?Customer $customer = null; public $plan_id; public $plan_name; public $plan_seller; public ?PlanInterface $plan; public $name; public $type; /** * @var string ID of the service instance in the service provider's subsystem, * that uniquely identifies the object or service, being sold. */ public $remoteid; public ?TargetInterface $target; /** @var DateTimeImmutable */ public $time; /** * @var ?DateTimeImmutable time, when the tariff plan change was requested. * Optional, is used to process events, accumulated in the message broker. * Requires higher permissions to be used. */ public $wall_time; /** * @var bool whether to skip the target check belonging to the customer. */ private bool $checkBelonging = true; public function rules(): array { return [ [['plan_name'], 'trim'], [['plan_seller'], UsernameValidator::class], [['plan_id'], IdValidator::class], [['customer_username'], 'trim'], [['customer_username'], UsernameValidator::class], [['customer_id'], IdValidator::class], [['name'], 'trim'], [['type'], 'trim'], [['type'], 'required'], [['remoteid'], 'trim'], [['time'], DateTimeValidator::class], [['wall_time'], DateTimeValidator::class], ]; } public function checkBelonging(): bool { return $this->checkBelonging; } public function skipCheckBelonging(): void { $this->checkBelonging = false; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\price; use hiapi\jsonApi\AttributionBasedCollectionDocument; class PricesCollectionDocument extends AttributionBasedCollectionDocument { } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\charge; use hiqdev\billing\hiapi\Hydrator\Strategy\MoneyStrategy; use function count; use function is_countable; use hiqdev\php\billing\action\Action; use hiqdev\php\billing\bill\Bill; use hiqdev\php\billing\charge\Charge; use hiqdev\php\billing\charge\ChargeInterface; use hiqdev\php\billing\charge\ChargeState; use hiqdev\php\billing\price\PriceInterface; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\type\Type; use hiqdev\php\units\Quantity; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; use Money\Money; /** * Charge Hydrator. * * @author <NAME> <<EMAIL>> */ class ChargeHydrator extends GeneratedHydrator { public function __construct() { $this->addStrategy('sum', new MoneyStrategy()); } /** {@inheritdoc} */ public function hydrate(array $data, $object): object { $data['type'] = $this->hydrator->create($data['type'], Type::class); $data['target'] = $this->hydrator->create($data['target'], Target::class); $data['action'] = $this->hydrator->create($data['action'], Action::class); $data['usage'] = $this->hydrator->create($data['usage'], Quantity::class); $data['sum'] = $this->getStrategy('sum')->hydrate($data['sum'], null); if (isset($data['price'])) { $data['price'] = $this->hydrator->create($data['price'], PriceInterface::class); } if (isset($data['bill'])) { if ((is_countable($data['bill']) ? count($data['bill']) : 0) === 0) { unset($data['bill']); // If empty array or null } else if (is_array($data['bill']) && !isset($data['bill']['sum'])) { unset($data['bill']); // If array without a "sum" } else { $data['bill'] = $this->hydrator->create($data['bill'], Bill::class); } } if (isset($data['state'])) { $data['state'] = $this->hydrator->create($data['state'], ChargeState::class); } if (isset($data['parent'])) { if (!empty($data['parent']['sum'])) { // If relation is actually populated $data['parent'] = $this->hydrate($data['parent'], $this->createEmptyInstance(ChargeInterface::class)); } else { unset($data['parent']); } } return parent::hydrate($data, $object); } /** * {@inheritdoc} * @param array */ public function extract($object): array { $result = array_filter([ 'id' => $object->getId(), 'type' => $this->hydrator->extract($object->getType()), 'target' => $this->hydrator->extract($object->getTarget()), 'action' => $this->hydrator->extract($object->getAction()), 'price' => $object->getPrice() ? $this->hydrator->extract($object->getPrice()) : null, 'usage' => $this->hydrator->extract($object->getUsage()), 'sum' => $this->getStrategy('sum')->extract($object->getSum()), 'bill' => $object->getBill() ? $this->hydrator->extract($object->getBill()) : null, 'state' => $object->getState() ? $this->hydrator->extract($object->getState()) : null, 'comment' => $object->getComment(), ], static function ($value): bool { return $value !== null; }, ARRAY_FILTER_USE_BOTH); return $result; } /** * @throws \ReflectionException * @return object */ public function createEmptyInstance(string $className, array $data = []): object { return parent::createEmptyInstance(Charge::class, $data); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\target\Create; use hiapi\Core\Endpoint\BuilderFactory; use hiapi\Core\Endpoint\Endpoint; use hiapi\Core\Endpoint\EndpointBuilder; use hiapi\endpoints\Module\Multitenant\Tenant; use hiqdev\billing\hiapi\customer\CustomerLoader; use hiqdev\php\billing\target\Target; final class BulkBuilder { public function __invoke(BuilderFactory $build): Endpoint { return $this->create($build)->build(); } public function create(BuilderFactory $build): EndpointBuilder { return $build->endpoint(self::class) ->description('Creates a set of Targets') ->exportTo(Tenant::ALL) ->take($build->many(Command::class)) ->checkPermission('plan.read') ->middlewares( $build->repeat(CustomerLoader::class), $build->repeat(Action::class) ) ->return($build->many(Target::class)); } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\target\ChangePlan; use DateTimeImmutable; use hiapi\exceptions\NotAuthorizedException; use hiapi\legacy\lib\billing\plan\Forker\PlanForkerInterface; use hiqdev\billing\hiapi\target\ChangePlan\Strategy\PlanChangeStrategyProviderInterface; use hiqdev\billing\hiapi\tools\PermissionCheckerInterface; use hiqdev\billing\mrdp\Sale\HistoryAndFutureSaleRepository; use hiqdev\DataMapper\Query\Specification; use hiqdev\DataMapper\Repository\ConnectionInterface; use hiqdev\php\billing\customer\Customer; use hiqdev\php\billing\customer\CustomerInterface; use hiqdev\php\billing\Exception\ConstraintException; use hiqdev\php\billing\Exception\InvariantException; use hiqdev\php\billing\Exception\RuntimeException; use hiqdev\php\billing\plan\PlanInterface; use hiqdev\php\billing\sale\Sale; use hiqdev\php\billing\sale\SaleInterface; use hiqdev\php\billing\target\TargetInterface; use hiqdev\php\billing\target\TargetRepositoryInterface; use hiqdev\php\billing\tools\CurrentDateTimeProviderInterface; use hiqdev\yii\DataMapper\Repository\Connection; use Psr\Log\LoggerInterface; use Throwable; use yii\web\User; /** * Schedules tariff plan change * * @author <NAME> <<EMAIL>> */ class Action { /** * @var ConnectionInterface|Connection */ private ConnectionInterface $connection; private TargetRepositoryInterface $targetRepo; private HistoryAndFutureSaleRepository $saleRepo; private PlanForkerInterface $planForker; private LoggerInterface $log; private DateTimeImmutable $currentTime; private User $user; private PlanChangeStrategyProviderInterface $strategyProvider; private Strategy\PlanChangeStrategyInterface $strategy; private PermissionCheckerInterface $permissionChecker; public function __construct( ConnectionInterface $connection, TargetRepositoryInterface $targetRepo, HistoryAndFutureSaleRepository $saleRepo, PlanForkerInterface $planForker, LoggerInterface $log, CurrentDateTimeProviderInterface $currentDateTimeProvider, User $user, PlanChangeStrategyProviderInterface $strategyProvider, PermissionCheckerInterface $permissionChecker, private ActiveSaleFinder $activeSaleFinder ) { $this->targetRepo = $targetRepo; $this->saleRepo = $saleRepo; $this->planForker = $planForker; $this->connection = $connection; $this->log = $log; $this->user = $user; $this->currentTime = $currentDateTimeProvider->dateTimeImmutable(); $this->strategyProvider = $strategyProvider; $this->permissionChecker = $permissionChecker; } public function __invoke(Command $command): TargetInterface { $this->permissionChecker->ensureCustomerCan($command->customer, 'have-goods'); $target = $this->getTarget($command); $customer = $command->customer; assert($customer !== null); assert($command->time instanceof DateTimeImmutable); $activeSale = $this->findActiveSale($target, $customer, $command->time); if ($activeSale === null) { throw new InvariantException('Plan can\'t be changed: there is no active sale for the given date'); } $this->strategy = $this->strategyProvider->getBySale($activeSale); $this->ensureNotHappeningInPast($command->time, $command->wall_time); $timeInPreviousSalePeriod = $this->strategy->calculateTimeInPreviousSalePeriod($activeSale, $command->time); $previousSale = $this->findActiveSale($target, $customer, $timeInPreviousSalePeriod); $target = $this->tryToCancelScheduledPlanChange($activeSale, $previousSale, $command->time, $command->plan); if ($target !== null) { return $target; } $target = $this->tryToChangeScheduledPlanChange($activeSale, $customer, $command->time, $command->plan); return $target ?? $this->schedulePlanChange($activeSale, $customer, $command->time, $command->plan); } public function withActiveSaleFinder(ActiveSaleFinder $activeSaleFinder): self { $new = clone $this; $new->activeSaleFinder = $activeSaleFinder; return $new; } /** * If there is a scheduled plan change from tariff "A" to "B" at some specific Date "D", * and we receive a new plan change request to change plan to "A" since Date "D", then: * * 1. Scheduled plan change should be cancelled * 2. Plan A closing should be cancelled * * @param SaleInterface $activeSale * @param null|SaleInterface $previousSale * @param DateTimeImmutable $effectiveDate * @param PlanInterface $newPlan * @return ?TargetInterface */ private function tryToCancelScheduledPlanChange( SaleInterface $activeSale, ?SaleInterface $previousSale, DateTimeImmutable $effectiveDate, PlanInterface $newPlan ): ?TargetInterface { if ($previousSale === null || $activeSale->getTime()->format(DATE_ATOM) !== $effectiveDate->format(DATE_ATOM) ) { return null; } if ($previousSale->getPlan()?->getId() !== $newPlan->getId()) { return null; } $previousSale->cancelClosing(); $this->replaceSaleInTransaction($activeSale, $previousSale, 'Failed to cancel scheduled plan change'); return $activeSale->getTarget(); } private function schedulePlanChange( SaleInterface $activeSale, CustomerInterface $customer, DateTimeImmutable $effectiveDate, PlanInterface $newPlan ): ?TargetInterface { $this->strategy->ensureSaleCanBeClosedForChangeAtTime($activeSale, $effectiveDate); $activeSale->close($effectiveDate); try { $sale = $this->connection->transaction(function () use ($activeSale, $customer, $newPlan, $effectiveDate) { $plan = $this->planForker->forkPlanIfRequired($newPlan, $activeSale->getCustomer()); $sale = new Sale(null, $activeSale->getTarget(), $customer, $plan, $effectiveDate); $this->saleRepo->save($activeSale); $this->saleRepo->save($sale); return $sale; }); return $sale->getTarget(); } catch (InvariantException $exception) { throw $exception; } catch (Throwable $exception) { $this->log->error('Failed to schedule a plan change', ['exception' => $exception]); throw new RuntimeException('Failed to schedule a plan change'); } } private function tryToChangeScheduledPlanChange( SaleInterface $activeSale, CustomerInterface $newCustomer, DateTimeImmutable $effectiveDate, ?PlanInterface $newPlan ): ?TargetInterface { $activeSaleTimeBiggerThenEffectiveTime = $activeSale->getTime()->format(DATE_ATOM) >= $effectiveDate->format(DATE_ATOM); $newPlanAndCustomerSameAsActiveSalePlanAndCustomer = $activeSale->getPlan()?->getId() === $newPlan?->getId() && $activeSale->getCustomer()->getId() === $newCustomer->getId(); if ($activeSaleTimeBiggerThenEffectiveTime || $newPlanAndCustomerSameAsActiveSalePlanAndCustomer) { $newSale = new Sale(null, $activeSale->getTarget(), $activeSale->getCustomer(), $newPlan, $effectiveDate); $this->replaceSaleInTransaction($activeSale, $newSale, 'Failed to change scheduled plan change'); return $newSale->getTarget(); } return null; } private function getTarget(Command $command): TargetInterface { $spec = (new Specification)->where([ 'type' => $command->type, 'name' => $command->name, ]); $target = $this->targetRepo->findOne($spec); if ($target === false) { throw new ConstraintException('Target must exist to change its plan'); } if ($command->checkBelonging()) { $this->ensureBelongs($target, $command->customer, $command->time); } return $target; } private function ensureBelongs(TargetInterface $target, CustomerInterface $customer, ?DateTimeImmutable $time = null): void { $sales = $this->saleRepo->findAllActive((new Specification)->where(array_filter([ 'seller-id' => $customer->getSeller()->getId(), 'target-id' => $target->getId(), ])), $time); if (!empty($sales) && reset($sales)->getCustomer()->getId() !== $customer->getId()) { throw new NotAuthorizedException('The target belongs to other client'); } } /** * @param TargetInterface $target * @param Customer $customer * @param DateTimeImmutable $time the sale is active at * @return SaleInterface|null */ private function findActiveSale(TargetInterface $target, Customer $customer, DateTimeImmutable $time): ?SaleInterface { return $this->activeSaleFinder->__invoke($target, $customer, $time); } private function truncateToMonth(DateTimeImmutable $time): DateTimeImmutable { return $time->modify('first day of this month midnight'); } private function ensureNotHappeningInPast(DateTimeImmutable $time, ?DateTimeImmutable $wallTime = null): void { if ($this->user->can('sale.update')) { $currentTime = $this->truncateToMonth($wallTime ?? $this->currentTime); } else { $currentTime = $this->truncateToMonth($this->currentTime); } if ($this->truncateToMonth($time) < $currentTime) { throw new ConstraintException('Plan can not be changed in past'); } } /** * @param SaleInterface $sale1 sale that will be destroyed * @param SaleInterface $sale2 sale the will put instead of it * @param string $errorMessage error message for the RuntimeException that describes an error * @throws InvariantException when save failed due to business limitations * @throws RuntimeException when save failed for other reasons */ private function replaceSaleInTransaction(SaleInterface $sale1, SaleInterface $sale2, string $errorMessage): void { try { $this->connection->transaction(function () use ($sale1, $sale2) { $this->saleRepo->delete($sale1); $this->saleRepo->save($sale2); }); } catch (InvariantException $exception) { throw $exception; } catch (Throwable $exception) { $this->log->error($errorMessage, ['exception' => $exception]); throw new RuntimeException($errorMessage); } } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\statement; use hiapi\jsonApi\AttributionBasedCollectionDocument; /** * @author <NAME> <<EMAIL>> */ class StatementsCollectionDocument extends AttributionBasedCollectionDocument { } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\target; use hiapi\jsonApi\AttributionBasedResource; class TargetResource extends AttributionBasedResource { } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tests\behat\bootstrap; use Dotenv\Dotenv; use Exception; use hipanel\hiart\Connection; use hiqdev\hiart\guzzle\Request; use hiqdev\hiart\RequestInterface; use Yii; use yii\di\Container; use yii\web\Application; class ApiClient { private Connection $connection; private Application $application; public function __construct() { $this->bootstrap(); $application = $this->application ?? $this->mockApplication(); $this->connection = new Connection($application); $this->connection->requestClass = Request::class; $this->connection->baseUri = $_ENV['HIART_BASEURI']; } private function bootstrap(): void { $dir = dirname(__DIR__, 6); $pathToYii = $dir . '/vendor/yiisoft/yii2/Yii.php'; require_once $pathToYii; (Dotenv::createImmutable($dir))->load(); if (empty($_ENV['HIART_BASEURI'])) { throw new Exception('HIART_BASEURI must be set in environment'); } } public function make(string $command, array $payload, string $performer): array { //var_dump(compact('command', 'payload', 'performer')); $res = $this->buildRequest($command, $payload, $performer ?? $this->reseller)->send()->getData(); if (!is_array($res)) { throw new Exception('API returned not array: ' . $res); } if (!empty($res['_error'])) { // var_dump(__FILE__ . ':' . __LINE__ . ' ' . __METHOD__, $command, $performer, $this->lastQuery, $res);die; $error = is_array($res['_error']) ? reset($res['_error']) : (string)$res['_error']; throw new Exception("API returned error: $error"); } return $res; } private function buildRequest(string $command, array $body = [], ?string $performer = null): RequestInterface { $body['auth_login'] = $performer; $body['auth_password'] = '<PASSWORD>'; $this->lastQuery = $this->connection->baseUri . $command . '?' . http_build_query($body); return $this->connection->callWithDisabledAuth( function () use ($command, $body) { $request = $this->connection ->createCommand() ->db ->getQueryBuilder() ->perform($command, null, $body); $request->build(); $request->addHeader('Cookie', 'XDEBUG_SESSION=XDEBUG_ECLIPSE'); return $request; } ); } private function mockApplication(): Application { Yii::$container = new Container(); return new Application( [ 'id' => 'behat-test-application', 'basePath' => __DIR__, 'vendorPath' => __DIR__ . '../../../../../', ] ); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\price; use hiqdev\php\billing\price\EnumPrice; use hiqdev\php\billing\price\RatePrice; use hiqdev\php\billing\price\SinglePrice; /** * Class PriceFactory. * * @author <NAME> <<EMAIL>> */ class PriceFactory extends \hiqdev\php\billing\price\PriceFactory { protected $creators = [ SinglePrice::class => 'createSinglePrice', EnumPrice::class => 'createEnumPrice', RatePrice::class => 'createRatePrice', TemplatePrice::class => 'createTemplatePrice', RateTemplatePrice::class => 'createRateTemplatePrice', ]; public function __construct(array $types = [], $defaultClass = null) { parent::__construct($types, $defaultClass); $this->types['TemplatePrice'] = TemplatePrice::class; } public function createTemplatePrice(TemplatePriceDto $dto): TemplatePrice { return new TemplatePrice($dto->id, $dto->type, $dto->target, $dto->plan, $dto->prepaid, $dto->price, $dto->subprices); } public function createRateTemplatePrice(RateTemplatePriceDto $dto): RateTemplatePrice { return new RateTemplatePrice($dto->id, $dto->type, $dto->target, $dto->plan, $dto->prepaid, $dto->price, $dto->rate); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\action; use hiapi\jsonApi\AttributionBasedResource; class ActionResource extends AttributionBasedResource { } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\target; use hiqdev\php\billing\target\TargetFactoryInterface; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\target\TargetInterface; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; use Laminas\Hydrator\HydratorInterface; /** * Class TargetHydrator. * * @author <NAME> <<EMAIL>> */ class TargetHydrator extends GeneratedHydrator { /** * @var TargetFactoryInterface */ private $targetFactory; public function __construct(TargetFactoryInterface $targetFactory) { $this->targetFactory = $targetFactory; } /** * {@inheritdoc} * @param object $object */ public function extract($object): array { $data = [ 'id' => $this->extractNone($object->getId()), 'type' => $this->extractNone($object->getType()), 'state' => $this->extractNone($object->getState()), 'name' => $object->getName(), 'label' => $object->getLabel(), ]; if ($data instanceof RemoteTarget) { $data['remoteid'] = $data->getRemoteId(); } return $data; } protected function extractNone($value) { /** * XXX JSON doesn't support float INF and NAN * TODO think of it more. */ return $value === TargetInterface::NONE ? '' : $value; } /** {@inheritdoc} */ public function hydrate(array $data, $object): object { if (!empty($data['type'])) { $data['type'] = $this->targetFactory->shortenType($data['type']); } return parent::hydrate($data, $object); } public function createEmptyInstance(string $className, array $data = []): object { if (isset($data['type'])) { $className = $this->targetFactory->getClassForType($data['type']); } if ($className === TargetInterface::class) { $className = Target::class; } return parent::createEmptyInstance($className, $data); } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\action\CheckCredit; use hiqdev\billing\hiapi\tools\CreditCheckerInterface; class Action { private CreditCheckerInterface $checker; public function __construct(CreditCheckerInterface $checker) { $this->checker = $checker; } public function __invoke(Command $command): bool { $actions = $command->getActions(); $this->checker->check($actions); return true; /// XXX ??? } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\target\Create; use hiapi\Core\Endpoint\BuilderFactory; use hiapi\Core\Endpoint\Endpoint; use hiapi\Core\Endpoint\EndpointBuilder; use hiapi\endpoints\Module\Multitenant\Tenant; use hiqdev\billing\hiapi\customer\CustomerLoader; use hiqdev\php\billing\target\Target; final class Builder { public function __invoke(BuilderFactory $build): Endpoint { return $this->create($build)->build(); } public function create(BuilderFactory $build): EndpointBuilder { return $build->endpoint(self::class) ->description('Creates a new Target') ->exportTo(Tenant::ALL) ->take(Command::class) ->checkPermission('plan.read') ->middlewares( CustomerLoader::class, $build->call(Action::class) ) ->return(Target::class); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\customer; use hiqdev\php\billing\customer\Customer; use hiqdev\php\billing\customer\CustomerRepositoryInterface; use League\Tactician\Middleware; use RuntimeException; use yii\web\User; use hiqdev\DataMapper\Query\Specification; use hiapi\Core\Auth\AuthRule; class CustomerLoader implements Middleware { private CustomerRepositoryInterface $repo; private User $user; public function __construct(User $user, CustomerRepositoryInterface $repo) { $this->user = $user; $this->repo = $repo; } public function execute($command, callable $next) { if (!isset($command->customer)) { $command->customer = $this->findCustomer($command); } return $next($command); } public function findCustomer($command): Customer { return $this->findCustomerByCommand($command) ?? $this->getCurrentCustomer(); } private function findCustomerByCommand($command): ?Customer { if (!empty($command->customer_id)) { $where = ['id' => $command->customer_id]; } elseif (!empty($command->customer_username)) { $where = ['login' => $command->customer_username]; } else { return null; } $spec = AuthRule::currentUser()->applyToSpecification( (new Specification)->where($where) ); return $this->repo->findOne($spec) ?: null; } private function getCurrentCustomer(): Customer { $identity = $this->user->getIdentity(); if ($identity === null) { throw new RuntimeException('CustomerLoader requires user to be authenticated'); } $seller = new Customer($identity->seller_id, $identity->seller); return new Customer($identity->id, $identity->username ?: $identity->email, $seller); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature; use DateTimeImmutable; use hiqdev\php\billing\EntityInterface; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\type\TypeInterface; interface FeatureInterface extends EntityInterface { public function setId(int $int): void; public function target(): Target; public function type(): TypeInterface; public function starts(): DateTimeImmutable; public function expires(): ?DateTimeImmutable; public function setExpires(?DateTimeImmutable $expirationTime): void; } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\action\Calculate; use DateTimeImmutable; use hiapi\commands\BaseCommand; use hiapi\validators\IdValidator; use hiapi\validators\LongRefValidator; use hiapi\validators\RefValidator; use hiapi\validators\UsernameValidator; use hiqdev\billing\hiapi\customer\CustomerLoader; use hiqdev\billing\hiapi\plan\PlanLoader; use hiqdev\billing\hiapi\target\TargetLoader; use hiqdev\DataMapper\Validator\DateTimeValidator; use hiqdev\php\billing\action\ActionInterface; use hiqdev\php\billing\customer\CustomerInterface; use hiqdev\php\billing\plan\PlanInterface; use hiqdev\php\billing\sale\SaleInterface; use hiqdev\php\billing\target\TargetInterface; use hiqdev\php\billing\type\TypeInterface; use hiqdev\php\units\Quantity; use hiqdev\php\units\QuantityInterface; use Psr\Container\ContainerInterface; use Laminas\Hydrator\HydratorInterface; class PaidCommand extends BaseCommand implements PaidCommandInterface { protected ContainerInterface $di; private HydratorInterface $hydrator; public function __construct(ContainerInterface $di, $config = []) { $this->di = $di; parent::__construct($config); } public $target_id; public $target_type; public $target_name; public $target_fullname; public $customer_id; public $customer_username; public $plan_id; public $plan_name; public $plan_seller; public $plan_fullname; public $amount; public $unit = 'items'; /** @var string */ public $type_name; /** @var TypeInterface|null */ public $type; /** @var DateTimeImmutable|string */ public $time; protected ?PlanInterface $plan = null; protected ?SaleInterface $sale = null; protected ?ActionInterface $action = null; protected ?TargetInterface $target = null; protected ?CustomerInterface $customer = null; /** @var ActionInterface[] */ private $actions; public function rules(): array { return array_merge(parent::rules(), [ [['target_id'], IdValidator::class], [['target_type'], RefValidator::class], [['target_name'], RefValidator::class], [['target_fullname'], 'string'], [['customer_id'], IdValidator::class], [['customer_username'], UsernameValidator::class], [['plan_id'], IdValidator::class], [['plan_name'], 'string'], [['plan_seller'], UsernameValidator::class], [['plan_fullname'], 'string'], ['amount', 'number', 'min' => 0], [['type_name'], LongRefValidator::class], [['unit'], RefValidator::class], [['time'], DateTimeValidator::class], ]); } public function getPlan(): ?PlanInterface { if (!isset($this->plan)) { $this->plan = $this->di->get(PlanLoader::class)->findPlanByCommand($this); } return $this->plan; } public function setPlan(?PlanInterface $plan) { $this->plan = $plan; } public function getTarget(): ?TargetInterface { if ($this->target === null) { $this->target = $this->di->get(TargetLoader::class)->findTarget($this); } return $this->target; } public function setTarget(?TargetInterface $target) { $this->target = $target; } public function getCustomer(): ?CustomerInterface { if (!isset($this->customer)) { $this->customer = $this->di->get(CustomerLoader::class)->findCustomer($this); } return $this->customer; } public function setCustomer(CustomerInterface $customer) { $this->customer = $customer; } public function getQuantity(): QuantityInterface { return Quantity::create($this->unit, $this->amount); } public function getType(): TypeInterface { if ($this->type === null) { $this->type = $this->getHydrator()->hydrate([ 'name' => $this->type_name, ], TypeInterface::class); } return $this->type; } public function getTime(): DateTimeImmutable { if (empty($this->time) || is_string($this->time)) { $this->time = new DateTimeImmutable($this->time ?? ''); } return $this->time; } public function getActions(): array { if (!isset($this->actions)) { $this->actions = [$this->getAction()]; } return $this->actions; } protected function getAction(): ActionInterface { if (!isset($this->action)) { /** @noinspection PhpFieldAssignmentTypeMismatchInspection */ $this->action = $this->getHydrator()->hydrate(array_filter([ 'customer' => $this->getCustomer(), 'target' => $this->getTarget(), 'type' => $this->getActionType(), 'quantity' => $this->getQuantity(), 'sale' => $this->getSale(), 'time' => $this->getTime(), ]), ActionInterface::class); } return $this->action; } protected function getActionType(): TypeInterface { return $this->getType(); } public function getSale(): ?SaleInterface { if (!isset($this->sale)) { if (!empty($this->getPlan())) { $this->sale = $this->getHydrator()->hydrate(array_filter([ 'customer' => $this->getCustomer(), 'target' => $this->getTarget(), 'plan' => $this->getPlan(), 'time' => $this->getTime(), ]), SaleInterface::class); } } return $this->sale; } protected function getHydrator(): HydratorInterface { if (!isset($this->hydrator)) { $this->hydrator = $this->di->get(HydratorInterface::class); } return $this->hydrator; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\action; use hiqdev\billing\hiapi\Hydrator\Helper\DateTimeImmutableFormatterStrategyHelper; use hiqdev\php\billing\action\Action; use hiqdev\php\billing\action\ActionState; use hiqdev\php\billing\customer\Customer; use hiqdev\php\billing\sale\Sale; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\type\Type; use hiqdev\php\units\Quantity; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; /** * Action Hydrator. * * @author <NAME> <<EMAIL>> */ class ActionHydrator extends GeneratedHydrator { public function __construct() { $this->addStrategy('time', DateTimeImmutableFormatterStrategyHelper::create()); } /** {@inheritdoc} */ public function hydrate(array $data, $object): object { $data['type'] = $this->hydrator->create($data['type'] ?? null, Type::class); $data['target'] = $this->hydrator->create($data['target'] ?? null, Target::class); $data['quantity'] = $this->hydrator->create($data['quantity'], Quantity::class); $data['customer'] = $this->hydrator->create($data['customer'], Customer::class); $data['time'] = $this->hydrateValue('time', $data['time'] ?? 'now'); if (isset($data['sale'])) { $data['sale'] = $this->hydrator->create($data['sale'], Sale::class); } if (isset($data['parent'])) { $data['parent'] = $this->hydrator->create($data['parent'], Action::class); } if (isset($data['state'])) { $data['state'] = $this->hydrator->create($data['state'], ActionState::class); } return parent::hydrate($data, $object); } /** * {@inheritdoc} * @param Action $object */ public function extract($object): array { $result = array_filter([ 'id' => $object->getId(), 'type' => $this->hydrator->extract($object->getType()), 'target' => $this->hydrator->extract($object->getTarget()), 'quantity' => $this->hydrator->extract($object->getQuantity()), 'customer' => $this->hydrator->extract($object->getCustomer()), 'time' => $this->extractValue('time', $object->getTime()), 'sale' => $object->getSale() ? $this->hydrator->extract($object->getSale()) : null, 'parent' => $object->getParent() ? $this->hydrator->extract($object->getParent()) : null, 'state' => $object->getState() ? $this->hydrator->extract($object->getState()) : null, 'usage_interval'=> $this->hydrator->extract($object->getUsageInterval()), ], static function ($value): bool { return $value !== null; }, ARRAY_FILTER_USE_BOTH); return $result; } public function createEmptyInstance(string $className, array $data = []): object { return parent::createEmptyInstance(Action::class, $data); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature; use hiqdev\billing\hiapi\target\TargetAttribution; use hiqdev\billing\hiapi\type\TypeAttribution; use hiqdev\DataMapper\Attribute\DateTimeAttribute; use hiqdev\DataMapper\Attribute\IntegerAttribute; use hiqdev\DataMapper\Attribution\AbstractAttribution; class FeatureAttribution extends AbstractAttribution { public function attributes() { return [ 'id' => IntegerAttribute::class, 'starts' => DateTimeAttribute::class, 'expires' => DateTimeAttribute::class, ]; } public function relations() { return [ 'target' => TargetAttribution::class, 'type' => TypeAttribution::class, ]; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\usage; use hiqdev\billing\hiapi\Hydrator\Helper\DateTimeImmutableFormatterStrategyHelper; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\type\Type; use hiqdev\php\billing\usage\Usage; use hiqdev\php\units\Quantity; class UsageHydrator extends GeneratedHydrator { public function __construct() { $this->addStrategy('time', DateTimeImmutableFormatterStrategyHelper::create()); } /** * {@inheritdoc} * @param object|Usage $object */ public function hydrate(array $data, $object): object { $data['target'] = $this->hydrator->create($data['target'], Target::class); $data['type'] = $this->hydrator->create($data['type'], Type::class); $data['time'] = $this->hydrateValue('time', $data['time']); $data['amount'] = $this->hydrator->create($data['amount'], Quantity::class); return parent::hydrate($data, $object); } /** * {@inheritdoc} * @param object|Usage $object */ public function extract($object): array { return [ 'time' => $this->extractValue('time', $object->time()), 'type' => $this->hydrator->extract($object->type()), 'target' => $this->hydrator->extract($object->target()), 'amount' => $this->hydrator->extract($object->amount()), ]; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\vo; use DateTimeImmutable; use League\Tactician\Middleware; class DateTimeLoader implements Middleware { private string $name; public function __construct(string $name) { $this->name = $name; } public function execute($command, callable $next) { $name = $this->name; if (is_string($command->$name)) { $command->$name = new DateTimeImmutable($command->$name); } return $next($command); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature\Cancel; use DateTimeImmutable; use DomainException; use hiqdev\billing\hiapi\feature\FeatureDto; use hiqdev\billing\hiapi\feature\FeatureFactoryInterface; use hiqdev\billing\hiapi\feature\FeatureInterface; use hiqdev\billing\hiapi\feature\FeatureRepositoryInterface; use hiqdev\billing\hiapi\tools\PermissionCheckerInterface; use hiqdev\php\billing\target\TargetRepositoryInterface; final class Action { private FeatureRepositoryInterface $featureRepository; private FeatureFactoryInterface $featureFactory; private TargetRepositoryInterface $targetRepository; private PermissionCheckerInterface $permissionChecker; public function __construct( FeatureFactoryInterface $featureFactory, FeatureRepositoryInterface $featureRepository, TargetRepositoryInterface $targetRepository, PermissionCheckerInterface $permissionChecker ) { $this->featureRepository = $featureRepository; $this->featureFactory = $featureFactory; $this->targetRepository = $targetRepository; $this->permissionChecker = $permissionChecker; } public function __invoke(Command $command): FeatureInterface { $this->permissionChecker->ensureCustomerCan($command->customer, 'have-goods'); $dto = new FeatureDto(); $dto->type = $command->type; $dto->target = $command->target; $feature = $this->findAndEnsureCanBeDisabled($dto); $feature->setExpires(new DateTimeImmutable()); $this->featureRepository->save($feature); return $feature; } private function findAndEnsureCanBeDisabled(FeatureDto $dto): FeatureInterface { $feature = $this->featureFactory->create($dto); $existingFeature = $this->featureRepository->findUnique($feature); if ($existingFeature === null) { throw new DomainException(sprintf( 'No active feature of type "%s" found. Nothing can be disabled', $feature->type()->getName(), )); } if ($existingFeature->expires() !== null && $existingFeature->expires() < new DateTimeImmutable() ) { throw new DomainException(sprintf( 'No active feature of type "%s" found. Nothing can be disabled', $feature->type()->getName(), )); } return $existingFeature; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\bill\Search; use hiapi\commands\SearchCommand; use hiqdev\php\billing\bill\Bill; /** * Bill Search Command * * @author <NAME> <<EMAIL>> */ class Command extends SearchCommand { public function getEntityClass(): string { return Bill::class; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\price; use hiqdev\billing\hiapi\formula\FormulaHydrationStrategy; use hiqdev\php\billing\plan\Plan; use hiqdev\php\billing\price\AbstractPrice; use hiqdev\php\billing\price\PriceFactoryInterface; use hiqdev\php\billing\price\PriceInterface; use hiqdev\php\billing\price\SinglePrice; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\type\Type; use hiqdev\php\units\Quantity; use hiqdev\php\units\Unit; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; use Laminas\Hydrator\Strategy\NullableStrategy; use Money\Currency; use Money\Money; use yii\helpers\Json; /** * Class PriceHydrator. * * @author <NAME> <<EMAIL>> */ class PriceHydrator extends GeneratedHydrator { /** * @var PriceFactoryInterface|PriceFactory */ protected $priceFactory; public function __construct(PriceFactoryInterface $priceFactory, FormulaHydrationStrategy $formulaHydrationStrategy) { $this->priceFactory = $priceFactory; $this->addStrategy('modifier', new NullableStrategy(clone $formulaHydrationStrategy, true)); } /** * {@inheritdoc} * @param object|PriceInterface|AbstractPrice $object */ public function hydrate(array $row, $object) { $row['target'] = $this->hydrator->hydrate($row['target'] ?? [], Target::class); $row['type'] = $this->hydrator->hydrate($row['type'], Type::class); if (isset($row['prepaid']['unit'])) { $row['unit'] = Unit::create($row['prepaid']['unit']); } if (isset($row['unit'], $row['prepaid']['quantity'])) { $row['prepaid'] = Quantity::create($row['unit'], $row['prepaid']['quantity']); } if (isset($row['price']['currency'])) { $row['currency'] = new Currency(strtoupper($row['price']['currency'])); } if (isset($row['currency'], $row['price']['amount'])) { $row['price'] = new Money(round($row['price']['amount']), $row['currency']); } if (!empty($row['plan'])) { $row['plan'] = $this->hydrator->create($row['plan'], Plan::class); } if (isset($row['data'])) { $data = is_array($row['data']) ? $row['data'] : Json::decode($row['data']); } $row['modifier'] = $this->hydrateValue('modifier', trim($data['formula'] ?? '')); $row['sums'] = empty($data['sums']) ? [] : $data['sums']; $row['rate'] = $data['rate'] ?? null; $row['subprices'] = $data['subprices'] ?? null; return parent::hydrate($row, $object); } /** * {@inheritdoc} * @param object|PriceInterface|SinglePrice $object */ public function extract($object): array { return array_filter([ 'id' => $object->getId(), 'type' => $this->hydrator->extract($object->getType()), 'target' => $this->hydrator->extract($object->getTarget()), 'plan' => null, ]); } /** * @throws \ReflectionException * @return object */ public function createEmptyInstance(string $className, array $data = []): object { if (isset($data['data']) && !is_array($data['data'])) { $additionalData = Json::decode($data['data']); } $class = $this->priceFactory->findClassForTypes([ $additionalData['class'] ?? null, $data['type']['name'], ]); return parent::createEmptyInstance($class, $data); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\price; use hiqdev\php\billing\plan\PlanInterface; use hiqdev\php\billing\price\SinglePrice; use hiqdev\php\billing\target\TargetInterface; use hiqdev\php\billing\type\TypeInterface; use hiqdev\php\units\QuantityInterface; use Money\Money; /** * Class TemplatePrice. * * @author <NAME> <<EMAIL>> */ class TemplatePrice extends SinglePrice { /** * @var Money[] */ protected $subprices = []; public function __construct( $id, TypeInterface $type, TargetInterface $target, PlanInterface $plan = null, QuantityInterface $prepaid, Money $price, array $subprices ) { parent::__construct($id, $type, $target, $plan, $prepaid, $price); $this->subprices = $subprices; } public function jsonSerialize(): array { return array_merge(parent::jsonSerialize(), [ 'subprices' => $this->subprices, ]); } /** * @return Money[] */ public function getSubprices(): array { return $this->subprices; } /** * @param string $currencyCode * @return string the subprice in decimal format (e.g. `10.25`) */ public function getSubprice($currencyCode): string { return $this->subprices[strtoupper($currencyCode)] ?? '0'; } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\plan; use hiqdev\billing\mrdp\Plan\AvailableForConditionBuilder; use hiqdev\DataMapper\Query\Field\FieldInterface; /** * Class AvailableFor * * @author <NAME> <<EMAIL>> * @see AvailableForConditionBuilder */ final class AvailableFor implements FieldInterface { public const SELLER = 0; public const CLIENT_ID = 1; public const SELLER_FIELD = 'available_for_seller'; public const CLIENT_ID_FIELD = 'available_for_client_id'; private string $fieldName; private int $type; /** * AvailableFor constructor. * * @psalm-param self::SELLER|self::CLIENT_ID $type */ public function __construct(string $fieldName, int $type) { $this->fieldName = $fieldName; $this->type = $type; } public static function seller(string $fieldName): self { return new self($fieldName, self::SELLER); } public static function client_id(string $fieldName): self { return new self($fieldName, self::CLIENT_ID); } public function getName(): string { return $this->fieldName; } public function getType(): int { return $this->type; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\type; use hiapi\jsonApi\AttributionBasedResource; class TypeResource extends AttributionBasedResource { } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature; use hiapi\jsonApi\AttributionBasedSingleResourceDocument; class FeatureDocument extends AttributionBasedSingleResourceDocument { } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\bill; use hiqdev\php\billing\bill\BillRequisite; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; class BillRequisiteHydrator extends GeneratedHydrator { public function hydrate(array $data, $object) { return parent::hydrate($data, $object); } /** * {@inheritdoc} * @param BillRequisite $object */ public function extract($object): array { return array_filter([ 'id' => $object->getId(), 'name' => $object->getName(), ]); } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\statement\Search; use Doctrine\Common\Collections\ArrayCollection; use hiapi\Core\Auth\AuthRule; use hiqdev\php\billing\statement\Statement; use hiqdev\php\billing\statement\StatementBill; use hiqdev\php\billing\statement\StatementRepositoryInterface; class Action { private StatementRepositoryInterface $repo; public function __construct(StatementRepositoryInterface $repo) { $this->repo = $repo; } public function __invoke(Command $command): ArrayCollection { $spec = $this->prepareSpecification($command); /** @var Statement[] $res */ $res = $this->repo->findAll($spec); return new ArrayCollection($res); } private function prepareSpecification(Command $command) { $spec = $command->getSpecification(); $spec = AuthRule::currentUser()->applyToSpecification($spec); if (empty($spec->orderBy)) { $spec->orderBy(['time' => SORT_DESC]); } return $spec; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\Hydrator\Helper; use DateTimeImmutable; use DateTimeZone; use Laminas\Hydrator\Strategy\DateTimeFormatterStrategy; use Laminas\Hydrator\Strategy\DateTimeImmutableFormatterStrategy; class DateTimeImmutableFormatterStrategyHelper { /** * Simplifies DateTimeImmutableFormatterStrategy creation with the * options, widely used in the billing-hiapi. * * @param string $format * @param DateTimeZone|null $timezone * @return DateTimeImmutableFormatterStrategy */ public static function create( string $format = DateTimeImmutable::ATOM, ?DateTimeZone $timezone = null ): DateTimeImmutableFormatterStrategy { return new DateTimeImmutableFormatterStrategy( new DateTimeFormatterStrategy($format, $timezone, true) ); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature; use hiapi\jsonApi\AttributionBasedResource; class FeatureResource extends AttributionBasedResource { } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\action\Calculate; use Doctrine\Common\Collections\ArrayCollection; use hiqdev\php\billing\order\BillingInterface; final class BulkAction { private BillingInterface $billing; public function __construct(BillingInterface $billing) { $this->billing = $billing; } public function __invoke($commands): ArrayCollection { $actions = (new BulkPaidCommand($commands))->getActions(); $charges = $this->billing->calculateCharges($actions); return new ArrayCollection($charges); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tests\unit\sale; use hiqdev\php\billing\sale\Sale; use hiqdev\php\billing\sale\SaleRepositoryInterface; use hiqdev\yii\DataMapper\tests\unit\BaseRepositoryTest; class SaleRepositoryTest extends BaseRepositoryTest { public function testDI() { $this->assertInstanceOf(SaleRepositoryInterface::class, $this->getRepo()); } protected function getRepo(): SaleRepositoryInterface { return $this->getRepository(Sale::class); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\type; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; use hiqdev\php\billing\type\Type; use hiqdev\php\billing\type\TypeInterface; /** * Class TypeHydrator. * * @author <NAME> <<EMAIL>> */ class TypeHydrator extends GeneratedHydrator { /** * {@inheritdoc} * @param object|Type $object */ public function extract($object): array { $result = array_filter([ 'id' => $object->getId(), 'name' => $object->getName(), ]); return $result; } public function createEmptyInstance(string $className, array $data = []): object { if ($className === TypeInterface::class) { $className = Type::class; } return parent::createEmptyInstance($className, $data); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\bill; use hiqdev\php\billing\bill\BillState; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; /** * BillState Hydrator. * * @author <NAME> <<EMAIL>> */ class BillStateHydrator extends GeneratedHydrator { public function hydrate(array $data, $object): object { return BillState::fromString($data['state'] ?? reset($data)); } /** * {@inheritdoc} * @param BillState $object */ public function extract($object): array { return ['name' => $object->getName()]; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tests\behat\bootstrap; use hiqdev\billing\hiapi\plan\PlanFactory; use hiqdev\billing\hiapi\price\PriceFactory; use hiqdev\billing\hiapi\target\TargetFactory; use hiqdev\billing\hiapi\type\TypeFactory; use hiqdev\php\billing\sale\SaleFactory; use hiqdev\php\billing\target\TargetInterface; use hiqdev\php\billing\tests\behat\bootstrap\BuilderInterface; use hiqdev\php\billing\tests\support\tools\SimpleFactory; class ApiBasedBuilder implements BuilderInterface { private ApiClient $client; protected SimpleFactory $factory; protected string $reseller; protected string $customer; protected string $manager; protected string $admin; protected string $root; protected array $prices = []; protected array $plan; protected static $lastPlan; protected static array $plans = []; protected array $sale; protected array $actions = []; public function __construct() { $this->client = new ApiClient(); $this->factory = new SimpleFactory([ 'plan' => new PlanFactory(), 'price' => new PriceFactory(), 'target' => new TargetFactory(), 'type' => new TypeFactory(), 'sale' => new SaleFactory(), ]); } public function buildReseller(string $login): void { $this->reseller = $login; } public function buildCustomer(string $login): void { $this->customer = $login; $this->makeAsCustomer('CleanForTests'); } public function buildPlan(string $name, string $type, bool $grouping = false): void { $this->prices = []; $plan = [ 'name' => $name, 'type' => $type, 'is_grouping' => $grouping, 'currency' => 'usd', 'is_available' => true, ]; if (empty(static::$plans[$name]) || !empty(array_diff($plan, static::$plans[$name]))) { static::$plans[$name] = $plan; } } public function buildPrice(array $data): void { $this->prices[] = $data; } public function performBilling(string $time): void { $this->makeAsReseller('client-perform-billing', [ 'client' => $this->customer, 'time' => $time, ]); } public function recreatePlan(string $name): void { $plan = static::$plans[$name] ?? []; if (!empty($plan['id']) && $plan['type'] !== 'server') { return; } $this->deletePlan($name); $this->createPlan($name); $this->assignPlan($name); $this->createPrices($name); } public function createPrices(string $name): void { $plan = static::$plans[$name]; foreach ($this->prices as &$price) { $price['plan_id'] = $plan['id'] ?? null; $price['quantity'] = $price['prepaid'] ?? 0; $price['currency'] = $this->preparePriceCurrency($price['currency']); $price['object'] = $price['target'] ?? null; if (isset($price['sums'])) { $price['sums'] = array_map(fn ($price) => (int) ((float) $price * 100), $price['sums']); $price['price'] = 0; $price['class'] = 'CertificatePrice'; } $this->makeAsReseller('price-create', $price); } } private function preparePriceCurrency(?string $currency): ?string { if ($currency === '%') { return null; } return strtolower($currency); } public function deletePlan(string $name): void { $plan = static::$plans[$name]; $found = $this->makeAsReseller('tariffs-search', [ 'name' => $name, 'show_deleted' => 1, 'limit' => 1, ]); $old = reset($found); if (empty($old)) { return; } $this->makeAsReseller('tariff-delete', ['id' => $old['id']]); $this->makeAsReseller('tariff-delete', ['id' => $old['id']]); } public function createPlan(string $name): array { $plan = static::$plans[$name]; $plan = array_merge($plan, $this->makeAsReseller('plan-create', $plan)); static::$plans[$name] = $plan; static::$lastPlan = $plan; $this->plan = $plan; return $plan; } public function assignPlan(string $name) { $assignedTariffsResponse = $this->makeAsReseller('client-get-tariffs', [ 'client' => $this->customer, ]); $tariff_ids = []; if ($assignedTariffsResponse['tariff_ids'] !== null) { $tariff_ids = explode(',', $assignedTariffsResponse['tariff_ids']); } $this->makeAsReseller('client-set-tariffs', [ 'client' => $this->customer, 'tariff_ids' => array_merge($tariff_ids, [static::$plans[$name]['id']]), ]); } public function buildSale(string $target, string $plan, string $time): void { $planExist = $this->makeAsReseller('plans-search', ['select' => 'column', 'name' => $plan, 'limit' => 1]); if (empty($planExist)) { return; } $plan = reset($planExist); if (empty($plan['id'])) { return; } [$class, $name] = explode(':', $target); if ($class === 'client') { $this->sale = $this->makeAsReseller('client-sell', [ 'client' => $this->customer, 'subject' => $name, 'plan_id' => $plan['id'], 'sale_time' => $time, ]); } elseif ($class === 'class' && in_array($name, ['zone','certificate'], true)) { $this->makeAsReseller('SaleCreate', [ 'customer_username' => 'hipanel_test_user', 'target_type' => $class, 'target_name' => $name, 'plan_id' => $plan['id'], 'time' => $time, ]); } else { $this->sale = $this->makeAsReseller('client-set-tariffs', [ 'client' => $this->customer, 'tariff_ids' => [$plan['id']], ]); } } public function targetChangePlan(string $target, string $planName, string $date, string $wallTime = null) { [$class, $name] = explode(':', $target); $options = [ 'name' => $name, 'type' => $class, 'plan_name' => $planName, 'time' => $date, ]; if ($wallTime !== null) { $this->makeAsReseller('TargetChangePlan', array_merge($options, ['wall_time' => $wallTime, 'customer_username' => $this->customer])); } else { $this->makeAsCustomer('TargetChangePlan', $options); } } public function buildPurchase(string $target, string $plan, string $time, ?array $uses = []): void { $target = $this->factory->get('target', $target); $plan = static::$plans[$plan]; $this->makeAsCustomer('TargetPurchase', [ 'type' => $target->getType(), 'name' => $target->getName(), 'plan_id' => $plan['id'], 'time' => $time, 'initial_uses' => $uses, ]); } public function findBills(array $params): array { $target = $this->factory->get('target', $params['target']); $targetTypes = $target->getType(); if ($targetTypes === 'domain') { $targetTypes = ['domain','regdomain']; } $rows = $this->makeAsCustomer('BillsSearch', [ 'with' => ['charges'], 'where' => [ 'customer-login' => 'hipanel_test_user', /// XXX to be removed! 'type-name' => $params['type'], 'target-type' => $targetTypes, 'target-name' => $target->getName(), 'time' => $params['time'] ?? null, ], ]); $res = []; foreach ($rows as $row) { $res[] = $this->factory->get('bill', $row); } return $res; } public function findUsage(string $time, string $targetName, string $typeName): array { return $this->makeAsCustomer('uses-search', [ 'groupby' => 'server_traf_hour', 'type' => $typeName, 'time_from' => $time, 'time_till' => (new \DateTimeImmutable($time))->modify('+1 second')->format(DATE_ATOM), ]); } public function buildTarget(string $name) { /** @var TargetInterface $target */ $target = $this->factory->get('target', $name); $this->makeAsCustomer('TargetCreate', [ 'name' => $target->getName(), 'type' => $target->getType(), 'remoteid' => random_int(111111, 999999), ]); } public function findHistoricalSales(array $params) { $target = $this->factory->get('target', $params['target']); $res = []; $rows = $this->makeAsCustomer('SalesSearch', [ 'include' => ['history'], 'where' => [ 'target-type' => $target->getType(), 'target-name' => $target->getName(), 'customer-login' => $this->customer, ], ]); foreach ($rows as $key => $row) { $res[$key] = $this->factory->create('sale', $row); } return $res; } public function flushEntitiesCache(): void { $this->factory->clearEntitiesCache(); } public function flushEntitiesCacheByType(string $type): void { $this->factory->clearEntitiesCacheByType($type); } public function setConsumption(string $type, int $amount, string $unit, string $target, string $time): void { $this->makeAsManager('use-set', [ 'object' => $target, 'type' => $type, 'time' => $time, 'amount' => $amount, 'unit' => $unit, ]); } public function setAction(string $type, int $amount, string $unit, string $target, string $time): void { $this->actions[] = [ 'target_fullname' => $target, 'type_name' => $type, 'amount' => $amount, 'unit' => $unit, 'time' => $time, 'plan_id' => static::$lastPlan['id'], ]; } public function performCalculation(string $time): array { $charges = $this->makeAsCustomer('ActionsCalculate', $this->actions); foreach ($charges as $key => $charge) { unset($charge['price']); $res[$key] = $this->factory->get('charge', $charge); } return $res; } protected function isAssigned(int $planId, string $login): bool { $assignments = $this->makeAsManager('client-get-tariffs', ['client' => $login]); $tariffIds = $assignments['tariff_ids'] ? explode(',', $assignments['tariff_ids']) : []; return in_array($planId, $tariffIds, true); } protected function makeAsReseller(string $command, array $payload = []): array { return $this->client->make($command, $payload, $this->reseller); } protected function makeAsManager(string $command, array $payload = []): array { return $this->client->make($command, $payload, $this->manager); } protected function makeAsCustomer(string $command, array $payload = []): array { return $this->client->make($command, $payload, $this->customer); } protected function makeAsAdmin(string $command, array $payload = []): array { return $this->client->make($command, $payload, $this->admin); } protected function makeAsRoot(string $command, array $payload = []): array { return $this->client->make($command, $payload, $this->root); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\vo; use DateTimeImmutable; use hiqdev\DataMapper\Repository\BaseRepository; class DateTimeImmutableRepository extends BaseRepository { /** * @param array $row * @return DateTimeImmutable */ public function create($data) { return new DateTimeImmutable($data); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tests\unit\bill; use hiqdev\php\billing\bill\Bill; use hiqdev\php\billing\bill\BillRepositoryInterface; use hiqdev\yii\DataMapper\tests\unit\BaseRepositoryTest; class BillRepositoryTest extends BaseRepositoryTest { public function testDI() { $this->assertInstanceOf(BillRepositoryInterface::class, $this->getRepo()); } protected function getRepo(): BillRepositoryInterface { return $this->getRepository(Bill::class); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\Hydrator\Strategy; use InvalidArgumentException; use Laminas\Hydrator\Strategy\StrategyInterface; use Money\Currency; use Money\Money; /** * Class MoneyStrategy converts between {@see Money} and array types. * * @author <NAME> <<EMAIL>> */ final class MoneyStrategy implements StrategyInterface { /** * @param Money $value * @param object|null $object * @return array */ public function extract($value, ?object $object = null) { return [ 'currency' => $value->getCurrency()->getCode(), 'amount' => $value->getAmount(), ]; } /** * Converts `amount`, passed in cents to {@see Money} object. * * @param array $value * @psalm-param array{currency: string, amount: int|float|string} $value * @param array|null $data * @return Money */ public function hydrate($value, ?array $data) { if (!is_array($value)) { throw new InvalidArgumentException('Money value must be an array'); } if (!isset($value['currency'])) { throw new InvalidArgumentException('Money value must contain `currency` key'); } $amount = sprintf('%.0f', $value['amount'] ?? '0'); $currency = new Currency(strtoupper($value['currency'])); return new Money($amount, $currency); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tests\unit\type; use hiqdev\billing\hiapi\type\TypeSemantics; use hiqdev\php\billing\type\Type; use hiqdev\php\billing\type\TypeInterface; /** * @author <NAME> <<EMAIL>> */ class TypeSemanticsTest extends \PHPUnit\Framework\TestCase { /** @var TypeSemantics */ protected $semantics; public function setUp(): void { $this->semantics = new TypeSemantics(); } /** * @dataProvider monthlyTypesProvider */ public function testDetectesMonthlyTypes(TypeInterface $type, bool $shouldBeMonthly) { $this->assertSame($shouldBeMonthly, $this->semantics->isMonthly($type)); } public function monthlyTypesProvider() { return [ [new Type(null, 'monthly,monthly'), true], [new Type(null, 'monthly,foo,bar'), true], [new Type(null, 'monthly'), true], [new Type(null, 'overuse'), false], [new Type(null, 'overuse,monthly'), false], ]; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\bill; use DateTimeImmutable; use hiqdev\billing\hiapi\Http\Serializer\HttpSerializer; use hiqdev\billing\hiapi\Hydrator\Helper\DateTimeImmutableFormatterStrategyHelper; use hiqdev\billing\hiapi\Hydrator\Strategy\MoneyStrategy; use hiqdev\php\billing\bill\Bill; use hiqdev\php\billing\bill\BillInterface; use hiqdev\php\billing\bill\BillRequisite; use hiqdev\php\billing\bill\BillState; use hiqdev\php\billing\charge\ChargeInterface; use hiqdev\php\billing\customer\Customer; use hiqdev\php\billing\plan\Plan; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\type\Type; use hiqdev\php\units\Quantity; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; use Money\Money; use RecursiveArrayIterator; use RecursiveIteratorIterator; use yii\web\User; /** * Bill Hydrator. * * @author <NAME> <<EMAIL>> */ class BillHydrator extends GeneratedHydrator { protected array $requiredAttributes = [ 'type' => Type::class, 'time' => DateTimeImmutable::class, 'quantity' => Quantity::class, 'sum' => Money::class, 'customer' => Customer::class, ]; /** @var array<string, bool> */ protected array $attributesHandledWithStrategy = [ 'time' => true, 'sum' => true, ]; protected array $optionalAttributes = [ 'target' => Target::class, 'plan' => Plan::class, 'state' => BillState::class, 'requisite' => BillRequisite::class, ]; private HttpSerializer $httpSerializer; public function __construct(HttpSerializer $httpSerializer) { $this->httpSerializer = $httpSerializer; $this->addStrategy('time', DateTimeImmutableFormatterStrategyHelper::create()); $this->addStrategy('sum', new MoneyStrategy()); } /** * {@inheritdoc} * @param array $data * @param object|Bill $object * @return object * @throws \Exception */ public function hydrate(array $data, $object): object { foreach ($this->requiredAttributes as $attr => $class) { if (isset($this->attributesHandledWithStrategy[$attr])) { $data[$attr] = $this->hydrateValue($attr, $data[$attr]); } else { $data[$attr] = $this->hydrator->create($data[$attr], $class); } } foreach ($this->optionalAttributes as $attr => $class) { if (isset($data[$attr])) { if (is_array($data[$attr]) && $this->isArrayDeeplyEmpty($data[$attr])) { $data[$attr] = null; continue; } if (isset($this->attributesHandledWithStrategy[$attr])) { $data[$attr] = $this->hydrateValue($attr, $data[$attr]); } else { $data[$attr] = $this->hydrator->create($data[$attr], $class); } } } $raw_charges = $data['charges'] ?? null; unset($data['charges']); /** @var Bill $bill */ $bill = parent::hydrate($data, $object); if (\is_array($raw_charges)) { $charges = []; foreach ($raw_charges as $key => $charge) { if ($charge instanceof ChargeInterface) { $charge->setBill($bill); $charges[$key] = $charge; } else { $charge['bill'] = $bill; $charges[$key] = $this->hydrator->hydrate($charge, ChargeInterface::class); } } $bill->setCharges($charges); } return $bill; } private function isArrayDeeplyEmpty(array $array): bool { $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)); foreach ($iterator as $value) { if ($value !== null) { return false; } } return true; } /** * {@inheritdoc} * @param object|Bill $object */ public function extract($object): array { return array_filter([ 'id' => $object->getId(), 'type' => $this->hydrator->extract($object->getType()), 'time' => $this->extractValue('time', $object->getTime()), 'sum' => $this->hydrator->extract($object->getSum()), 'quantity' => $this->hydrator->extract($object->getQuantity()), 'customer' => $this->hydrator->extract($object->getCustomer()), 'requisite' => $object->getRequisite() ? $this->hydrator->extract($object->getRequisite()) : null, 'target' => $object->getTarget() ? $this->hydrator->extract($object->getTarget()) : null, 'plan' => $object->getPlan() ? $this->hydrator->extract($object->getPlan()) : null, 'charges' => $this->httpSerializer->ensureBeforeCall( function (User $user) use ($object) { $plan = $object->getPlan(); if ($plan && $plan->getType() && in_array($plan->getType()->getName(), ['server', 'private_cloud'])) { return $user->can('bill.see-server-charges'); } return true; }, fn() => $this->hydrator->extractAll($object->getCharges()), [] ), 'state' => $object->getState() ? $this->hydrator->extract($object->getState()) : null, 'comment' => $object->getComment(), ], static function ($value): bool { return $value !== null; }, ARRAY_FILTER_USE_BOTH); } public function createEmptyInstance(string $className, array $data = []): object { if ($className === BillInterface::class) { $className = Bill::class; } return parent::createEmptyInstance($className, $data); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\tests\unit\Hydrator\Strategy; use hiqdev\billing\hiapi\Hydrator\Strategy\MoneyStrategy; use Money\Currency; use Money\Money; use PHPUnit\Framework\TestCase; /** * Class MoneyStrategyTest * * @author <NAME> <<EMAIL>> * @covers \hiqdev\billing\hiapi\Hydrator\Strategy\MoneyStrategy */ class MoneyStrategyTest extends TestCase { /** * @dataProvider hydrateHydrateDataProvider */ public function testHydrate($array, $money): void { $strategy = new MoneyStrategy(); $this->assertEquals($money, $strategy->hydrate($array, null)); } public function testInputMustBeAnArray(): void { $strategy = new MoneyStrategy(); $this->expectExceptionMessage('Money value must be an array'); $strategy->hydrate('foo', null); } public function testCurrencyIsRequired(): void { $strategy = new MoneyStrategy(); $this->expectExceptionMessage('Money value must contain `currency` key'); $strategy->hydrate(['amount' => 100], null); } public function testExtract(): void { $strategy = new MoneyStrategy(); $money = new Money(100, new Currency('USD')); $expected = [ 'amount' => 100, 'currency' => 'USD', ]; $this->assertEquals($expected, $strategy->extract($money, null)); } public function hydrateHydrateDataProvider() { yield 'simple' => [ 'array' => [ 'amount' => '100', 'currency' => 'USD', ], 'object' => new Money(100, new Currency('USD')) ]; yield 'lowercase currency' => [ 'array' => [ 'amount' => 100, 'currency' => 'usd', ], 'object' => new Money(100, new Currency('USD')) ]; yield 'strategy expects amount in cents and rounds amount to integer (#1)' => [ 'array' => [ 'amount' => 100.99, 'currency' => 'USD', ], 'object' => new Money(101, new Currency('USD')) ]; yield 'strategy expects amount in cents and rounds amount to integer (#2)' => [ 'array' => [ 'amount' => 100.4, 'currency' => 'USD', ], 'object' => new Money(100, new Currency('USD')) ]; yield 'negative amount' => [ 'array' => [ 'amount' => -100, 'currency' => 'USD', ], 'object' => new Money(-100, new Currency('USD')) ]; yield 'zero amount' => [ 'array' => [ 'amount' => 0, 'currency' => 'USD', ], 'object' => new Money(0, new Currency('USD')) ]; yield 'missing amount' => [ 'array' => [ 'currency' => 'USD', ], 'object' => new Money(0, new Currency('USD')) ]; yield 'amount after precision lose' => [ 'array' => [ 'amount' => '70485.65' * 100, 'currency' => 'USD', ], 'object' => new Money(7048565, new Currency('USD')) ]; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\action\Calculate; class BulkPaidCommand implements PaidCommandInterface { private iterable $commands; public function __construct(iterable $commands) { $this->commands = $commands; } public function getActions(): array { $res = []; foreach ($this->commands as $key => $command) { $res = array_merge($res, $command->getActions()); } return $res; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ /** * @var array $params */ $singletons = [ \hiqdev\billing\hiapi\Http\Serializer\HttpSerializer::class => \hiqdev\billing\hiapi\Http\Serializer\HttpSerializer::class, \hiqdev\DataMapper\Repository\EntityManagerInterface::class => [ 'repositories' => [ \DateTimeImmutable::class => \hiqdev\billing\hiapi\vo\DateTimeImmutableRepository::class, ], ], \hiqdev\DataMapper\Hydrator\ConfigurableHydrator::class => [ 'hydrators' => [ \hiqdev\php\billing\customer\Customer::class => \hiqdev\billing\hiapi\customer\CustomerHydrator::class, \hiqdev\php\billing\customer\CustomerInterface::class => \hiqdev\billing\hiapi\customer\CustomerHydrator::class, \hiqdev\php\billing\action\Action::class => \hiqdev\billing\hiapi\action\ActionHydrator::class, \hiqdev\php\billing\action\ActionInterface::class => \hiqdev\billing\hiapi\action\ActionHydrator::class, \hiqdev\php\billing\action\ActionState::class => \hiqdev\billing\hiapi\action\ActionStateHydrator::class, \hiqdev\php\billing\action\UsageInterval::class => \hiqdev\billing\hiapi\action\UsageIntervalHydrator::class, \hiqdev\php\billing\charge\Charge::class => \hiqdev\billing\hiapi\charge\ChargeHydrator::class, \hiqdev\php\billing\charge\ChargeInterface::class => \hiqdev\billing\hiapi\charge\ChargeHydrator::class, \hiqdev\php\billing\charge\ChargeState::class => \hiqdev\billing\hiapi\charge\ChargeStateHydrator::class, \hiqdev\php\billing\bill\Bill::class => \hiqdev\billing\hiapi\bill\BillHydrator::class, \hiqdev\php\billing\bill\BillInterface::class => \hiqdev\billing\hiapi\bill\BillHydrator::class, \hiqdev\php\billing\bill\BillState::class => \hiqdev\billing\hiapi\bill\BillStateHydrator::class, \hiqdev\php\billing\bill\BillRequisite::class => \hiqdev\billing\hiapi\bill\BillRequisiteHydrator::class, \hiqdev\php\billing\statement\Statement::class => \hiqdev\billing\hiapi\statement\StatementHydrator::class, \hiqdev\php\billing\statement\StatementBill::class => \hiqdev\billing\hiapi\statement\StatementBillHydrator::class, \hiqdev\php\billing\statement\StatementBillInterface::class => \hiqdev\billing\hiapi\statement\StatementBillHydrator::class, \hiqdev\php\billing\target\Target::class => \hiqdev\billing\hiapi\target\TargetHydrator::class, \hiqdev\php\billing\target\TargetCollection::class => \hiqdev\billing\hiapi\target\TargetHydrator::class, \hiqdev\php\billing\target\TargetInterface::class => \hiqdev\billing\hiapi\target\TargetHydrator::class, \hiqdev\php\billing\type\Type::class => \hiqdev\billing\hiapi\type\TypeHydrator::class, \hiqdev\php\billing\type\TypeInterface::class => \hiqdev\billing\hiapi\type\TypeHydrator::class, \hiqdev\php\billing\plan\Plan::class => \hiqdev\billing\hiapi\plan\PlanHydrator::class, \hiqdev\php\billing\plan\PlanInterface::class => \hiqdev\billing\hiapi\plan\PlanHydrator::class, \hiqdev\php\billing\price\PriceInterface::class => \hiqdev\billing\hiapi\price\PriceHydrator::class, \hiqdev\php\billing\price\EnumPrice::class => \hiqdev\billing\hiapi\price\EnumPriceHydrator::class, \hiqdev\php\billing\price\SinglePrice::class => \hiqdev\billing\hiapi\price\SinglePriceHydrator::class, \hiqdev\php\billing\sale\Sale::class => \hiqdev\billing\hiapi\sale\SaleHydrator::class, \hiqdev\php\billing\sale\SaleInterface::class => \hiqdev\billing\hiapi\sale\SaleHydrator::class, \hiqdev\php\units\Quantity::class => \hiqdev\billing\hiapi\vo\QuantityHydrator::class, \hiqdev\billing\hiapi\feature\FeatureInterface::class => \hiqdev\billing\hiapi\feature\FeatureHydrator::class, \hiqdev\billing\hiapi\feature\Feature::class => \hiqdev\billing\hiapi\feature\FeatureHydrator::class, \hiqdev\billing\hiapi\plan\PlanReadModel::class => \hiqdev\billing\hiapi\plan\PlanReadModelHydrator::class, \hiqdev\php\billing\usage\Usage::class => \hiqdev\billing\hiapi\usage\UsageHydrator::class, \Money\Money::class => \hiqdev\billing\hiapi\vo\MoneyHydrator::class, ], ], \hiqdev\php\billing\formula\FormulaEngineInterface::class => [ '__class' => \hiqdev\php\billing\formula\FormulaEngine::class, ], \hiqdev\php\billing\order\CalculatorInterface::class => [ '__class' => \hiqdev\php\billing\order\Calculator::class, ], \hiqdev\php\billing\tools\AggregatorInterface::class => [ '__class' => \hiqdev\php\billing\tools\Aggregator::class, ], \hiqdev\php\billing\tools\MergerInterface::class => [ '__class' => \hiqdev\billing\hiapi\tools\Merger::class, ], \hiqdev\billing\hiapi\tools\Merger::class => [ '__construct()' => [ \hiqdev\yii\compat\yii::referenceTo(\hiqdev\php\billing\tools\Merger::class), ], ], \hiqdev\php\billing\charge\GeneralizerInterface::class => [ '__class' => \hiqdev\billing\hiapi\charge\Generalizer::class, ], \hiqdev\php\billing\action\ActionFactoryInterface::class => [ '__class' => \hiqdev\php\billing\action\ActionFactory::class, ], \hiqdev\php\billing\charge\ChargeFactoryInterface::class => [ '__class' => \hiqdev\php\billing\charge\ChargeFactory::class, ], \hiqdev\php\billing\type\TypeFactoryInterface::class => [ '__class' => \hiqdev\billing\hiapi\type\TypeFactory::class, ], \hiqdev\php\billing\target\TargetFactoryInterface::class => [ '__class' => \hiqdev\billing\hiapi\target\TargetFactory::class, '__construct()' => [ $params['billing-hiapi.target.classmap'], $params['billing-hiapi.target.defaultClass'], ], ], \hiqdev\php\billing\bill\BillFactoryInterface::class => [ '__class' => \hiqdev\php\billing\bill\BillFactory::class, ], \hiqdev\php\billing\customer\CustomerFactoryInterface::class => [ '__class' => \hiqdev\php\billing\customer\CustomerFactory::class, ], \hiqdev\php\billing\plan\PlanFactoryInterface::class => [ '__class' => \hiqdev\php\billing\plan\PlanFactory::class, ], \hiqdev\php\billing\price\PriceFactoryInterface::class => [ '__class' => \hiqdev\billing\hiapi\price\PriceFactory::class, '__construct()' => [ $params['billing-hiapi.price.types'], $params['billing-hiapi.price.defaultClass'], ], ], \hiqdev\php\billing\sale\SaleFactoryInterface::class => [ '__class' => \hiqdev\php\billing\sale\SaleFactory::class, ], \hiqdev\php\billing\tools\FactoryInterface::class => [ '__class' => \hiqdev\php\billing\tools\Factory::class, '__construct()' => [ 'factories' => [ 'action' => \hiqdev\yii\compat\yii::referenceTo(\hiqdev\php\billing\action\ActionFactoryInterface::class), 'bill' => \hiqdev\yii\compat\yii::referenceTo(\hiqdev\php\billing\bill\BillFactoryInterface::class), 'charge' => \hiqdev\yii\compat\yii::referenceTo(\hiqdev\php\billing\charge\ChargeFactoryInterface::class), 'customer' => \hiqdev\yii\compat\yii::referenceTo(\hiqdev\php\billing\customer\CustomerFactoryInterface::class), 'plan' => \hiqdev\yii\compat\yii::referenceTo(\hiqdev\php\billing\plan\PlanFactoryInterface::class), 'price' => \hiqdev\yii\compat\yii::referenceTo(\hiqdev\php\billing\price\PriceFactoryInterface::class), 'sale' => \hiqdev\yii\compat\yii::referenceTo(\hiqdev\php\billing\sale\SaleFactoryInterface::class), 'target' => \hiqdev\yii\compat\yii::referenceTo(\hiqdev\php\billing\target\TargetFactoryInterface::class), 'type' => \hiqdev\yii\compat\yii::referenceTo(\hiqdev\php\billing\type\TypeFactoryInterface::class), ], 'remove keys' => new \Yiisoft\Composer\Config\Merger\Modifier\RemoveKeys(), ], ], \hiqdev\billing\hiapi\type\TypeSemantics::class, \hiapi\jsonApi\ResourceDocumentFactory::class => [ '__construct()' => [ 'resourceMap' => [ \Money\Money::class => \hiqdev\billing\hiapi\vo\MoneyResource::class, \hiqdev\php\units\QuantityInterface::class => \hiqdev\billing\hiapi\vo\QuantityResource::class, \hiqdev\php\units\UnitInterface::class => \hiqdev\billing\hiapi\vo\UnitResource::class, \hiqdev\php\billing\bill\BillInterface::class => \hiqdev\billing\hiapi\bill\BillResource::class, \hiqdev\php\billing\charge\ChargeInterface::class => \hiqdev\billing\hiapi\charge\ChargeResource::class, \hiqdev\php\billing\plan\PlanInterface::class => \hiqdev\billing\hiapi\plan\PlanResource::class, \hiqdev\php\billing\sale\SaleInterface::class => \hiqdev\billing\hiapi\sale\SaleResource::class, \hiqdev\php\billing\type\TypeInterface::class => \hiqdev\billing\hiapi\type\TypeResource::class, \hiqdev\php\billing\target\TargetInterface::class => \hiqdev\billing\hiapi\target\TargetResource::class, \hiqdev\php\billing\price\PriceInterface::class => \hiqdev\billing\hiapi\price\PriceResource::class, \hiqdev\php\billing\customer\CustomerInterface::class => \hiqdev\billing\hiapi\customer\CustomerResource::class, \hiqdev\php\billing\statement\Statement::class => \hiqdev\billing\hiapi\statement\StatementResource::class, \hiqdev\billing\hiapi\feature\FeatureInterface::class => \hiqdev\billing\hiapi\feature\FeatureResource::class, \hiqdev\billing\hiapi\plan\PlanReadModel::class => \hiqdev\billing\hiapi\plan\PlanReadModelResource::class, ], ], ], \hiapi\Core\Endpoint\EndpointRepository::class => [ '__construct()' => [ 'endpoints' => [ 'PlansSearch' => \hiqdev\billing\hiapi\plan\Search\BulkBuilder::class, 'PlanGetInfo' => \hiqdev\billing\hiapi\plan\GetInfo\Builder::class, 'TargetsSearch' => \hiqdev\billing\hiapi\target\Search\BulkBuilder::class, 'TargetGetInfo' => \hiqdev\billing\hiapi\target\GetInfo\Builder::class, 'TargetPurchase' => \hiqdev\billing\hiapi\target\Purchase\Builder::class, 'TargetsPurchase' => \hiqdev\billing\hiapi\target\Purchase\BulkBuilder::class, 'TargetCreate' => \hiqdev\billing\hiapi\target\Create\Builder::class, 'TargetsCreate' => \hiqdev\billing\hiapi\target\Create\BulkBuilder::class, 'TargetChangePlan' => \hiqdev\billing\hiapi\target\ChangePlan\Builder::class, 'FeaturePurchase' => \hiqdev\billing\hiapi\feature\Purchase\Builder::class, 'FeatureCancel' => \hiqdev\billing\hiapi\feature\Cancel\Builder::class, 'SalesSearch' => \hiqdev\billing\hiapi\sale\Search\BulkBuilder::class, 'SalesCount' => \hiqdev\billing\hiapi\sale\Search\CountBuilder::class, 'SaleCreate' => \hiqdev\billing\hiapi\sale\Create\Builder::class, 'SaleClose' => \hiqdev\billing\hiapi\sale\Close\SaleClose::class, 'BillsSearch' => \hiqdev\billing\hiapi\bill\Search\BulkBuilder::class, 'BillGetInfo' => \hiqdev\billing\hiapi\bill\GetInfo\Builder::class, 'StatementsSearch' => \hiqdev\billing\hiapi\statement\Search\BulkBuilder::class, 'StatementGetInfo' => \hiqdev\billing\hiapi\statement\GetInfo\Builder::class, 'ActionCalculate' => \hiqdev\billing\hiapi\action\Calculate\Builder::class, 'ActionsCalculate' => \hiqdev\billing\hiapi\action\Calculate\BulkBuilder::class, ], ], ], \Psr\Http\Message\ResponseFactoryInterface::class => \Laminas\Diactoros\ResponseFactory::class, \Yiisoft\Router\UrlGeneratorInterface::class => \hiapi\legacy\Http\Route\UrlGenerator::class, \hiqdev\billing\hiapi\target\ChangePlan\Strategy\PlanChangeStrategyProviderInterface::class => \hiqdev\billing\hiapi\target\ChangePlan\Strategy\PlanChangeStrategyProvider::class, ]; return class_exists(\Yiisoft\Factory\Definitions\Reference::class) ? $singletons : ['container' => ['singletons' => $singletons]]; <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\statement; use hiapi\jsonApi\AttributionBasedResource; use hiqdev\php\billing\statement\Statement; use hiqdev\php\billing\charge\ChargeInterface; use WoohooLabs\Yin\JsonApi\Schema\Relationship\ToManyRelationship; class StatementResource extends AttributionBasedResource { /** * @param Statement $entity */ public function getRelationships($entity): array { $res = array_merge(parent::getRelationships($entity), [ 'charges' => fn (Statement $po) => ToManyRelationship::create() ->setData($po->getCharges(), $this->getResourceFor(ChargeInterface::class)), ]); return $res; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature\Purchase; use DateTimeImmutable; use DomainException; use hiapi\Core\Auth\AuthRule; use hiqdev\billing\hiapi\feature\FeatureDto; use hiqdev\billing\hiapi\feature\FeatureServiceInterface; use hiqdev\billing\hiapi\feature\FeatureFactoryInterface; use hiqdev\billing\hiapi\feature\FeatureInterface; use hiqdev\billing\hiapi\feature\FeatureRepositoryInterface; use hiqdev\billing\hiapi\tools\PermissionCheckerInterface; use hiqdev\DataMapper\Query\Specification; use hiqdev\php\billing\target\TargetInterface; use hiqdev\php\billing\target\TargetRepositoryInterface; final class Action { private FeatureRepositoryInterface $featureRepository; private FeatureFactoryInterface $featureFactory; private TargetRepositoryInterface $targetRepository; private FeatureServiceInterface $featureService; private PermissionCheckerInterface $permissionChecker; public function __construct( FeatureFactoryInterface $featureFactory, FeatureRepositoryInterface $featureRepository, TargetRepositoryInterface $targetRepository, FeatureServiceInterface $featureService, PermissionCheckerInterface $permissionChecker ) { $this->featureRepository = $featureRepository; $this->featureFactory = $featureFactory; $this->targetRepository = $targetRepository; $this->featureService = $featureService; $this->permissionChecker = $permissionChecker; } public function __invoke(Command $command): FeatureInterface { $this->permissionChecker->ensureCustomerCan($command->customer, 'have-goods'); $dto = new FeatureDto(); $dto->type = $command->getType(); $dto->target = $command->getTarget(); $dto->starts = new DateTimeImmutable(); $dto->amount = $command->amount; $feature = $this->featureFactory->create($dto); $this->calculateExpirationTime($feature, $command->amount); $this->ensureCanBeEnabled($feature); $this->featureRepository->save($feature); $this->featureService->activate($feature); return $feature; } private function calculateExpirationTime(FeatureInterface $feature, $amount): void { $feature->setExpires( $this->featureService->calculateExpiration($feature, $amount) ); } private function ensureCanBeEnabled(FeatureInterface $feature): void { $existingFeature = $this->featureRepository->findUnique($feature); if ($existingFeature === null) { return; } if ($existingFeature->expires() === null && $feature->expires() !== null) { // Unlimited feature becomes limited return; } if ($feature->expires() !== null) { if ($existingFeature->expires() > $feature->expires()) { throw new DomainException(sprintf( "Feature '%s' is already active for the passed object '%s' and lasts longer. " . 'If you want to shorten existing feature, disable it and create a new one', $feature->type()->getName(), $feature->target()->getId(), )); } if ($existingFeature->expires() <= $feature->expires()) { throw new DomainException(sprintf( "Feature '%s' is already active for the passed object '%s'. " . 'If you want to renew existing feature, use a "renew" API endpoint', $feature->type()->getName(), $feature->target()->getId(), )); } } throw new DomainException(sprintf( "Feature '%s' is already active for the passed object '%s'", $feature->type()->getName(), $feature->target()->getId(), )); } private function createTarget(Command $command): TargetInterface { $spec = (new Specification())->where(['id' => $command->object_id]); $target = $this->targetRepository->findOne( AuthRule::currentUser()->applyToSpecification($spec) ); if ($target === false) { throw new DomainException(sprintf('Could not find object "%s"', $command->object_id)); } return $target; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\target\Purchase; use hiapi\commands\BaseCommand; use hiapi\validators\IdValidator; use hiapi\validators\UsernameValidator; use hiqdev\DataMapper\Validator\DateTimeValidator; use Throwable; use yii\validators\InlineValidator; class Command extends BaseCommand { public $customer_username; public $customer_id; public $plan_id; public $plan_name; public $plan_seller; public $name; public $type; /** * @var string ID of the service instance in the service provider's subsystem, * that uniquely identifies the object or service, being sold. */ public $remoteid; public $time; public $customer; public $plan; /** @var list<InitialUse> */ public $initial_uses = []; public function rules(): array { return [ [['customer_username'], UsernameValidator::class], [['customer_id'], IdValidator::class], [['plan_name'], 'trim'], [['plan_seller'], UsernameValidator::class], [['plan_id'], IdValidator::class], [['name'], 'trim'], [['type'], 'trim'], [['type'], 'required'], [['remoteid'], 'trim'], [['time'], DateTimeValidator::class], [['initial_uses'], function (string $attribute, ?array $params, InlineValidator $validator, $initial_uses) { if (!empty($initial_uses) && !is_array($initial_uses)) { $this->addError('initial_uses must be an array'); return; } foreach ($initial_uses as &$use) { $type = $use['type'] ?? null; $unit = $use['unit'] ?? null; $amount = $use['amount'] ?? null; if ($type === null || $unit === null || $amount === null) { $this->addError($attribute, 'Initial use MUST contain `type`, `unit` and `amount` properties'); return; } try { $use = InitialUse::fromScalar($type, $unit, $amount); } catch (Throwable $exception) { $this->addError($attribute, $exception->getMessage()); return; } } $this->initial_uses = $initial_uses; }, ], ]; } } <file_sep><?php namespace hiqdev\billing\hiapi\price; use hiqdev\php\billing\plan\Plan; class RatePriceHydrator extends PriceHydrator { /** * {@inheritdoc} * @param object|Plan $object */ public function extract($object): array { return array_merge( parent::extract($object), array_filter( [ 'prepaid' => $this->hydrator->extract($object->getPrepaid()), // 'price' => $this->hydrator->extract($object->getPrice()), ], static function ($value): bool { return $value !== null; }, ARRAY_FILTER_USE_BOTH ) ); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\target\Purchase; use hiqdev\php\billing\type\Type; use hiqdev\php\billing\type\TypeInterface; use hiqdev\php\units\Quantity; final class InitialUse { public TypeInterface $type; public Quantity $quantity; public function __construct(TypeInterface $type, Quantity $quantity) { $this->type = $type; $this->quantity = $quantity; } /** * @param string $type * @param string $unit * @param string $amount * @return static * @throw InvalidConfigException when passed $unit does not exist */ public static function fromScalar(string $type, string $unit, string $amount): self { return new self( new Type(TypeInterface::ANY, $type), Quantity::create($unit, $amount) ); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\vo; use hiapi\jsonApi\AttributionBasedResource; use hiqdev\php\units\QuantityInterface; class QuantityResource extends AttributionBasedResource { /** * @param QuantityInterface $entity */ public function getId($entity): string { return (string)$entity->getQuantity() . $entity->getUnit()->getName(); } public function getAttributes($entity): array { return [ 'quantity' => fn(QuantityInterface $po): string => (string) $po->getQuantity(), 'unit' => fn(QuantityInterface $po): string => (string) $po->getUnit()->getName(), ]; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\tests\unit\action; use DateTimeImmutable; use hiqdev\php\billing\action\UsageInterval; use hiqdev\yii\DataMapper\tests\unit\BaseHydratorTest; use Laminas\Hydrator\HydratorInterface; /** * Class UsageIntervalHydratorTest * * @author <NAME> <<EMAIL>> * @covers \hiqdev\billing\hiapi\action\UsageIntervalHydrator */ class UsageIntervalHydratorTest extends BaseHydratorTest { private HydratorInterface $hydrator; public function setUp(): void { $this->hydrator = $this->getHydrator(); } public function testHydration(): void { $interval = UsageInterval::withinMonth( $month = new DateTimeImmutable('2020-01-01'), new DateTimeImmutable('2020-01-24 22:11:00'), null ); $hydratedInterval = $this->hydrator->hydrate([ 'month' => $month->format(DATE_ATOM), 'start' => $interval->start()->format(DATE_ATOM), 'end' => $interval->end()->format(DATE_ATOM), ], UsageInterval::class); $this->assertInstanceOf(UsageInterval::class, $interval); $this->assertEquals($interval, $hydratedInterval); } public function testExtraction(): void { $interval = UsageInterval::withinMonth( $month = new DateTimeImmutable('2020-01-01'), new DateTimeImmutable('2020-01-24 22:11:00'), null ); $extracted = $this->hydrator->extract($interval); $this->assertSame([ 'start' => '2020-01-24T22:11:00+00:00', 'end' => '2020-02-01T00:00:00+00:00', 'seconds' => 611340, 'ratio' => 0.22824820788530467, 'seconds_in_month' => 2678400 ], $extracted); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\vo; use hiqdev\php\units\Quantity; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; /** * Quantity Hydrator. * * @author <NAME> <<EMAIL>> */ class QuantityHydrator extends GeneratedHydrator { public function hydrate(array $data, $object): object { return Quantity::create($data['unit'], $data['quantity']); } /** * {@inheritdoc} * @param object|Quantity $object */ public function extract($object): array { return [ 'unit' => $object->getUnit()->getName(), 'quantity' => $object->getQuantity(), ]; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\action\Calculate; use hiqdev\php\billing\action\ActionInterface; interface PaidCommandInterface { /** * @return ActionInterface[] */ public function getActions(): array; } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tools; use hiqdev\php\billing\bill\BillInterface; use hiqdev\php\billing\tools\MergerInterface; /** * @author <NAME> <<EMAIL>> */ class Merger implements MergerInterface { /** * @var MonthlyBillQuantityFixer */ private $monthlyBillQuantityFixer; /** * @var MergerInterface */ private $defaultMerger; public function __construct(MergerInterface $defaultMerger, MonthlyBillQuantityFixer $monthlyBillQuantityFixer) { $this->defaultMerger = $defaultMerger; $this->monthlyBillQuantityFixer = $monthlyBillQuantityFixer; } /** * {@inheritdoc} */ public function mergeBills(array $bills): array { $bills = $this->defaultMerger->mergeBills($bills); foreach ($bills as $bill) { $this->monthlyBillQuantityFixer->__invoke($bill); } return $bills; } public function mergeBill(BillInterface $first, BillInterface $other): BillInterface { return $this->defaultMerger->mergeBill($first, $other); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\customer; use hiqdev\php\billing\customer\Customer; use hiqdev\php\billing\customer\CustomerInterface; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; /** * Class CustomerHydrator. * * @author <NAME> <<EMAIL>> */ class CustomerHydrator extends GeneratedHydrator { /** * {@inheritdoc} * @param object|Customer $object */ public function hydrate(array $data, $object): object { if (!empty($data['seller'])) { $data['seller'] = $this->hydrator->hydrate($data['seller'], Customer::class); } return parent::hydrate($data, $object); } /** * {@inheritdoc} * @param object|Customer $object */ public function extract($object): array { return [ 'id' => $object->getId(), 'login' => $object->getLogin(), 'seller' => $object->getSeller() ? $this->hydrator->extract($object->getSeller()) : null, ]; } public function createEmptyInstance(string $className, array $data = []): object { if ($className === CustomerInterface::class) { $className = Customer::class; } return parent::createEmptyInstance($className, $data); } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\action\CheckCredit; use hiqdev\billing\hiapi\action\Calculate\PaidCommandInterface; use hiqdev\billing\hiapi\tools\CreditCheckerInterface; use League\Tactician\Middleware; use Laminas\Hydrator\HydratorInterface; class CheckCreditMiddleware implements Middleware { private CreditCheckerInterface $checker; public function __construct(CreditCheckerInterface $checker) { $this->checker = $checker; } /** * @param PaidCommandInterface $command * @param callable $next * @return mixed */ public function execute($command, callable $next) { $actions = $command->getActions(); $this->checker->check($actions); $this->reserveBalanceAmount(); return $next($command); } private function reserveBalanceAmount(): void { // TODO: mutex to prevent concurrent charges? } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\price; use hiqdev\php\billing\price\PriceCreationDto; /** * Class TemplatePriceDto. * * @author <NAME> <<EMAIL>> */ class RateTemplatePriceDto extends PriceCreationDto { } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\statement\GetInfo; use hiapi\commands\GetInfoCommand; use hiqdev\php\billing\statement\Statement; use hiapi\validators\RefValidator; use hiqdev\DataMapper\Query\Specification; class Command extends GetInfoCommand { public $month; public $customer_id; public function getMonth() { return $this->month; } public function getCustomerID() { return $this->customer_id; } public function rules() { return [ [['month'], 'date', 'format' => 'php:Y-m-d'], [['month'], 'filter', 'filter' => function($value) { return date("Y-m-01", strtotime($value)); }], [['month'], 'required'], [['customer_id'], 'integer', 'min' => 1], ['with', 'each', 'rule' => [RefValidator::class]], ]; } public function getEntityClass(): string { return Statement::class; } public function getSpecification(): Specification { $spec = new Specification(); $spec->where = array_filter([ 'month' => $this->month, 'customer_id' => $this->customer_id, ]); $spec->with = $this->with; return $spec; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tests\unit\target; use hiqdev\php\billing\target\Target; use hiqdev\yii\DataMapper\tests\unit\BaseHydratorTest; /** * @author <NAME> <<EMAIL>> */ class TargetHydratorTest extends BaseHydratorTest { const ID1 = 11111; const TYPE1 = 'server'; const NAME1 = 'name-11111'; const ID2 = 22222; const TYPE2 = 'certificate'; const NAME2 = 'name-22222'; protected $data = [ 'id' => self::ID1, 'type' => self::TYPE1, 'name' => self::NAME1, ]; public function setUp(): void { $this->hydrator = $this->getHydrator(); } public function testHydrateNew() { $obj = $this->hydrator->hydrate($this->data, Target::class); $this->checkValues($obj); } public function testHydrateOld() { $obj = new Target(self::ID2, self::TYPE2, self::NAME2); $this->hydrator->hydrate($this->data, $obj); $this->checkValues($obj); } public function checkValues($obj) { $this->assertInstanceOf(Target::class, $obj); $this->assertSame(self::ID1, $obj->getId()); $this->assertSame(self::TYPE1, $obj->getType()); $this->assertSame(self::NAME1, $obj->getName()); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tests\unit\customer; use hiqdev\php\billing\customer\Customer; use hiqdev\yii\DataMapper\tests\unit\BaseHydratorTest; /** * @author <NAME> <<EMAIL>> */ class CustomerHydratorTest extends BaseHydratorTest { const ID1 = 11111; const LOGIN1 = 'login11111'; const ID2 = 22222; const LOGIN2 = 'login22222'; protected $data = [ 'id' => self::ID1, 'login' => self::LOGIN1, 'seller' => [ 'id' => self::ID2, 'login' => self::LOGIN2, ], ]; public function setUp(): void { $this->hydrator = $this->getHydrator(); } public function testHydrateNew() { $obj = $this->hydrator->hydrate($this->data, Customer::class); $this->checkValues($obj); } public function testHydrateOld() { $obj = new Customer(self::ID2, self::LOGIN2); $this->hydrator->hydrate($this->data, $obj); $this->checkValues($obj); } public function checkValues($obj) { $this->assertInstanceOf(Customer::class, $obj); $this->assertSame(self::ID1, $obj->getId()); $this->assertSame(self::LOGIN1, $obj->getLogin()); $seller = $obj->getSeller(); $this->assertInstanceOf(Customer::class, $seller); $this->assertSame(self::ID2, $seller->getId()); $this->assertSame(self::LOGIN2, $seller->getLogin()); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature; use DateTimeImmutable; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\target\TargetInterface; use hiqdev\php\billing\type\TypeInterface; class FeatureDto { public $id; public $amount; public TypeInterface $type; public ?TargetInterface $target = null; public ?DateTimeImmutable $starts = null; } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING & ~E_STRICT & ~E_DEPRECATED); $autoload = __DIR__ . '/../vendor/autoload.php'; if (!file_exists($autoload)) { $autoload = __DIR__ . '/../../../autoload.php'; } require_once $autoload; require_once dirname($autoload) . '/yiisoft/yii2/Yii.php'; use yii\console\Application; use Yiisoft\Composer\Config\Builder; Yii::setAlias('@root', dirname(__DIR__)); Yii::$app = new Application(require Builder::path('common')); <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\plan; use hiapi\jsonApi\AttributionBasedResource; use hiqdev\php\billing\plan\PlanInterface; use hiqdev\php\billing\price\PriceInterface; use WoohooLabs\Yin\JsonApi\Schema\Relationship\ToManyRelationship; class PlanResource extends AttributionBasedResource { /** * @param PlanInterface $entity */ public function getRelationships($entity): array { return array_merge(parent::getRelationships($entity), [ 'prices' => fn (PlanInterface $po) => ToManyRelationship::create() ->setData($po->getPrices(), $this->getResourceFor(PriceInterface::class)), ]); } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2022, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\formula; use hiqdev\php\billing\charge\ChargeModifier; use hiqdev\php\billing\formula\FormulaEngine; use hiqdev\php\billing\formula\FormulaEngineInterface; use Laminas\Hydrator\Strategy\StrategyInterface; class FormulaHydrationStrategy implements StrategyInterface { /** * @var FormulaEngineInterface|FormulaEngine */ protected $formulaEngine; public function __construct(FormulaEngineInterface $formulaEngine) { $this->formulaEngine = $formulaEngine; } public function hydrate($value, ?array $data): object { return $this->formulaEngine->build($value); } /** * @param ChargeModifier $value * @param object|null $object * @return mixed */ public function extract($value, ?object $object = null) { throw new \LogicException('Not implemented'); } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tools; use hiqdev\billing\hiapi\action\Calculate\PaidCommandInterface; use hiqdev\php\billing\order\BillingInterface; use League\Tactician\Middleware; class PerformBillingMiddleware implements Middleware { public bool $checkCredit = true; private CreditCheckerInterface $creditChecker; private BillingInterface $billing; public function __construct(CreditCheckerInterface $creditChecker, BillingInterface $billing) { $this->creditChecker = $creditChecker; $this->billing = $billing; } /** * @param PaidCommandInterface $command * @param callable $next * @return mixed */ public function execute($command, callable $next) { $actions = $command->getActions(); if ($this->checkCredit) { $this->creditChecker->check($actions); } $this->reserveBalanceAmount(); $res = $next($command); $this->billing->perform($actions); return $res; } private function reserveBalanceAmount(): void { // TODO: mutex to prevent concurrent charges } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\plan\GetInfo; use hiqdev\billing\hiapi\plan\AvailableFor; use hiqdev\php\billing\plan\PlanRepositoryInterface; use yii\web\User; use hiqdev\php\billing\plan\Plan; final class Action { private PlanRepositoryInterface $repo; private User $user; public function __construct(PlanRepositoryInterface $repo, User $user) { $this->repo = $repo; $this->user = $user; } public function __invoke(Command $command): ?Plan { $spec = $command->getSpecification(); $spec->where[AvailableFor::CLIENT_ID_FIELD] = $this->user->getId(); $result = $this->repo->findOne($spec); if ($result === false) { return null; } return $result; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tests\unit\plan; use hiqdev\php\billing\plan\Plan; use hiqdev\php\billing\plan\PlanRepositoryInterface; use hiqdev\yii\DataMapper\tests\unit\BaseRepositoryTest; class PlanRepositoryTest extends BaseRepositoryTest { public function testDI() { $this->assertInstanceOf(PlanRepositoryInterface::class, $this->getRepo()); } protected function getRepo(): PlanRepositoryInterface { return $this->getRepository(Plan::class); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tools; use hiqdev\billing\hiapi\charge\Generalizer; use hiqdev\billing\hiapi\type\TypeSemantics; use hiqdev\php\billing\bill\BillInterface; use hiqdev\php\billing\charge\GeneralizerInterface; use hiqdev\php\units\Quantity; use hiqdev\php\units\QuantityInterface; use hiqdev\php\units\Unit; /** * Normally, when multiple charges are put in the single bill, the bill quantity * increases accordingly. But it's not the right scenario for monthly bills: all * the charges are for the month quantity, but the whole bill is for one month as well. * * Class MonthlyBillQuantityFixer is applicable only for monthly bills and * adjusts the quantity of monthly bills according to the number of days in month. * * @author <NAME> <<EMAIL>> */ final class MonthlyBillQuantityFixer { /** * @var Generalizer */ private $generalizer; /** * @var TypeSemantics */ private $typeSemantics; public function __construct( GeneralizerInterface $generalizer, TypeSemantics $typeSemantics ) { $this->generalizer = $generalizer; $this->typeSemantics = $typeSemantics; } /** * @param BillInterface $bill */ public function __invoke($bill): void { if ($this->typeSemantics->isMonthly($bill->getType())) { $bill->setQuantity($this->calculateMonthlyQuantity($bill)); } } private function calculateMonthlyQuantity(BillInterface $bill): QuantityInterface { $res = null; foreach ($bill->getCharges() as $charge) { $amount = $this->generalizer->generalizeQuantity($charge); if (!$amount->getUnit()->isConvertible(Unit::items())) { continue; } if ($amount === $charge->getUsage()) { /** * If the amount was NOT generalized, if should not affect the result. * * Usually, the charge quantity could not be generalized when the bill * being processing is loaded from the DBMS and does not contain all the * relations, required for quantity generalization. */ continue; } if ($res === null || $amount->compare($res) > 0) { $res = $amount; } } return $res ?? Quantity::create('items', 1); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\target\ChangePlan\Strategy; use DateTimeImmutable; use hiqdev\php\billing\Exception\ConstraintException; use hiqdev\php\billing\sale\SaleInterface; interface PlanChangeStrategyInterface { public function calculateTimeInPreviousSalePeriod(SaleInterface $activeSale, DateTimeImmutable $desiredCloseTime): DateTimeImmutable; /** * Checks, whether the passed $activeSale can be closed at the passed $desiredCloseTime. * This method should be used only in the plan change workflow. * * @param SaleInterface $activeSale * @param DateTimeImmutable $desiredCloseTime * @throws ConstraintException when the sale can not be closed at the passed time */ public function ensureSaleCanBeClosedForChangeAtTime(SaleInterface $activeSale, DateTimeImmutable $desiredCloseTime): void; } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tests\support\order; use hiqdev\billing\hiapi\charge\Generalizer; use hiqdev\billing\hiapi\type\TypeSemantics; use hiqdev\php\billing\charge\GeneralizerInterface; class SimpleCalculator extends \hiqdev\php\billing\tests\support\order\SimpleCalculator { public function __construct(GeneralizerInterface $generalizer = null, $sale = null, $plan = null) { $generalizer = $generalizer ?: new Generalizer(new TypeSemantics()); return parent::__construct($generalizer, $sale, $plan); } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\plan; use hiapi\exceptions\domain\RequiredInputException; use hiapi\exceptions\domain\ValidationException; use hiqdev\DataMapper\Query\Specification; use hiqdev\php\billing\plan\PlanInterface; use hiqdev\php\billing\plan\PlanRepositoryInterface; use League\Tactician\Middleware; class PlanLoader implements Middleware { private PlanRepositoryInterface $repo; public bool $isRequired = false; public function __construct(PlanRepositoryInterface $repo) { $this->repo = $repo; } public function execute($command, callable $next) { if (empty($command->plan)) { $command->plan = $this->findPlanByCommand($command); $this->validatePlan($command); } return $next($command); } public function findPlanByCommand($command): ?PlanInterface { if (!empty($command->plan_id)) { $availabilityFilter = [AvailableFor::CLIENT_ID_FIELD => $command->customer->getId()]; return $this->findPlanById($command->plan_id, $availabilityFilter); } if (!empty($command->plan_name)) { return $this->findPlanByName($command->plan_name, $command->plan_seller ?? $this->getSeller($command)) ?? $this->findPlanByName($command->plan_name, $command->customer->getLogin()); } if (!empty($command->plan_fullname)) { return $this->findPlanByFullName($command->plan_fullname); } return null; } private function findPlanById($id, array $availabilityFilter) { return $this->findPlanByArray($availabilityFilter + ['id' => $id]); } private function findPlanByFullName($fullname) { $ps = explode('@', $fullname, 2); if (empty($ps[1])) { return null; } return $this->findPlanByName($ps[0], $ps[1]); } private function findPlanByName($name, $seller) { return $this->findPlanByArray([ 'name' => $name, 'seller' => $seller, AvailableFor::SELLER_FIELD => $seller, ]); } private function findPlanByArray(array $cond) { return $this->repo->findOne((new Specification)->with('prices')->where($cond)) ?: null; } private function getSeller($command): ?string { return $command->customer->getSeller()->getLogin(); } private function validatePlan($command): void { if (!$this->isRequired || !empty($command->plan)) { return; } if (!empty($command->plan_id)) { throw new ValidationException( sprintf('Failed to find plan by ID %s: wrong ID or not authorized', $command->plan_id) ); } if (!empty($command->plan_name)) { throw new ValidationException( sprintf('Failed to find plan by name "%s": wrong name or not authorized', $command->plan_name) ); } throw new RequiredInputException('plan_id or plan_name'); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\bill; use hiqdev\billing\hiapi\customer\CustomerAttribution; use hiqdev\billing\hiapi\plan\PlanAttribution; use hiqdev\billing\hiapi\target\TargetAttribution; use hiqdev\billing\hiapi\type\TypeAttribution; use hiqdev\billing\hiapi\vo\MoneyAttribution; use hiqdev\billing\hiapi\vo\QuantityAttribution; use hiqdev\DataMapper\Attribute\DateTimeAttribute; use hiqdev\DataMapper\Attribute\IntegerAttribute; use hiqdev\DataMapper\Attribute\StringAttribute; use hiqdev\DataMapper\Attribution\AbstractAttribution; class BillAttribution extends AbstractAttribution { public function attributes() { return [ 'id' => IntegerAttribute::class, 'time' => DateTimeAttribute::class, 'comment' => StringAttribute::class, ]; } public function relations() { return [ 'type' => TypeAttribution::class, 'target' => TargetAttribution::class, 'customer' => CustomerAttribution::class, 'plan' => PlanAttribution::class, 'sum' => MoneyAttribution::class, 'quantity' => QuantityAttribution::class, ]; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\type; use hiqdev\php\billing\type\Type; use hiqdev\php\billing\type\TypeInterface; final class TypeSemantics { private const MONTHLY = 'monthly'; private const OVERUSE = 'overuse'; private const DISCOUNT = 'discount'; private const DEPOSIT = 'deposit'; private const HARDWARE = 'hardware'; private const NOT_ALLOWED_GENERALIZE_ITEMS = [ 'storage', 'private_cloud', 'volume_du', 'cdn_cache', 'cdn_traf_max', 'cdn_traf95_max', 'vps', ]; private const ONCE_PER_MONTH_TYPES = [ 'certificate,certificate_purchase', 'certificate,certificate_renewal', 'domain,dregistration', 'domain,drenewal', 'domain,dtransfer', 'feature,premium_dns_purchase', 'feature,premium_dns_renew', 'feature,whois_protect_purchase', 'feature,whois_protect_renew', ]; /** * // TODO: Probably not the best place for this method */ public function createMonthlyType(): TypeInterface { return new Type(null, self::MONTHLY . ',' . self::MONTHLY); } public function isMonthly(TypeInterface $type): bool { return $this->groupName($type) === self::MONTHLY; } public function isSwapToMonthlyAllowed(TypeInterface $type): bool { return $this->isMonthly($type) && !in_array($this->localName($type), self::NOT_ALLOWED_GENERALIZE_ITEMS, true); } public function isOncePerMonth(TypeInterface $type): bool { return in_array($type->getName(), self::ONCE_PER_MONTH_TYPES, true); } public function isHardware(TypeInterface $type): bool { return $this->localName($type) === self::HARDWARE; } public function isDiscount(TypeInterface $type): bool { return $this->groupName($type) === self::DISCOUNT; } public function isOveruse(TypeInterface $type): bool { return $this->groupName($type) === self::OVERUSE; } public function isDeposit(TypeInterface $type): bool { return $this->groupName($type) === self::DEPOSIT; } public function groupName(TypeInterface $type): string { $name = $type->getName(); if (strpos($name, ',') !== false) { [$name,] = explode(',', $name, 2); } return $name; } public function localName(TypeInterface $type): string { $name = $type->getName(); if (strpos($name, ',') !== false) { [,$name] = explode(',', $name, 2); } return $name; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\target\Create; use hiapi\commands\BaseCommand; use hiapi\validators\IdValidator; use hiapi\validators\UsernameValidator; use hiqdev\php\billing\customer\Customer; final class Command extends BaseCommand { /** * @var string|null a customer ID, when command is running on behalf of other user. * Either `customer_id` or `customer_username` can be filled. */ public $customer_id; /** * @var string|null a customer ID, when command is running on behalf of other user. * Either `customer_id` or `customer_username` can be filled. */ public $customer_username; /** @var string a target name */ public $name; /** @var string a target type */ public $type; /** @var string a target ID at the remote service */ public $remoteid; /** @var Customer a customer */ public $customer; public function rules(): array { return [ [['customer_username'], UsernameValidator::class], [['customer_id'], IdValidator::class], [['name'], 'trim'], [['type'], 'trim'], [['remoteid'], 'trim'], [['name', 'type', 'remoteid'], 'required'], ]; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\charge; use hiqdev\php\billing\charge\ChargeInterface; use hiapi\jsonApi\AttributionBasedResource; class ChargeResource extends AttributionBasedResource { /** * @param ChargeInterface $entity */ public function getRelationships($entity): array { $res = parent::getRelationships($entity); // XXX temp because of Maximum nesting function level in woohoolabs/yin // TODO remove after fixing unset($res['bill']); return $res; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tests\unit\charge; use hiqdev\billing\hiapi\charge\Generalizer; use hiqdev\billing\hiapi\type\TypeSemantics; use hiqdev\php\billing\action\Action; use hiqdev\php\billing\order\Order; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\tools\Aggregator; use hiqdev\php\billing\type\Type; use hiqdev\php\units\Quantity; class AggregatorTest extends \hiqdev\php\billing\tests\unit\tools\AggregatorTest { /** @var Aggregator */ protected $aggregator; public function setUp(): void { parent::setUp(); $this->aggregator = new Aggregator(new Generalizer(new TypeSemantics()), new TypeSemantics()); } public function testMonthlyChargesQuantityIsNotSummarized() { $this->markTestIncomplete('Test is strictly bound to certificate plan. TODO: implement for server'); $actions = [ new Action( null, new Type(null, 'monthly,monthly'), new Target(Target::ANY, 'server'), Quantity::items(0.25), $this->plan->customer, new \DateTimeImmutable() ), new Action( null, new Type(null, 'monthly,monthly'), new Target(Target::ANY, 'server'), Quantity::items(1), $this->plan->customer, new \DateTimeImmutable() ), ]; $order = new Order(null, $this->plan->customer, $actions); $charges = $this->calculator->calculateOrder($order); // TODO: aggregate bills from charges // TODO: Check bill quantity is not summarized } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\usage; use hiqdev\billing\hiapi\target\TargetAttribution; use hiqdev\billing\hiapi\type\TypeAttribution; use hiqdev\billing\hiapi\vo\QuantityAttribution; use hiqdev\DataMapper\Attribution\AbstractAttribution; class UsageAttribution extends AbstractAttribution { public function attributes() { return []; } public function relations() { return [ 'target' => TargetAttribution::class, 'type' => TypeAttribution::class, 'amount' => QuantityAttribution::class, ]; } } <file_sep><?php namespace hiqdev\billing\hiapi\feature; use DateTimeImmutable; interface FeatureServiceInterface { /** * @param FeatureInterface $feature * @param int|float|string $periodsNumber the number of periods expiration must be calculated for * @return DateTimeImmutable|null */ public function calculateExpiration(FeatureInterface $feature, $periodsNumber): ?DateTimeImmutable; /** * @param FeatureInterface $feature * @return mixed */ public function activate(FeatureInterface $feature); } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\price; use hiqdev\php\billing\plan\PlanInterface; use hiqdev\php\billing\price\SinglePrice; use hiqdev\php\billing\target\TargetInterface; use hiqdev\php\billing\type\TypeInterface; use hiqdev\php\units\QuantityInterface; use Money\Money; /** * Class TemplateRatePrice. * * @author <NAME> <<EMAIL>> */ class RateTemplatePrice extends SinglePrice { /** * @var float */ protected float $rate; public function __construct( $id, TypeInterface $type, TargetInterface $target, PlanInterface $plan = null, QuantityInterface $prepaid, Money $price, float $rate ) { parent::__construct($id, $type, $target, $plan, $prepaid, $price); $this->rate = $rate; } /** * @return float */ public function getRate(): float { return $this->rate; } } <file_sep># BILLING TESTING ## General idea We have tests of different levels: - unit tests for in-class functionality (done in every package) - BDD-tests for charges calculation for all expected cases (done in [php-billing] and specific billing implementations) - PACTs for API interactions - acceptance tests for billing is really properly calculated for manually created cases ## Acceptance tests - insert all the needed billing data: - customers and targets - with DB-migrations - all billable targets to be covered! - plans, sales and resource consumption - through API (tests API) - all used plan types to be covered! - check everything is calculated properly - check ad-hoc calculations - through API - run billing calculation - throuh CLI (in prod run with CRON) - compare calculated values - get bills and charges - through API - compare with precalculated values - clean - through API or DB - no need to clean customers and targets - repeat - profit [php-billing]: https://github.com/hiqdev/php-billing <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\statement; use hiqdev\billing\hiapi\Hydrator\Helper\DateTimeImmutableFormatterStrategyHelper; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; use hiqdev\php\billing\customer\CustomerInterface; use hiqdev\php\billing\statement\StatementBillInterface; use hiqdev\php\billing\statement\Statement; use hiqdev\php\billing\plan\PlanInterface; use Money\Money; /** * Statement Hydrator. * * @author <NAME> <<EMAIL>> */ class StatementHydrator extends GeneratedHydrator { public function __construct() { $this->addStrategy('time', DateTimeImmutableFormatterStrategyHelper::create()); $this->addStrategy('month', DateTimeImmutableFormatterStrategyHelper::create()); } /** * {@inheritdoc} * @param object|Statement $object */ public function hydrate(array $row, $object) { $row['time'] = $this->hydrateValue('time', $row['time']); $row['balance'] = $this->hydrator->create($row['balance'], Money::class); $row['customer'] = $this->hydrator->create($row['customer'], CustomerInterface::class); $row['month'] = $this->hydrateValue('month', $row['month']); $row['total'] = $this->hydrator->create($row['total'], Money::class); $row['payment'] = $this->hydrator->create($row['payment'], Money::class); $row['amount'] = $this->hydrator->create($row['amount'], Money::class); $raw_bills = $row['bills']; $raw_plans = $row['plans'] ?? []; unset($row['bills'], $row['plans']); /** @var Statement $statement */ $statement = parent::hydrate($row, $object); if (\is_array($raw_bills)) { $bills = []; foreach ($raw_bills as $key => $bill) { if (! $bill instanceof StatementBillInterface) { $bill = $this->hydrator->hydrate($bill, StatementBillInterface::class); } $bills[$key] = $bill; } $statement->setBills($bills); } if (\is_array($raw_plans)) { $plans = []; foreach ($raw_plans as $key => $plan) { if (! $plan instanceof PlanInterface) { $plan = $this->hydrator->hydrate($bill, PlanInterface::class); } $plans[$key] = $plan; } $statement->setPlans($plans); } return $statement; } /** * {@inheritdoc} * @param object|Statement $object */ public function extract($object): array { return array_filter([ 'customer' => $this->hydrator->extract($object->getCustomer()), 'period' => $object->getPeriod(), 'time' => $this->extractValue('time', $object->getTime()), 'balance' => $this->hydrator->extract($object->getBalace()), 'month' => $this->extractValue('month', $object->getMonth()), 'total' => $this->hydrator->extract($object->getTotal()), 'payment' => $this->hydrator->extract($object->getPayment()), 'amount' => $this->hydrator->extract($object->getAmount()), 'bills' => $this->hydrator->extractAll($object->getBills()), 'plans' => $this->hydrator->extractAll($object->getPlans()), ], static function ($value): bool { return $value !== null; }, ARRAY_FILTER_USE_BOTH); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ use hiapi\Core\Http\Psr15\RequestHandler; use hiapi\Core\Http\Psr7\Response\FatResponse; use hiqdev\yii\compat\yii; use Laminas\Diactoros\ServerRequest; use Laminas\Diactoros\ServerRequestFactory; use Laminas\HttpHandlerRunner\Emitter\SapiEmitter; use Laminas\HttpHandlerRunner\RequestHandlerRunner; (static function () { ini_set('error_reporting', (string) (E_ALL ^ E_NOTICE)); define('APP_TYPE', 'web'); require_once __DIR__ . '/../config/bootstrap.php'; $container = yii::getContainer(); $runner = new RequestHandlerRunner( $container->get(RequestHandler::class), $container->get(SapiEmitter::class), static function (): ServerRequest { return ServerRequestFactory::fromGlobals(); }, static function (Throwable $e) { return FatResponse::create($e); } ); $runner->run(); })(); <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature; interface FeatureFactoryInterface { public function create(FeatureDto $dto): FeatureInterface; } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\charge; use hiqdev\php\billing\charge\ChargeState; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; /** * ChargeState Hydrator. * * @author <NAME> <<EMAIL>> */ class ChargeStateHydrator extends GeneratedHydrator { public function hydrate(array $data, $object): object { return ChargeState::fromString($data['state'] ?? reset($data)); } /** * {@inheritdoc} * @param ChargeState $object */ public function extract($object) { return $object->getName(); } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\statement\GetInfo; use hiapi\Core\Auth\AuthRule; use hiqdev\php\billing\statement\StatementRepositoryInterface; use hiqdev\php\billing\statement\Statement; final class Action { private StatementRepositoryInterface $repo; public function __construct(StatementRepositoryInterface $repo) { $this->repo = $repo; } public function __invoke(Command $command): ?Statement { $res = $this->repo->findOne( AuthRule::currentUser()->applyToSpecification($command->getSpecification()) ); return $res ?: null; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\plan; use hiqdev\php\billing\plan\PlanCreationDto; class PlanFactory extends \hiqdev\php\billing\plan\PlanFactory { public function create(PlanCreationDto $dto) { return $this->createAnyPlan($dto, $dto->is_grouping ? GroupingPlan::class : null); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\usage; use hiapi\jsonApi\AttributionBasedResource; class UsageResource extends AttributionBasedResource { } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\target; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\target\TargetCreationDto; use hiqdev\php\billing\target\TargetFactoryInterface; use hiqdev\php\units\exceptions\InvalidConfigException; class TargetFactory implements TargetFactoryInterface { protected array $classmap; protected string $defaultClass; public function __construct(array $classmap = [], string $defaultClass = Target::class) { $this->classmap = $classmap; $this->defaultClass = $defaultClass; } public function getEntityClassName(): string { return Target::class; } public function create(TargetCreationDto $dto): ?Target { if (!isset($dto->type)) { $class = Target::class; } else { $class = $this->getClassForType($dto->type); $dto->type = $this->shortenType($dto->type); } $target = new $class($dto->id, $dto->type, $dto->name); if ($target instanceof RemoteTarget) { $this->initRemoteTarget($target, $dto); } return $target; } // XXX tmp solution TODO redo better protected function initRemoteTarget($target, TargetCreationDto $dto): void { if (!empty($dto->customer)) { $target->customer = $dto->customer; } if (!empty($dto->remoteid)) { $target->remoteid = $dto->remoteid; } } /** * {@inheritdoc} */ public function shortenType(string $type): string { return $this->parseType($type)[0]; } protected function parseType(string $type): array { if (strpos($type, '.') !== false) { return explode('.', $type, 2); } return [$type, '*']; } /** * {@inheritdoc} */ public function getClassForType(string $type): string { [$type, $subtype] = $this->parseType($type); $class = $this->classmap[$type][$subtype] ?? $this->classmap[$type]['*'] ?? $this->defaultClass; if (empty($class)) { throw new InvalidConfigException("No class for type '$type'"); } return $class; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\sale\Create; use hiapi\commands\BaseCommand; use hiapi\validators\IdValidator; use hiapi\validators\RefValidator; use hiapi\validators\UsernameValidator; use hiqdev\DataMapper\Validator\DateTimeValidator; class Command extends BaseCommand { public $customer_id; public $customer_username; public $plan_id; public $plan_name; public $plan_seller; public $plan_fullname; public $target_id; public $target_name; public $target_type; public $target_fullname; public $time; public $customer; public $plan; public $target; public function rules(): array { return [ [['customer_id'], IdValidator::class], [['customer_username'], UsernameValidator::class], [['plan_id'], IdValidator::class], [['plan_name'], RefValidator::class], [['plan_seller'], UsernameValidator::class], [['plan_fullname'], 'string'], [['target_id'], IdValidator::class], [['target_type'], RefValidator::class], [['target_name'], RefValidator::class], [['target_fullname'], 'string'], [['time'], DateTimeValidator::class], ]; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\plan; class PlanReadModelResource extends PlanResource { } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\price; use hiqdev\php\billing\plan\Plan; /** * SinglePrice Hydrator. * * @author <NAME> <<EMAIL>> */ class SinglePriceHydrator extends PriceHydrator { /** * {@inheritdoc} * @param object|Plan $object */ public function extract($object): array { return array_merge(parent::extract($object), array_filter([ 'prepaid' => $this->hydrator->extract($object->getPrepaid()), 'price' => $this->hydrator->extract($object->getPrice()), ], static function ($value): bool { return $value !== null; }, ARRAY_FILTER_USE_BOTH)); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\sale\Close; use hiapi\exceptions\domain\RequiredInputException; use hiqdev\php\billing\sale\SaleRepositoryInterface; use hiqdev\php\billing\plan\Plan; use hiqdev\php\billing\sale\Sale; use DomainException; class SaleCloseAction { private SaleRepositoryInterface $repo; public function __construct(SaleRepositoryInterface $repo) { $this->repo = $repo; } public function __invoke(SaleCloseCommand $command): Sale { $this->checkRequiredInput($command); $sale = new Sale( null, $command->target, $command->customer, new Plan($command->plan?->getId(), null) ); $saleId = $this->repo->findId($sale); if (!$saleId) { throw new DomainException("Sale does not exists"); } $sale = $this->repo->findById($saleId); $sale->close($command->time); $this->repo->save($sale); return $sale; } protected function checkRequiredInput(SaleCloseCommand $command) { if (empty($command->customer)) { throw new RequiredInputException('customer'); } if (empty($command->target)) { throw new RequiredInputException('target'); } } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\usage; use hiapi\jsonApi\AttributionBasedSingleResourceDocument; class UsageDocument extends AttributionBasedSingleResourceDocument { } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\sale; use hiapi\jsonApi\AttributionBasedResource; class SaleResource extends AttributionBasedResource { } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\plan; use hiqdev\php\billing\plan\Plan; class PlanReadModel extends Plan { public array $customAttributes = []; } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\charge; use hiqdev\DataMapper\Attribution\AbstractAttribution; use hiqdev\DataMapper\Attribute\IntegerAttribute; use hiqdev\billing\hiapi\type\TypeAttribution; use hiqdev\billing\hiapi\target\TargetAttribution; use hiqdev\billing\hiapi\action\ActionAttribution; use hiqdev\billing\hiapi\price\PriceAttribution; use hiqdev\billing\hiapi\vo\QuantityAttribution; use hiqdev\billing\hiapi\vo\MoneyAttribution; use hiqdev\billing\hiapi\bill\BillAttribution; class ChargeAttribution extends AbstractAttribution { public function attributes() { return [ 'id' => IntegerAttribute::class, ]; } public function relations() { return [ 'type' => TypeAttribution::class, 'target' => TargetAttribution::class, 'action' => ActionAttribution::class, 'price' => PriceAttribution::class, 'usage' => QuantityAttribution::class, 'sum' => MoneyAttribution::class, 'bill' => BillAttribution::class, 'parent' => self::class, ]; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\vo; use hiapi\jsonApi\AttributionBasedResource; use hiqdev\php\units\UnitInterface; class UnitResource extends AttributionBasedResource { /** * @param UnitInterface $entity */ public function getId($entity): string { return (string)$entity->getName(); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature; use hiqdev\DataMapper\Query\Specification; use hiqdev\DataMapper\Repository\RepositoryInterface; /** * Interface FeatureRepositoryInterface * * @author <NAME> <<EMAIL>> * * @todo Should it extend RepositoryInterface? */ interface FeatureRepositoryInterface extends RepositoryInterface { /** * @param Specification $specification * @return false|Feature */ public function findOne(Specification $specification); /** * Finds the $feature in DBMS by the unique constraints * * @param FeatureInterface $feature * @return FeatureInterface|null */ public function findUnique(FeatureInterface $feature): ?FeatureInterface; } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\target\ChangePlan; use DateTimeImmutable; use hiqdev\billing\mrdp\Sale\HistoryAndFutureSaleRepository; use hiqdev\DataMapper\Query\Specification; use hiqdev\php\billing\customer\CustomerInterface; use hiqdev\php\billing\sale\SaleInterface; use hiqdev\php\billing\target\TargetInterface; class ActiveSaleFinder { public function __construct(protected readonly HistoryAndFutureSaleRepository $saleRepository) { } public function __invoke( TargetInterface $target, CustomerInterface $customer, DateTimeImmutable $time ): ?SaleInterface { $spec = (new Specification())->where([ 'seller-id' => $customer->getSeller()?->getId(), 'target-id' => $target->getId(), ]); /** @var SaleInterface|false $sale */ $sale = $this->saleRepository->findOneAsOfDate($spec, $time); if ($sale === false) { return null; } return $sale; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ return [ 'controllerNamespace' => 'hiqdev\\billing\\hiapi\\controllers', ]; <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ use hiqdev\php\billing\price\SinglePrice; use hiqdev\php\billing\target\Target; return [ 'billing-hiapi.price.types' => [], 'billing-hiapi.price.defaultClass' => SinglePrice::class, 'billing-hiapi.target.classmap' => [], 'billing-hiapi.target.defaultClass' => Target::class, ]; <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tools; use hiqdev\php\billing\bill\BillInterface; use hiqdev\php\billing\tools\MergerInterface; /** * Class GroupByClientMerger merges bills by the buyer. * * Could be used to get totals by client in a list of bills. * * @author <NAME> <<EMAIL>> */ final class GroupByClientMerger implements MergerInterface { private const CUSTOMER_UNKNOWN = 'guest'; /** * @var MergerInterface */ private $defaultMerger; /** * @var MonthlyBillQuantityFixer */ private $monthlyBillQuantityFixer; public function __construct(MergerInterface $defaultMergingStrategy, MonthlyBillQuantityFixer $monthlyBillQuantityFixer) { $this->defaultMerger = $defaultMergingStrategy; $this->monthlyBillQuantityFixer = $monthlyBillQuantityFixer; } /** * Merges array of bills. * @param BillInterface[] $bills * @return BillInterface[] */ public function mergeBills(array $bills): array { $res = []; foreach ($bills as $bill) { $buyer = $bill->getCustomer()->getUniqueId() ?? self::CUSTOMER_UNKNOWN; if (empty($res[$buyer])) { $res[$buyer] = $bill; } else { $res[$buyer] = $this->mergeBill($res[$buyer], $bill); } } return $res; } /** * Merges two bills in one. */ public function mergeBill(BillInterface $first, BillInterface $other): BillInterface { $bill = $this->defaultMerger->mergeBill($first, $other); $this->monthlyBillQuantityFixer->__invoke($bill); return $bill; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\action; use hiqdev\php\billing\action\ActionState; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; /** * ActionState Hydrator. * * @author <NAME> <<EMAIL>> */ class ActionStateHydrator extends GeneratedHydrator { public function hydrate(array $data, $object): object { return ActionState::fromString($data['state'] ?? reset($data)); } /** * @param ActionState $object */ public function extract($object): array { return ['name' => $object->getName()]; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tests\unit\price; use hiqdev\php\billing\price\EnumPrice; use hiqdev\php\billing\price\PriceInterface; use hiqdev\php\billing\price\SinglePrice; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\type\Type; use hiqdev\php\units\Quantity; use hiqdev\php\units\Unit; use hiqdev\yii\DataMapper\tests\unit\BaseHydratorTest; use Money\Currency; use Money\Money; use yii\helpers\Json; /** * @author <NAME> <<EMAIL>> */ class PriceHydratorTest extends BaseHydratorTest { const ID1 = '11111'; const CUR1 = 'USD'; const NAME1 = 'name-11111'; const TYPE1 = 'server'; const UNIT1 = 'MB'; const ID2 = '22222'; const CUR2 = 'EUR'; const NAME2 = 'certificate_purchase'; const TYPE2 = 'certificate'; const UNIT2 = 'GB'; protected $dataSinglePrice = [ 'id' => self::ID1, 'type' => [ 'id' => self::ID1, 'name' => self::NAME1, ], 'target' => [ 'id' => self::ID1, 'type' => self::TYPE1, 'name' => self::NAME1, ], 'prepaid' => [ 'quantity' => self::ID1, 'unit' => self::UNIT1, ], 'price' => [ 'amount' => self::ID1, 'currency' => self::CUR1, ], ]; protected $dataEnumPrice = [ 'id' => self::ID2, 'type' => [ 'id' => self::ID2, 'name' => self::NAME2, ], 'target' => [ 'id' => self::ID2, 'type' => self::TYPE2, 'name' => self::NAME2, ], 'prepaid' => [ 'unit' => self::UNIT2, ], 'price' => [ 'currency' => self::CUR2, ], ]; protected $sums = [ 1 => self::ID1, 2 => self::ID2, ]; public function setUp(): void { $this->hydrator = $this->getHydrator(); $this->dataEnumPrice['data'] = Json::encode(['sums' => $this->sums]); } public function testHydrateNewSinglePrice() { $obj = $this->hydrator->hydrate($this->dataSinglePrice, PriceInterface::class); $this->checkSinglePrice($obj); } public function testHydrateExistingSinglePrice() { $type = new Type(self::ID2, self::NAME2); $target = new Target(self::ID2, self::TYPE2, self::NAME2); $price = new Money(self::ID2, new Currency(self::CUR2)); $prepaid = Quantity::create(self::ID2, Unit::create(self::UNIT2)); $obj = new SinglePrice(self::ID2, $type, $target, null, $prepaid, $price); $this->hydrator->hydrate($this->dataSinglePrice, $obj); $this->checkSinglePrice($obj); } public function checkSinglePrice($obj) { $this->assertInstanceOf(SinglePrice::class, $obj); $this->assertSame(self::ID1, $obj->getId()); $type = $obj->getType(); $this->assertInstanceOf(Type::class, $type); $this->assertSame(self::ID1, $type->getId()); $this->assertSame(self::NAME1, $type->getName()); $target = $obj->getTarget(); $this->assertInstanceOf(Target::class, $target); $this->assertSame(self::ID1, $target->getId()); $this->assertSame(self::TYPE1, $target->getType()); $this->assertSame(self::NAME1, $target->getName()); $prepaid = $obj->getPrepaid(); $this->assertInstanceOf(Quantity::class, $prepaid); $this->assertSame(self::ID1, $prepaid->getQuantity()); $this->assertSame(self::UNIT1, $prepaid->getUnit()->getName()); $price = $obj->getPrice(); $this->assertInstanceOf(Money::class, $price); $this->assertSame(self::ID1, $price->getAmount()); $this->assertSame(self::CUR1, $price->getCurrency()->getCode()); } public function testHydrateNewEnumPrice() { $obj = $this->hydrator->hydrate($this->dataEnumPrice, PriceInterface::class); $this->checkEnumPrice($obj); } public function testHydrateExistingEnumPrice() { $type = new Type(self::ID2, self::NAME2); $target = new Target(self::ID2, self::TYPE2, self::NAME2); $currency = new Currency(self::CUR2); $unit = Unit::create(self::UNIT2); $sums = array_reverse($this->sums); $obj = new EnumPrice(self::ID2, $type, $target, null, $unit, $currency, $sums); $this->hydrator->hydrate($this->dataEnumPrice, $obj); $this->checkEnumPrice($obj); } public function checkEnumPrice($obj) { $this->assertInstanceOf(EnumPrice::class, $obj); $this->assertSame(self::ID2, $obj->getId()); $this->assertSame($this->sums, $obj->getSums()); $type = $obj->getType(); $this->assertInstanceOf(Type::class, $type); $this->assertSame(self::ID2, $type->getId()); $this->assertSame(self::NAME2, $type->getName()); $target = $obj->getTarget(); $this->assertInstanceOf(Target::class, $target); $this->assertSame(self::ID2, $target->getId()); $this->assertSame(self::TYPE2, $target->getType()); $this->assertSame(self::NAME2, $target->getName()); $unit = $obj->getUnit(); $this->assertInstanceOf(Unit::class, $unit); $this->assertSame(self::UNIT2, $unit->getName()); $currency = $obj->getCurrency(); $this->assertInstanceOf(Currency::class, $currency); $this->assertSame(self::CUR2, $currency->getCode()); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature; use DateTimeImmutable; use Exception; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\type\TypeInterface; class Feature implements FeatureInterface { /** @var int|string */ protected $id; protected Target $target; protected DateTimeImmutable $starts; protected ?DateTimeImmutable $expires = null; private TypeInterface $type; public function __construct( $id, TypeInterface $type, Target $target, DateTimeImmutable $starts = null ) { $this->id = $id; $this->type = $type; $this->target = $target; $this->starts = $starts ?? new DateTimeImmutable(); } public function getId() { return $this->id; } public function target(): Target { return $this->target; } public function starts(): DateTimeImmutable { return $this->starts; } public function expires(): ?DateTimeImmutable { return $this->expires; } public function setExpires(?DateTimeImmutable $expires): void { $this->expires = $expires; } public function type(): TypeInterface { return $this->type; } public function setId(int $int): void { if ($this->id !== null) { throw new Exception('ID is already set'); } $this->id = $int; } public function jsonSerialize(): array { return array_filter(get_object_vars($this)); } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\statement; use hiqdev\billing\hiapi\customer\CustomerAttribution; use hiqdev\billing\hiapi\vo\MoneyAttribution; use hiqdev\DataMapper\Attribute\DateTimeAttribute; use hiqdev\DataMapper\Attribution\AbstractAttribution; class StatementAttribution extends AbstractAttribution { public function attributes() { return [ 'time' => DateTimeAttribute::class, 'period' => DateTimeAttribute::class, 'month' => DateTimeAttribute::class, ]; } public function relations() { return [ 'customer' => CustomerAttribution::class, 'balance' => MoneyAttribution::class, 'total' => MoneyAttribution::class, 'payment' => MoneyAttribution::class, 'amount' => MoneyAttribution::class, ]; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\target\Create; use hiapi\exceptions\HiapiException; use hiqdev\billing\hiapi\target\RemoteTargetCreationDto; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\target\TargetFactoryInterface; use hiqdev\php\billing\target\TargetRepositoryInterface; use hiqdev\DataMapper\Query\Specification; use hiqdev\php\billing\target\TargetWasCreated; use League\Event\EmitterInterface; final class Action { private TargetFactoryInterface $targetFactory; private TargetRepositoryInterface $targetRepo; private EmitterInterface $emitter; public function __construct( TargetRepositoryInterface $targetRepo, TargetFactoryInterface $targetFactory, EmitterInterface $emitter ) { $this->targetRepo = $targetRepo; $this->targetFactory = $targetFactory; $this->emitter = $emitter; } public function __invoke(Command $command): Target { $this->ensureDoesNotExist($command->type, $command->name); $target = $this->createTarget($command); return $target; } private function ensureDoesNotExist(string $type, string $name): void { $spec = (new Specification)->where([ 'type' => $type, 'name' => $name, ]); $target = $this->targetRepo->findOne($spec); if ($target !== false) { throw new HiapiException(sprintf('Target "%s" for type "%s" already exists with ID %s', $name, $type, $target->getId() )); } } private function createTarget(Command $command): Target { $dto = new RemoteTargetCreationDto(); $dto->name = $command->name; $dto->type = $command->type; $dto->customer = $command->customer; $dto->remoteid = $command->remoteid; $target = $this->targetFactory->create($dto); $this->targetRepo->save($target); $this->emitter->emit(TargetWasCreated::occurred($target)); return $target; } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\bill\GetInfo; use hiapi\Core\Auth\AuthRule; use hiqdev\php\billing\bill\BillRepositoryInterface; use hiqdev\php\billing\bill\BillInterface; final class Action { private BillRepositoryInterface $repo; public function __construct(BillRepositoryInterface $repo) { $this->repo = $repo; } public function __invoke(Command $command): ?BillInterface { $res = $this->repo->findOne( AuthRule::currentUser()->applyToSpecification($command->getSpecification()) ); return $res ?: null; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\target\ChangePlan\Strategy; use DateTimeImmutable; use hiqdev\php\billing\Exception\ConstraintException; use hiqdev\php\billing\sale\SaleInterface; final class GeneralPlanChangeStrategy implements PlanChangeStrategyInterface { public function ensureSaleCanBeClosedForChangeAtTime(SaleInterface $activeSale, DateTimeImmutable $desiredCloseTime): void { if ($activeSale->getTime() > $desiredCloseTime) { throw new ConstraintException(sprintf( 'Plan can not be changed earlier than the active sale "%s" was created', $activeSale->getId() )); } if ($activeSale->getCloseTime() !== null && $activeSale->getCloseTime() > $desiredCloseTime) { throw new ConstraintException(sprintf( 'Currently active sale "%s" is closed at "%s". Could not change plan earlier than active sale close time.', $activeSale->getId(), $activeSale->getCloseTime()->format(DATE_ATOM) )); } } public function calculateTimeInPreviousSalePeriod(SaleInterface $activeSale, DateTimeImmutable $desiredCloseTime): DateTimeImmutable { return $activeSale->getTime()->modify('-1 second'); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\plan\Search; use Doctrine\Common\Collections\ArrayCollection; use hiqdev\billing\hiapi\plan\AvailableFor; use hiqdev\billing\hiapi\plan\PlanReadModelRepositoryInterface; use yii\web\User; class BulkAction { private PlanReadModelRepositoryInterface $repo; private User $user; public function __construct(PlanReadModelRepositoryInterface $repo, User $user) { $this->repo = $repo; $this->user = $user; } public function __invoke(Command $command): ArrayCollection { $spec = $command->getSpecification(); if (empty($command->where[AvailableFor::SELLER_FIELD])) { $spec->where[AvailableFor::CLIENT_ID_FIELD] ??= $this->user->id; } $res = $this->repo->findAll($spec); return new ArrayCollection($res); } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\action\CheckCredit; use hiqdev\billing\hiapi\action\Calculate; class Command extends Calculate\Command { } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\vo; use hiqdev\billing\hiapi\Hydrator\Strategy\MoneyStrategy; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; use Money\Currency; use Money\Money; /** * Class MoneyHydrator. * * @author <NAME> <<EMAIL>> * @deprecated Use {@see MoneyStrategy} instead */ class MoneyHydrator extends GeneratedHydrator { public function hydrate(array $data, $object): object { $currency = new Currency(strtoupper($data['currency'])); return new Money($data['amount'] ?? '0', $currency); } /** * {@inheritdoc} * @param object|Money $object */ public function extract($object): array { return [ 'currency' => $object->getCurrency()->getCode(), 'amount' => $object->getAmount(), ]; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\sale\Close; use hiapi\commands\BaseCommand; use hiapi\validators\IdValidator; use hiapi\validators\UsernameValidator; use hiqdev\DataMapper\Validator\DateTimeValidator; use yii\validators\StringValidator; class SaleCloseCommand extends BaseCommand { public $customer_id; public $customer_username; public $plan_id; public $plan_name; public $target_id; public $target_fullname; public $time; public $customer; public $plan; public $target; public function rules(): array { return [ [['customer_id'], IdValidator::class], [['customer_username'], UsernameValidator::class], [['plan_id'], IdValidator::class], [['plan_name'], StringValidator::class], [['target_id'], IdValidator::class], [['target_fullname'], 'string'], [['time'], DateTimeValidator::class], [['time'], 'required'] ]; } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\target\Purchase; use hiapi\exceptions\NotAuthorizedException; use hiapi\legacy\lib\billing\plan\Forker\PlanForkerInterface; use hiqdev\billing\hiapi\target\RemoteTargetCreationDto; use hiqdev\billing\hiapi\tools\PermissionCheckerInterface; use hiqdev\DataMapper\Query\Specification; use hiqdev\php\billing\customer\CustomerInterface; use hiqdev\php\billing\Exception\ConstraintException; use hiqdev\php\billing\plan\PlanInterface; use hiqdev\php\billing\sale\Sale; use hiqdev\php\billing\sale\SaleInterface; use hiqdev\php\billing\sale\SaleRepositoryInterface; use hiqdev\php\billing\target\TargetFactoryInterface; use hiqdev\php\billing\target\TargetInterface; use hiqdev\php\billing\target\TargetRepositoryInterface; use hiqdev\php\billing\target\TargetState; use hiqdev\php\billing\target\TargetWasCreated; use hiqdev\php\billing\usage\Usage; use hiqdev\php\billing\usage\UsageRecorderInterface; use Psr\EventDispatcher\EventDispatcherInterface; use DateTimeImmutable; class Action { protected bool $targetWasCreated = false; private TargetRepositoryInterface $targetRepo; private TargetFactoryInterface $targetFactory; private SaleRepositoryInterface $saleRepo; private PlanForkerInterface $planForker; private PermissionCheckerInterface $permissionChecker; private UsageRecorderInterface $usageRecorder; private EventDispatcherInterface $eventDispatcher; public function __construct( TargetRepositoryInterface $targetRepo, TargetFactoryInterface $targetFactory, SaleRepositoryInterface $saleRepo, PlanForkerInterface $planForker, PermissionCheckerInterface $permissionChecker, UsageRecorderInterface $usageRecorder, EventDispatcherInterface $eventDispatcher ) { $this->targetRepo = $targetRepo; $this->targetFactory = $targetFactory; $this->saleRepo = $saleRepo; $this->planForker = $planForker; $this->permissionChecker = $permissionChecker; $this->usageRecorder = $usageRecorder; $this->eventDispatcher = $eventDispatcher; } public function __invoke(Command $command): TargetInterface { $this->targetWasCreated = false; $this->permissionChecker->ensureCustomerCan($command->customer, 'have-goods'); $target = $this->getTarget($command); $plan = $this->planForker->forkPlanIfRequired($command->plan, $command->customer); $sale = new Sale(null, $target, $command->customer, $plan, $command->time); $saleId = $this->saleRepo->findId($sale); if ($saleId !== null) { return $target; } $this->saleRepo->save($sale); if ($this->targetWasCreated) { $this->eventDispatcher->dispatch(TargetWasCreated::occurred($target)); } $this->saveInitialUses($sale, $command->initial_uses); return $target; } private function getTarget(Command $command): TargetInterface { $spec = (new Specification)->where([ 'type' => $command->type, 'name' => $command->name, ]); $target = $this->targetRepo->findOne($spec); if ($target === false) { $spec = (new Specification)->where([ 'type' => $command->type, 'remoteid' => $command->remoteid, 'customer_id' => $command->customer->getId(), ]); $target = $this->targetRepo->findByRemoteid($spec); } if ($target === false) { return $this->createTarget($command); } if (TargetState::isDeleted($target)) { $this->targetRepo->renameToDeleted($target); return $this->createTarget($command); } $this->ensureBelongs($target, $command->customer, $command->time); return $target; } private function ensureBelongs(TargetInterface $target, CustomerInterface $customer, ?DateTimeImmutable $time = null): void { $sales = $this->saleRepo->findAllActive((new Specification)->where([ 'seller-id' => $customer->getSeller()->getId(), 'target-id' => $target->getId(), ]), $time); if (!empty($sales) && reset($sales)->getCustomer()->getId() !== $customer->getId()) { throw new NotAuthorizedException('The target belongs to other client'); } } private function createTarget(Command $command): TargetInterface { $dto = new RemoteTargetCreationDto(); $dto->type = $command->type; $dto->name = $command->name; $dto->customer = $command->customer; $dto->remoteid = $command->remoteid; $target = $this->targetFactory->create($dto); $this->targetRepo->save($target); $this->targetWasCreated = true; return $target; } /** * @param PlanInterface $plan * @param list<InitialUse> $initialUses */ private function saveInitialUses(SaleInterface $sale, array $initialUses): void { $usedTypes = array_map(static fn (InitialUse $use) => $use->type->getName(), $initialUses); if ($usedTypes !== array_unique($usedTypes)) { throw new ConstraintException('The same Initial Use type must be listed only once'); } $plan = $sale->getPlan(); foreach ($initialUses as $use) { foreach ($plan->getPrices() as $price) { if ($price->getType()->matches($use->type)) { $use->type = $price->getType(); // In order to have Type with ID continue 2; } } throw new ConstraintException('The Initial Use type must be within Plan Prices types'); } foreach ($initialUses as $use) { $this->usageRecorder->record( new Usage($sale->getTarget(), $sale->getTime(), $use->type, $use->quantity) ); } } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\bill\Search; use Doctrine\Common\Collections\ArrayCollection; use hiapi\Core\Auth\AuthRule; use hiqdev\php\billing\bill\BillRepositoryInterface; class Action { private BillRepositoryInterface $repo; public function __construct(BillRepositoryInterface $repo) { $this->repo = $repo; } public function __invoke(Command $command): ArrayCollection { $res = $this->repo->findAll( AuthRule::currentUser()->applyToSpecification($command->getSpecification()) ); return new ArrayCollection($res); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\target; use hiapi\Core\Auth\AuthRule; use hiapi\exceptions\domain\ValidationException; use hiqdev\php\billing\target\TargetInterface; use hiqdev\php\billing\target\TargetRepositoryInterface; use League\Tactician\Middleware; use hiqdev\DataMapper\Query\Specification; class TargetLoader implements Middleware { private TargetRepositoryInterface $repo; public bool $isRequired = false; public function __construct(TargetRepositoryInterface $repo) { $this->repo = $repo; } public function execute($command, callable $next) { if (!isset($command->target)) { $command->target = $this->findTarget($command); if ($this->isRequired && $command->target === null) { throw new ValidationException(sprintf('Failed to find target')); } } return $next($command); } public function findTarget($command): ?TargetInterface { if (!empty($command->target_id)) { return $this->findTargetById($command->target_id); } if (!empty($command->target_type) && !empty($command->target_name)) { return $this->findTargetByName($command->target_name, $command->target_type); } if (!empty($command->target_fullname)) { return $this->findTargetByFullName($command->target_fullname); } return null; } private function findTargetById($id) { return $this->findTargetByArray(['id' => $id]); } private function findTargetByFullName($fullname) { $ps = explode(':', $fullname, 2); if (empty($ps[1])) { return null; } return $this->findTargetByName($ps[1], $ps[0]); } private function findTargetByName($name, $type) { return $this->findTargetByArray([ 'name' => $name, 'type' => $type, ]); } private function findTargetByArray(array $cond) { $cond += [AuthRule::currentUser()]; return $this->repo->findOne((new Specification)->where($cond)) ?: null; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\sale; use hiqdev\billing\hiapi\customer\CustomerAttribution; use hiqdev\billing\hiapi\plan\PlanAttribution; use hiqdev\billing\hiapi\target\TargetAttribution; use hiqdev\DataMapper\Attribute\DateTimeAttribute; use hiqdev\DataMapper\Attribute\IntegerAttribute; use hiqdev\DataMapper\Attribution\AbstractAttribution; class SaleAttribution extends AbstractAttribution { public function attributes() { return [ 'id' => IntegerAttribute::class, 'time' => DateTimeAttribute::class, 'closeTime' => DateTimeAttribute::class, ]; } public function relations() { return [ 'target' => TargetAttribution::class, 'seller' => CustomerAttribution::class, 'customer' => CustomerAttribution::class, 'plan' => PlanAttribution::class, ]; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature\Purchase; use hiqdev\billing\hiapi\action\Calculate\PaidCommand; use hiqdev\billing\hiapi\type\TypeLoader; use hiqdev\php\billing\type\Type; use hiqdev\php\billing\type\TypeInterface; final class Command extends PaidCommand { public function getType(): TypeInterface { if ($this->type === null) { $this->type = $this->di->get(TypeLoader::class)->findPrefixed('type,feature', $this->type_name); } return $this->type; } protected function getActionType(): TypeInterface { return new Type(TypeInterface::ANY, $this->getType()->getName()); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\plan; use hiapi\jsonApi\AttributionBasedCollectionDocument; class PlansCollectionDocument extends AttributionBasedCollectionDocument { } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\vo; use hiapi\jsonApi\AttributionBasedResource; use Money\Money; class MoneyResource extends AttributionBasedResource { /** * @param Money $entity */ public function getId($entity): string { return (string)$entity->getAmount() . $entity->getCurrency(); } public function getAttributes($entity): array { return [ 'amount' => fn(Money $po): string => (string) $po->getAmount(), 'currency' => fn(Money $po): string => (string) $po->getCurrency()->getCode(), ]; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\type; use hiqdev\billing\mrdp\Type\TypeRepository; use hiqdev\DataMapper\Query\Specification; use hiqdev\php\billing\type\TypeInterface; use League\Tactician\Middleware; use OutOfRangeException; class TypeLoader implements Middleware { public string $typePrefix = ''; private TypeRepository $typeRepository; public function __construct(TypeRepository $typeRepository) { $this->typeRepository = $typeRepository; } public function execute($command, callable $next) { if (empty($command->type) && !empty($command->type_name)) { $command->type = $this->findPrefixed($this->typePrefix, $command->type_name); } return $next($command); } public function findPrefixed(string $prefix, string $typeName): ?TypeInterface { $type = $this->typeRepository->findOne( (new Specification())->where(['fullName' => "{$prefix},{$typeName}"]) ); if ($type === false) { throw new OutOfRangeException(sprintf('Type "%s" does not exist', $typeName)); } return $type; } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\action; use hiqdev\billing\hiapi\Hydrator\Helper\DateTimeImmutableFormatterStrategyHelper; use hiqdev\php\billing\action\UsageInterval; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; use Laminas\Hydrator\Strategy\NullableStrategy; class UsageIntervalHydrator extends GeneratedHydrator { public function __construct() { $this->addStrategy('start', DateTimeImmutableFormatterStrategyHelper::create()); $this->addStrategy('end', new NullableStrategy(DateTimeImmutableFormatterStrategyHelper::create())); $this->addStrategy('month', DateTimeImmutableFormatterStrategyHelper::create()); } /** {@inheritdoc} */ public function hydrate(array $data, $object): object { $data['start'] = $this->hydrateValue('start', $data['start']); $data['end'] = $this->hydrateValue('end', $data['end']); $data['month'] = $this->hydrateValue('month', $data['month']); return parent::hydrate($data, $object); } /** * {@inheritdoc} * @param UsageInterval $object */ public function extract($object): array { $result = array_filter([ 'start' => $this->extractValue('start', $object->start()), 'end' => $this->extractValue('end', $object->end()), 'seconds' => $object->seconds(), 'ratio' => $object->ratioOfMonth(), 'seconds_in_month' => $object->secondsInMonth(), ], static function ($value): bool { return $value !== null; }, ARRAY_FILTER_USE_BOTH); return $result; } public function createEmptyInstance(string $className, array $data = []): object { return parent::createEmptyInstance(UsageInterval::class, $data); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\Http\Serializer; use Closure; use yii\web\User; use Laminas\Hydrator\ExtractionInterface; use Laminas\Hydrator\HydratorInterface; /** * Class HttpSerializer implements ExtractionInterface and should be used * to serialize objects for HTTP responses and hide some sensitive information * from the serialized objects. * * This is a trick to re-use existing Hydrators and do not implement them again * just for HTTP interaction. * * The HTTP formatter should call {@see extract()} method of this class, * then, this class calls the concrete Hydrator implementations. * * The underlying Hydrator implementation may depend on HttpSerializer and * use its {@see ensureBeforeCall()} method to check, if it was called in a context * of HTTP response preparation. * * @author <NAME> <<EMAIL>> */ final class HttpSerializer implements ExtractionInterface { private User $user; private HydratorInterface $hydrator; public function __construct(User $user, HydratorInterface $hydrator) { $this->user = $user; $this->hydrator = $hydrator; } private bool $isRunning = false; public function extract(object $object): array { $wasRunning = $this->isRunning; $this->isRunning = true; try { return $this->hydrator->extract($object); } finally { $this->isRunning = $wasRunning; } } public function ensureBeforeCall($permissionOrClosure, Closure $closure, $fallback = null) { if (!$this->isRunning) { return $closure(); } if (is_string($permissionOrClosure)) { if ($this->user->can($permissionOrClosure)) { return $closure(); } return $fallback; } if ($permissionOrClosure instanceof Closure) { if ($permissionOrClosure($this->user)) { return $closure(); } return $fallback; } return $fallback; } } <file_sep># Billing API Overview Billing API provides endpoints to create and manage Sales. ## Creating a new Sale Briefly, can be done in several steps: 1. Search for the available Tariff Plans with a [PlansSearch](#PlansSearch) command. When the command is called with the customer's identity, it returns tariff plans, marked as public by the seller or personally assigned to a Customer. The plans are available for self purchasing. The command can be also called without authentication, supplied with a query parameter `where[available_for_seller]=$SELLER_LOGIN`. This will show tariff plans, assigned as public by the seller, specified in `$SELLER_LOGIN`. Each tariff consists of a set of prices and may include some additional information. See examples in [PlansSearch](#planssearch-for-plans-and-get-its-prices) 2. Then purchase a Target with `PurchaseTarget` command. This command creates a Sale i.e. connection between user, billed object (named Target) and a (tariff) Plan. After running a `PurchaseTarget` command, the billing starts and continues until the sale gets removed with the `SaleClose` command. The list of current active sales can be retrieved with command [`SalesSearch`](#salessearch). 3. Billing charges users with Bills. Each bill is comprised of charges, each representing a price, that produced it. The list of bills and charges can be received with the [`BillsSearch`](#billssearch) command. --- ## PlansSearch – search for plans and get its prices A response is a data structure as follows, each record represents a tariff plan: ```json { data: [ { id: 2, name: "Anycast CDN: 5 TB", seller: {…}, prices: {…} }, { id: 5, name: "Anycast CDN: 25 TB", seller: {…}, prices: {…} }, { id: 6, name: "Anycast CDN: 50 TB", seller: {…}, prices: {…} }, { id: 8, name: "Anycast CDN: 100 TB", seller: {…}, prices: {…} }, { id: 9, name: "Anycast CDN: 500 TB", seller: {…}, prices: {…} } ] } ``` ### Price meaning Each `price` consists of the following data: ```json { id: 231, type: { id: 421, name: "overuse,storage_du" }, price: { amount: "3000", currency: "USD" }, prepaid: { unit: "tb", quantity: "0.5" }, target: [] } ``` - **type**: a billable service *type*. The name is unique among the billing system. The name is an well-known comma-separated string of tags. The quantity of comma-separated tags and their values may vary, but there is a convention in naming of the first block: - `monthly` – billed once a month when the Sale is active regardless of the consumption - `overuse` – billed once a month depending on the consumed amount of service - **price**: how much costs the consumption of one *unit* of this service. - **prepaid**: contains a measure *unit* of this price and the *quantity* that is prepaid in this tariff plan. The prepaid *quantity* will NOT be charged. The example price will cost `3 000 USD` for each *TB* of the `storage_du` (storage disk usage), if exceeds the *prepaid.quantity* of `0.5 TB` - **target**: when empty, the price will be applied to any service, sold by this tariff plan. When filled, it reduces the price applicability scope to the specific object, e.g. service, or its specific part. ### Calculations of a total monthly price of the tariff plan The total monthly price of a Plan can be calculation by summing all `monthly` prices in it. ## PurchaseTarget – Creates a new Sale of the Target Something that can be billed is called `Target`. In order to buy a target, call the `PurchaseTarget` command using the Customer's identity. See [Swagger](http://swagger.hiqdev.com/?urls.primaryName=Billing%20API#/default/post_TargetsPurchase) for the request type and details. ```json { "customer_username": "string", "customer_id": "string", "plan_id": "string", "plan_name": "string", "plan_seller": "string", "name": "string", "type": "string", "remoteid": "string", "time": "string" } ``` - **customer_username**, **customer_id** (*optional*) – must be filled, when the authenticated Customer purchases a Target on behalf of other Customer - **plan_id** – ID of plan among of available via [PlansSearch](#planssearchsearch-for-plans-and-get-its-prices) - **plan_name**, **plan_seller** (*optional*) – either **plan_id**, or a pair of a Plan name and Seller login must be provided - **name** – arbitrary string, the service name, as is registered at the Service Provider subsystem - **remoteid** – arbitrary string, the service ID, as is registered at the Service Provider subsystem. Will be used to find a proper Target, or to create a new one. - **type** – the Target type. Muse be supported by billing. E.g.: `anycastcdn`, `videocdn`, etc. Will be used to find a proper Target, or to create a new one. - **time** - the ISO8601 time, since when the Target should be billed. Might be useful for the trial period. If the sale date is greater than the start of current month, the `monthly` prices will be charged proportionally to the active service time in the month. If the date is less then current month, charges will NOT be created for the previous billing periods. Success command run results in creation of a sale, the response contains an `id` of the Target, registered in our system. It's recommended to save is as a foreign identifier of the **remoteid**. ## SaleClose – interrupt the sale and stop charging ```json { "customer_id": "string", "plan_id": "string", "target_id": "string", "time": "string" } ``` - **customer_id** (*optional*) – defaults to currently authenticated Customer. Must be filled only when the Sale is getting closed belongs to another Customer. - **plan_id** – the Plan ID, sale is active for - **target_id** – the Target ID - **time** – the ISO8601 time of the active Sale ## SalesSearch > // TBD ## BillsSearch > // TBD # Aliases for API Gateway compatibility - GET `/api/v1/clients` - alias to [clientsSearch](http://swagger.hiqdev.com/#/client/post_clientsSearch) - GET `/api/v1/client/:id` - alias to [clientGetInfo?id=:id](http://swagger.hiqdev.com/#/client/post_clientGetInfo) - GET `/api/v1/plans` - alias to [PlansSearch](http://swagger.hiqdev.com/?urls.primaryName=Billing%20API#/default/post_PlansSearch) - GET `/api/v1/plans/public` - alias to [plansGetAvailable](http://swagger.hiqdev.com/#/client/post_plansGetAvailable) - GET `/api/v1/plan/:id` - alias to [PlanGetInfo?id=:id](http://swagger.hiqdev.com/?urls.primaryName=Billing%20API#/default/post_PlanGetInfo) - GET `/api/v1/targets` - alias to [TargetsSearch](http://swagger.hiqdev.com/?urls.primaryName=Billing%20API#/default/post_TargetsSearch) - GET `/api/v1/target/:id` - alias to [TargetGetInfo?id=:id](http://swagger.hiqdev.com/?urls.primaryName=Billing%20API#/default/post_TargetGetInfo) - POST `/api/v1/target` - alias to [TargetPurchase](http://swagger.hiqdev.com/?urls.primaryName=Billing%20API#/default/post_TargetPurchase) - GET `/api/v1/sales` - alias to [SalesSearch](http://swagger.hiqdev.com/?urls.primaryName=Billing%20API#/default/post_SalesSearch) - POST `/api/v1/sales` - alias to [SaleCreate](http://swagger.hiqdev.com/?urls.primaryName=Billing%20API#/default/post_SaleCreate) - DELETE `/api/v1/sales` - alias to [SaleClose](http://swagger.hiqdev.com/?urls.primaryName=Billing%20API#/default/post_SaleClose) - GET `/api/v1/bills` - alias to [BillsSearch](http://swagger.hiqdev.com/?urls.primaryName=Billing%20API#/default/post_BillsSearch) - GET `/api/v1/bill/:id` - alias to [BillGetInfo?id=:id](http://swagger.hiqdev.com/?urls.primaryName=Billing%20API#/default/post_BillGetInfo) - POST `/api/v1/feature/purchase` - alias to [FeaturePurchase](http://swagger.hiqdev.com/?urls.primaryName=Billing%20API#/default/post_FeaturePurchase) - POST `/api/v1/feature/cancel` - alias to [FeatureCancel](http://swagger.hiqdev.com/?urls.primaryName=Billing%20API#/default/post_FeatureCancel)<file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature\Cancel; use hiapi\commands\BaseCommand; use hiapi\validators\IdValidator; use hiapi\validators\RefValidator; use hiqdev\php\billing\customer\Customer; use hiqdev\php\billing\target\TargetInterface; use hiqdev\php\billing\type\TypeInterface; final class Command extends BaseCommand { public $customer_id; public $target_id; public $type_name; public ?Customer $customer = null; public ?TargetInterface $target = null; public ?TypeInterface $type = null; public function rules() { return array_merge(parent::rules(), [ ['customer_id', IdValidator::class], ['target_id', IdValidator::class], ['type_name', RefValidator::class], [['target_id', 'type_name'], 'required'], ]); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tests\unit\type; use hiqdev\php\billing\type\Type; use hiqdev\yii\DataMapper\tests\unit\BaseHydratorTest; /** * @author <NAME> <<EMAIL>> */ class TypeHydratorTest extends BaseHydratorTest { const ID1 = 11111; const NAME1 = 'login11111'; const ID2 = 22222; const NAME2 = 'login22222'; protected $data = [ 'id' => self::ID1, 'name' => self::NAME1, ]; public function setUp(): void { $this->hydrator = $this->getHydrator(); } public function testHydrateNew() { $obj = $this->hydrator->hydrate($this->data, Type::class); $this->checkValues($obj); } public function testHydrateOld() { $obj = new Type(self::ID2, self::NAME2); $this->hydrator->hydrate($this->data, $obj); $this->checkValues($obj); } public function checkValues($obj) { $this->assertInstanceOf(Type::class, $obj); $this->assertSame(self::ID1, $obj->getId()); $this->assertSame(self::NAME1, $obj->getName()); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\plan; use hiqdev\billing\hiapi\customer\CustomerAttribution; use hiqdev\billing\hiapi\type\TypeAttribution; use hiqdev\billing\hiapi\price\PriceAttribution; use hiqdev\DataMapper\Attribute\BooleanAttribute; use hiqdev\DataMapper\Attribute\IntegerAttribute; use hiqdev\DataMapper\Attribute\StringAttribute; use hiqdev\DataMapper\Attribution\AbstractAttribution; use hiqdev\DataMapper\Attribute\DateTimeAttribute; class PlanAttribution extends AbstractAttribution { public function attributes() { return [ 'id' => IntegerAttribute::class, 'name' => StringAttribute::class, 'is_grouping' => BooleanAttribute::class, 'month' => DateTimeAttribute::class, ]; } public function relations() { return [ 'type' => TypeAttribution::class, 'seller' => CustomerAttribution::class, 'prices' => PriceAttribution::class, ]; } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\target\GetInfo; use hiapi\commands\GetInfoCommand; use hiqdev\php\billing\target\Target; class Command extends GetInfoCommand { public function getEntityClass(): string { return Target::class; } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\plan; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; use Laminas\Hydrator\HydratorInterface; /** * Class PlanReadModelHydrator hydrates {@see PlanReadModel} * * @author <NAME> <<EMAIL>> */ class PlanReadModelHydrator extends GeneratedHydrator { private PlanHydrator $planHydrator; public function __construct(PlanHydrator $planHydrator) { $this->planHydrator = $planHydrator; } private function ensurePlanHydratorHasAHydrator(): void { if ($this->planHydrator->getHydrator() === null) { $this->planHydrator->setHydrator($this->hydrator); } } public function hydrate(array $data, $object): object { $this->ensurePlanHydratorHasAHydrator(); $plan = $this->planHydrator->hydrate($data, $object); $additionalData = []; if (isset($data['data'])) { /** @noinspection JsonEncodingApiUsageInspection */ $decodedData = json_decode($data['data'], true) ?? []; $additionalData['customAttributes'] = $decodedData['custom_attributes'] ?? []; } if ($additionalData === []) { return $plan; } return parent::hydrate($additionalData, $plan); } public function createEmptyInstance(string $className, array $data = []): object { return parent::createEmptyInstance($className, $data); } /** * @param PlanReadModel $object * @return array */ public function extract($object): array { return array_merge($this->planHydrator->extract($object), [ 'customAttributes' => $object->customAttributes, ]); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\vo; use hiqdev\DataMapper\Attribution\AbstractAttribution; use hiqdev\DataMapper\Attribute\IntegerAttribute; use hiqdev\DataMapper\Attribute\StringAttribute; /** * @author <NAME> <<EMAIL>> */ class MoneyAttribution extends AbstractAttribution { public function attributes() { return [ 'amount' => IntegerAttribute::class, 'currency' => StringAttribute::class, // todo: regexp validatior ]; } public function relations() { return []; } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\target\ChangePlan; use hiapi\Core\Endpoint\BuilderFactory; use hiapi\Core\Endpoint\Endpoint; use hiapi\Core\Endpoint\EndpointBuilder; use hiapi\endpoints\Module\Multitenant\Tenant; use hiqdev\billing\hiapi\customer\CustomerLoader; use hiqdev\billing\hiapi\vo\DateTimeLoader; use hiqdev\billing\hiapi\plan\PlanLoader; use hiqdev\php\billing\target\Target; final class Builder { public function __invoke(BuilderFactory $build): Endpoint { return $this->create($build)->build(); } public function create(BuilderFactory $build): EndpointBuilder { return $build->endpoint(self::class) ->exportTo(Tenant::ALL) ->take(Command::class) ->middlewares( CustomerLoader::class, [ '__class' => PlanLoader::class, 'isRequired' => true, ], new DateTimeLoader('time'), new DateTimeLoader('wall_time'), $build->call(Action::class) ) ->return(Target::class); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\bill; use hiapi\jsonApi\AttributionBasedResource; use hiqdev\php\billing\bill\BillInterface; use hiqdev\php\billing\charge\ChargeInterface; use WoohooLabs\Yin\JsonApi\Schema\Relationship\ToManyRelationship; class BillResource extends AttributionBasedResource { /** * @param BillInterface $entity */ public function getRelationships($entity): array { $res = array_merge(parent::getRelationships($entity), [ 'charges' => fn (BillInterface $po) => ToManyRelationship::create() ->setData($po->getCharges(), $this->getResourceFor(ChargeInterface::class)), ]); // XXX temp because of Maximum nesting function level in woohoolabs/yin // TODO remove after fixing unset($res['plan']); return $res; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\plan; use hiqdev\php\billing\customer\Customer; use hiqdev\php\billing\type\Type; use hiqdev\php\billing\plan\Plan; use hiqdev\php\billing\plan\PlanInterface; use hiqdev\php\billing\price\PriceInterface; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; /** * Class PlanHydrator. * * @author <NAME> <<EMAIL>> */ class PlanHydrator extends GeneratedHydrator { /** * {@inheritdoc} * @param object|Plan $object * @throws \Exception */ public function hydrate(array $data, $object): object { if (!empty($data['seller'])) { $data['seller'] = $this->hydrator->hydrate($data['seller'], Customer::class); } if (!empty($data['type'])) { $data['type'] = $this->hydrator->hydrate($data['type'], Type::class); } $raw_prices = $data['prices'] ?? []; unset($data['prices']); /** @var Plan $plan */ $plan = parent::hydrate($data, $object); if (is_array($raw_prices)) { $prices = []; foreach ($raw_prices as $key => $price) { if ($price instanceof PriceInterface) { $price->setPlan($plan); $prices[$key] = $price; } else { $price['plan'] = $plan; $prices[$key] = $this->hydrator->hydrate($price, PriceInterface::class); } } $plan->setPrices($prices); } return $plan; } private bool $preventNestedCall = false; /** * {@inheritdoc} * @param ?Plan $object */ public function extract($object): array { $result = []; if ($this->preventNestedCall) { return $result; } $this->preventNestedCall = true; $result = array_filter([ 'id' => $object->getId(), 'name' => $object->getName(), 'seller' => $object->getSeller() ? $this->hydrator->extract($object->getSeller()) : null, 'parent' => $object->getParent() ? $this->hydrator->extract($object->getParent()) : null, 'is_grouping' => $object instanceof GroupingPlan, 'type' => $object->getType() ? $this->hydrator->extract($object->getType()) : null, 'prices' => $this->hydrator->extractAll($object->getPrices()), ], static function ($value): bool { return $value !== null; }, ARRAY_FILTER_USE_BOTH); $this->preventNestedCall = false; return $result; } /** * @throws \ReflectionException * @return object */ public function createEmptyInstance(string $className, array $data = []): object { if (isset($data['is_grouping']) && $data['is_grouping'] === true) { $className = GroupingPlan::class; } if ($className === PlanInterface::class) { $className = Plan::class; } return parent::createEmptyInstance($className, $data); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\target\ChangePlan\Strategy; use hiqdev\php\billing\sale\SaleInterface; interface PlanChangeStrategyProviderInterface { /** * @param SaleInterface $sale * @return PlanChangeStrategyInterface */ public function getBySale(SaleInterface $sale): PlanChangeStrategyInterface; } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\target\ChangePlan\Strategy; use hiqdev\php\billing\sale\SaleInterface; final class PlanChangeStrategyProvider implements PlanChangeStrategyProviderInterface { private GeneralPlanChangeStrategy $generalPlanChangeStrategy; private OncePerMonthPlanChangeStrategy $oncePerMonthPlanChangeStrategy; public function __construct( GeneralPlanChangeStrategy $generalPlanChangeStrategy, OncePerMonthPlanChangeStrategy $oncePerMonthPlanChangeStrategy ) { $this->generalPlanChangeStrategy = $generalPlanChangeStrategy; $this->oncePerMonthPlanChangeStrategy = $oncePerMonthPlanChangeStrategy; } public function getBySale(SaleInterface $sale): PlanChangeStrategyInterface { if (in_array($sale->getTarget()->getType(), [ // TODO: Add a property to a type, that will distinguish strategies 'anycastcdn', 'storage', 'videocdn' ], true)) { return $this->oncePerMonthPlanChangeStrategy; } return $this->generalPlanChangeStrategy; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\sale\Search; use Doctrine\Common\Collections\ArrayCollection; use hiapi\Core\Auth\AuthRule; use hiqdev\billing\mrdp\Sale\HistoryAndFutureSaleRepository; use hiqdev\php\billing\sale\SaleRepositoryInterface; class BulkAction { /** * @var SaleRepositoryInterface */ private $repo; /** * @var HistoryAndFutureSaleRepository */ private HistoryAndFutureSaleRepository $historyRepo; public function __construct(SaleRepositoryInterface $repo, HistoryAndFutureSaleRepository $saleRepository) { $this->repo = $repo; $this->historyRepo = $saleRepository; } public function __invoke(Command $command): ArrayCollection { $specification = AuthRule::currentUser()->applyToSpecification($command->getSpecification()); if (in_array('history', $command->include, true)) { $res = $this->historyRepo->findAll($specification); } else { $res = $this->repo->findAll($specification); } return new ArrayCollection($res); } } <file_sep># Billing HiAPI **API for Billing** [![Latest Stable Version](https://poser.pugx.org/hiqdev/billing-hiapi/v/stable)](https://packagist.org/packages/hiqdev/billing-hiapi) [![Total Downloads](https://poser.pugx.org/hiqdev/billing-hiapi/downloads)](https://packagist.org/packages/hiqdev/billing-hiapi) [![Build Status](https://img.shields.io/travis/hiqdev/billing-hiapi.svg)](https://travis-ci.org/hiqdev/billing-hiapi) [![Scrutinizer Code Coverage](https://img.shields.io/scrutinizer/coverage/g/hiqdev/billing-hiapi.svg)](https://scrutinizer-ci.com/g/hiqdev/billing-hiapi/) [![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/hiqdev/billing-hiapi.svg)](https://scrutinizer-ci.com/g/hiqdev/billing-hiapi/) Billing API. Uses: - [php-billing] - [hiapi] Also see [tests README]. [php-billing]: https://github.com/hiqdev/php-billing [hiapi]: https://github.com/hiqdev/hiapi [tests README]: tests/README.md ## Installation The preferred way to install this yii2-extension is through [composer](http://getcomposer.org/download/). Either run ```sh php composer.phar require "hiqdev/billing-hiapi" ``` or add ```json "hiqdev/billing-hiapi": "*" ``` to the require section of your composer.json. ## License This project is released under the terms of the BSD-3-Clause [license](LICENSE). Read more [here](http://choosealicense.com/licenses/bsd-3-clause). Copyright © 2017-2018, HiQDev (http://hiqdev.com/) <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\tests\unit\vo; use hiqdev\yii\DataMapper\tests\unit\BaseHydratorTest; use Money\Currency; use Money\Money; /** * @author <NAME> <<EMAIL>> */ class MoneyHydratorTest extends BaseHydratorTest { const AMOUNT1 = '11111'; const CURRENCY1 = 'USD'; const AMOUNT2 = '22222'; const CURRENCY2 = 'EUR'; protected $data = [ 'amount' => self::AMOUNT1, 'currency' => self::CURRENCY1, ]; public function setUp(): void { $this->hydrator = $this->getHydrator(); } public function testHydrateNew() { $obj = $this->hydrator->hydrate($this->data, Money::class); $this->checkValues($obj); } public function testHydrateOld() { $obj = new Money(self::AMOUNT2, new Currency(self::CURRENCY2)); $obj = $this->hydrator->hydrate($this->data, $obj); $this->checkValues($obj); } public function checkValues($obj) { $this->assertInstanceOf(Money::class, $obj); $this->assertSame(self::AMOUNT1, $obj->getAmount()); $this->assertSame(self::CURRENCY1, $obj->getCurrency()->getCode()); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\plan; use hiqdev\php\billing\plan\PlanRepositoryInterface; interface PlanReadModelRepositoryInterface extends PlanRepositoryInterface { } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\tools; use hiqdev\php\billing\customer\CustomerInterface; interface PermissionCheckerInterface { public function checkAccess($clientId, string $permission): bool; public function ensureCustomerCan(CustomerInterface $customer, string $permission): void; } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\target\GetInfo; use hiapi\Core\Auth\AuthRule; use hiqdev\php\billing\target\TargetRepositoryInterface; use hiqdev\php\billing\target\TargetInterface; final class Action { private TargetRepositoryInterface $repo; public function __construct(TargetRepositoryInterface $repo) { $this->repo = $repo; } public function __invoke(Command $command): TargetInterface { return $this->repo->findOne( AuthRule::currentUser()->applyToSpecification($command->getSpecification()) ); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ use Yiisoft\Composer\Config\Builder; require_once __DIR__ . '/../../../autoload.php'; date_default_timezone_set('UTC'); $config = require Builder::path('web'); require_once __DIR__ . '/../../../yiisoft/yii2/Yii.php'; \Yii::setAlias('@root', dirname(__DIR__, 4)); \Yii::$app = new \yii\web\Application($config); <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\customer; use hiapi\jsonApi\AttributionBasedResource; class CustomerResource extends AttributionBasedResource { } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\feature\Cancel; use hiapi\Core\Endpoint\BuilderFactory; use hiapi\Core\Endpoint\Endpoint; use hiapi\Core\Endpoint\EndpointBuilder; use hiapi\endpoints\Module\Multitenant\Tenant; use hiqdev\billing\hiapi\customer\CustomerLoader; use hiqdev\billing\hiapi\feature\Feature; use hiqdev\billing\hiapi\target\TargetLoader; use hiqdev\billing\hiapi\type\TypeLoader; final class Builder { public function __invoke(BuilderFactory $build): Endpoint { return $this->create($build)->build(); } public function create(BuilderFactory $build): EndpointBuilder { return $build->endpoint(self::class) ->description('Cancel a feature') ->exportTo(Tenant::ALL) ->take(Command::class) ->middlewares( CustomerLoader::class, [ '__class' => TargetLoader::class, 'isRequired' => true, ], [ '__class' => TypeLoader::class, 'typePrefix' => 'type,feature', ], $build->call(Action::class) ) ->return(Feature::class); } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2021, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\statement; use hiqdev\billing\hiapi\Http\Serializer\HttpSerializer; use hiqdev\billing\hiapi\Hydrator\Helper\DateTimeImmutableFormatterStrategyHelper; use hiqdev\php\billing\statement\StatementBill; use hiqdev\php\billing\statement\StatementBillInterface; use hiqdev\billing\hiapi\bill\BillHydrator; use hiqdev\php\billing\bill\BillRequisite; use hiqdev\php\billing\bill\BillState; use hiqdev\php\billing\customer\Customer; use hiqdev\php\billing\plan\Plan; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\type\Type; use hiqdev\php\units\Quantity; use DateTimeImmutable; use Money\Money; /** * Statement Bill Hydrator. * * @author <NAME> <<EMAIL>> */ class StatementBillHydrator extends BillHydrator { protected array $requiredAttributes = [ 'type' => Type::class, 'month' => DateTimeImmutable::class, 'time' => DateTimeImmutable::class, 'sum' => Money::class, 'quantity' => Quantity::class, 'customer' => Customer::class, 'price' => Money::class, 'overuse' => Money::class, 'prepaid' => Quantity::class, ]; protected array $optionalAttributes = [ 'target' => Target::class, 'plan' => Plan::class, 'state' => BillState::class, 'requisite' => BillRequisite::class, 'tariff_type' => Type::class, ]; public function __construct(HttpSerializer $httpSerializer) { parent::__construct($httpSerializer); $this->addStrategy('month', DateTimeImmutableFormatterStrategyHelper::create()); $this->attributesHandledWithStrategy['month'] = true; } /** * {@inheritdoc} * @param object|StatementBill $object */ public function extract($object): array { return array_filter(array_merge(parent::extract($object), [ 'month' => $this->extractValue('month', $object->getMonth()), 'from' => $object->getFrom(), 'price' => $object->getPrice() ? $this->hydrator->extract($object->getPrice()) : null, 'overuse' => $object->getOveruse() ? $this->hydrator->extract($object->getOveruse()) : null, 'prepaid' => $object->getPrepaid() ? $this->hydrator->extract($object->getPrepaid()) : null, 'tariff_type' => $object->getTariffType() ? $this->hydrator->extract($object->getTariffType()) : null, ]), static function ($value): bool { return $value !== null; }, ARRAY_FILTER_USE_BOTH); } public function createEmptyInstance(string $className, array $data = []): object { if ($className === StatementBillInterface::class) { $className = StatementBill::class; } return parent::createEmptyInstance($className, $data); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\sale; use hiapi\jsonApi\AttributionBasedCollectionDocument; class SalesCollectionDocument extends AttributionBasedCollectionDocument { } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\feature; use hiqdev\billing\hiapi\Hydrator\Helper\DateTimeImmutableFormatterStrategyHelper; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; use hiqdev\php\billing\target\Target; use hiqdev\php\billing\type\Type; use Laminas\Hydrator\Strategy\NullableStrategy; /** * Class FeatureHydrator. */ class FeatureHydrator extends GeneratedHydrator { public function __construct() { $this->addStrategy('starts', DateTimeImmutableFormatterStrategyHelper::create()); $this->addStrategy('expires', new NullableStrategy(DateTimeImmutableFormatterStrategyHelper::create())); } /** * {@inheritdoc} * @param object|Feature $object */ public function hydrate(array $data, $object): object { $data['target'] = $this->hydrator->create($data['target'], Target::class); $data['type'] = $this->hydrator->create($data['type'], Type::class); $data['starts'] = $this->hydrateValue('starts', $data['starts']); if (!empty($data['expires'])) { $data['expires'] = $this->hydrateValue('expires', $data['expires']); } return parent::hydrate($data, $object); } /** * {@inheritdoc} * @param object|Feature $object */ public function extract($object): array { return [ 'id' => $object->getId(), 'type' => $this->hydrator->extract($object->type()), 'starts' => $this->extractValue('starts', $object->starts()), 'expires' => $this->extractValue('expires', $object->expires()), 'target' => $this->hydrator->extract($object->target()), ]; } } <file_sep><?php /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\sale; use hiqdev\billing\hiapi\Hydrator\Helper\DateTimeImmutableFormatterStrategyHelper; use hiqdev\php\billing\customer\CustomerInterface; use hiqdev\php\billing\plan\PlanInterface; use hiqdev\php\billing\sale\Sale; use hiqdev\php\billing\sale\SaleInterface; use hiqdev\php\billing\target\TargetInterface; use hiqdev\DataMapper\Hydrator\GeneratedHydrator; use Laminas\Hydrator\Strategy\NullableStrategy; /** * Class SaleHydrator. * * @author <NAME> <<EMAIL>> */ class SaleHydrator extends GeneratedHydrator { public function __construct() { $this->addStrategy('time', DateTimeImmutableFormatterStrategyHelper::create()); $this->addStrategy('closeTime', new NullableStrategy(DateTimeImmutableFormatterStrategyHelper::create())); } public function hydrate(array $data, $object): object { $data['target'] = $this->hydrateChild($data['target'] ?? null, TargetInterface::class); $data['customer'] = $this->hydrateChild($data['customer'], CustomerInterface::class); $data['plan'] = $data['plan'] ?? null; if (is_array($data['plan']) && !empty($data['plan'])) { $data['plan'] = $this->hydrateChild($data['plan'], PlanInterface::class); } $data['time'] = $this->hydrateValue('time', $data['time']); $data['closeTime'] = $this->hydrateValue('closeTime', $data['closeTime'] ?? null); return parent::hydrate($data, $object); } /** * {@inheritdoc} * @param object|Sale $object */ public function extract($object): array { return array_filter([ 'id' => $object->getId(), 'target' => $this->extractChild($object->getTarget()), 'customer' => $this->extractChild($object->getCustomer()), 'plan' => $this->extractChild($object->getPlan()), 'time' => $this->extractValue('time', $object->getTime()), 'closeTime' => $this->extractValue('closeTime', $object->getCloseTime()), ], static function ($value): bool { return $value !== null; }, ARRAY_FILTER_USE_BOTH); } public function createEmptyInstance(string $className, array $data = []): object { if ($className === SaleInterface::class) { $className = Sale::class; } return parent::createEmptyInstance($className, $data); } } <file_sep><?php declare(strict_types=1); /** * API for Billing * * @link https://github.com/hiqdev/billing-hiapi * @package billing-hiapi * @license BSD-3-Clause * @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/) */ namespace hiqdev\billing\hiapi\sale\Search; use hiapi\Core\Auth\AuthRule; use hiapi\endpoints\Module\InOutControl\VO\Count; use hiqdev\billing\mrdp\Sale\HistoryAndFutureSaleRepository; use hiqdev\php\billing\sale\SaleRepositoryInterface; class CountAction { private SaleRepositoryInterface $repo; private HistoryAndFutureSaleRepository $historyRepo; public function __construct(SaleRepositoryInterface $repo, HistoryAndFutureSaleRepository $historyRepo) { $this->repo = $repo; $this->historyRepo = $historyRepo; } public function __invoke(Command $command): Count { $specification = AuthRule::currentUser()->applyToSpecification($command->getSpecification()); if (in_array('history', $command->include, true)) { $count = $this->historyRepo->count($specification); } else { $count = $this->repo->count($specification); } return Count::is($count); } } <file_sep><?php declare(strict_types=1); namespace hiqdev\billing\hiapi\bill; use hiapi\jsonApi\AttributionBasedCollectionDocument; /** * @author <NAME> <<EMAIL>> */ class BillsCollectionDocument extends AttributionBasedCollectionDocument { }
c05d670920956ff2e36f669f9fab6d863b7d746e
[ "Markdown", "PHP" ]
156
PHP
hiqdev/billing-hiapi
e8d9155f1e62d2f7eef87cbaa09edebd6868dce4
bacdf8d38e1d13ecfb412d162c7799d58f8f2df6
refs/heads/master
<repo_name>arwagner/GettingAndCleaningData<file_sep>/README.md This tidy data set was assembled for the course project for the "Getting and Cleaning Data" Coursera class. This includes measurements from the data described at http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones , which is available at https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip Fields: subject * id of the subject for this observation activity * One of the following: WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING timeBodyAcceleration-mean()-X * time-domain signal mean acceleration in the X axis timeBodyAccelerationmean()-Y * time-domain signal mean acceleration in the Y axis timeBodyAccelerationmean()-Z * time-domain signal mean acceleration in the Z axis timeBodyAccelerationStandardDeviation()-X * time-domain signal standard deviation of acceleration in the X axis timeBodyAccelerationStandardDeviation()-Y * time-domain signal standard deviation of acceleration in the Y axis timeBodyAccelerationStandardDeviation()-Z * time-domain signal standard deviation of acceleration in the Z axis timeGravityAccelerationmean()-X * time-domain signal mean of gravity-based acceleration in the X axis timeGravityAccelerationmean()-Y * time-domain signal mean of gravity-based acceleration in the Y axis timeGravityAccelerationmean()-Z * time-domain signal mean of gravity-based acceleration in the Z axis timeGravityAccelerationStandardDeviation()-X * time-domain signal standard deviation of gravity-based acceleration in the X axis timeGravityAccelerationStandardDeviation()-Y * time-domain signal standard deviation of gravity-based acceleration in the Y axis timeGravityAccelerationStandardDeviation()-Z * time-domain signal standard deviation of gravity-based acceleration in the Z axis timeBodyAccelerationJerk-mean()-X * time-domain signal mean of acceleration jerk in the X axis timeBodyAccelerationJerk-mean()-Y * time-domain signal mean of acceleration jerk in the Y axis timeBodyAccelerationJerk-mean()-Z * time-domain signal mean of acceleration jerk in the Z axis timeBodyAccelerationJerk-StandardDeviation()-X * time-domain signal standard deviation of acceleration jerk in the X axis timeBodyAccelerationJerk-StandardDeviation()-Y * time-domain signal standard deviation of acceleration jerk in the Y axis timeBodyAccelerationJerk-StandardDeviation()-Z * time-domain signal standard deviation of acceleration jerk in the Y axis timeBodyGyro-mean()-X * time-domain signal of mean gyroscopic motion in the X axis timeBodyGyro-mean()-Y * time-domain signal of mean gyroscopic motion in the X axis timeBodyGyro-mean()-Z * time-domain signal of mean gyroscopic motion in the X axis timeBodyGyro-StandardDeviation()-X * time-domain signal of standard deviation of gyroscopic motion in the X axis timeBodyGyro-StandardDeviation()-Y * time-domain signal of standard deviation of gyroscopic motion in the Y axis timeBodyGyro-StandardDeviation()-Z * time-domain signal of standard deviation of gyroscopic motion in the Z axis timeBodyGyroJerk-mean()-X * time-domain signal of mean gyroscopic jerk in the X axis timeBodyGyroJerk-mean()-Y * time-domain signal of mean gyroscopic jerk in the Y axis timeBodyGyroJerk-mean()-Z * time-domain signal of mean gyroscopic jerk in the Z axis timeBodyGyroJerk-StandardDeviation()-X * time-domain signal of standard deviation of gyroscopic jerk in the X axis timeBodyGyroJerk-StandardDeviation()-Y * time-domain signal of standard deviation of gyroscopic jerk in the Y axis timeBodyGyroJerk-StandardDeviation()-Z * time-domain signal of standard deviation of gyroscopic jerk in the Z axis timeBodyAccelerationMag-mean() * time-domain signal of mean of acceleration magnitude timeBodyAccelerationMag-StandardDeviation() * time-domain signal of standard deviation of acceleration magnitude timeGravityAccelerationMag-mean() * time-domain signal of mean of gravity-based acceleration magnitude timeGravityAccelerationMag-StandardDeviation() * time-domain signal of standard deviation of gravity-based acceleration magnitude timeBodyAccelerationJerkMag-mean() * time-domain signal of mean of gravity-based acceleration jerk magnitude timeBodyAccelerationJerkMag-StandardDeviation() * time-domain signal of standard error of gravity-based acceleration jerk magnitude timeBodyGyroMag-mean() * time-domain signal of mean of gyroscopic motion magnitude timeBodyGyroMag-StandardDeviation() * time-domain signal of standard deviation of gyroscopic motion magnitude timeBodyGyroJerkMag-mean() * time-domain signal of mean of gyroscopic jerk magnitude timeBodyGyroJerkMag-StandardDeviation() * time-domain signal of standard deviation of gyroscopic jerk magnitude frequencyBodyAccelerationMean()-X * frequency-domain signal of mean of acceleration in the X axis frequencyBodyAccelerationMean()-Y * frequency-domain signal of mean of acceleration in the Y axis frequencyBodyAccelerationMean()-Z * frequency-domain signal of mean of acceleration in the Z axis frequencyBodyAccelerationStandardDeviation()-X * frequency-domain signal of standard deviation of acceleration in the X axis frequencyBodyAccelerationStandardDeviation()-Y * frequency-domain signal of standard deviation of acceleration in the Y axis frequencyBodyAccelerationStandardDeviation()-Z * frequency-domain signal of standard deviation of acceleration in the Z axis frequencyBodyAccelerationJerk-mean()-X * frequency-domain signal of mean of acceleration jerk in the X axis frequencyBodyAccelerationJerk-mean()-Y * frequency-domain signal of mean of acceleration jerk in the Y axis frequencyBodyAccelerationJerk-mean()-Z * frequency-domain signal of mean of acceleration jerk in the Z axis frequencyBodyAccelerationJerk-StandardDeviation()-X * frequency-domain signal of standard deviation of acceleration jerk in the Z axis frequencyBodyAccelerationJerk-StandardDeviation()-Y * frequency-domain signal of standard deviation of acceleration jerk in the Z axis frequencyBodyAccelerationJerk-StandardDeviation()-Z * frequency-domain signal of standard deviation of acceleration jerk in the Z axis frequencyBodyGyro-mean()-X * frequency-domain signal of mean of gyroscopic motion in the X axis frequencyBodyGyro-mean()-Y * frequency-domain signal of mean of gyroscopic motion in the Y axis frequencyBodyGyro-mean()-Z * frequency-domain signal of mean of gyroscopic motion in the Z axis frequencyBodyGyro-StandardDeviation()-X * frequency-domain signal of standard deviation of gyroscopic motion in the X axis frequencyBodyGyro-StandardDeviation()-Y * frequency-domain signal of standard deviation of gyroscopic motion in the Y axis frequencyBodyGyro-StandardDeviation()-Z * frequency-domain signal of standard deviation of gyroscopic motion in the Z axis frequencyBodyAccelerationMag-mean() * frequency-domain signal of mean of acceleration magnitude frequencyBodyAccelerationMag-StandardDeviation() * frequency-domain signal of standard deviation of acceleration magnitude frequencyBodyAccelerationJerkMag-mean() * frequency-domain signal of mean of acceleration jerk magnitude frequencyBodyAccelerationJerkMag-StandardDeviation() * frequency-domain signal of standard deviation of acceleration jerk magnitude frequencyBodyGyroMag-mean() * frequency-domain signal of mean of gyroscopic motion magnitude frequencyBodyGyroMag-StandardDeviation() * frequency-domain signal of standard deviation of gyroscopic motion magnitude frequencyBodyGyroJerkMag-mean() * frequency-domain signal of mean of gyroscopic jerk magnitude frequencyBodyGyroJerkMag-StandardDeviation() * frequency-domain signal of standard deviation of gyroscopic jerk magnitude<file_sep>/run_analysis.R if (!file.exists("dataset")) download.file("https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip","dataset.zip",method="curl") if (!file.exists("UCI HAR Dataset")) unzip("dataset.zip") test_subject <- read.table("UCI HAR Dataset/test/subject_test.txt") test_labels <- read.table("UCI HAR Dataset/test/y_test.txt") test_features <- read.table("UCI HAR Dataset/test/X_test.txt") test_data <- cbind(test_subject, test_labels, test_features) training_subject <- read.table("UCI HAR Dataset/train/subject_train.txt") training_labels <- read.table("UCI HAR Dataset/train/y_train.txt") training_features <- read.table("UCI HAR Dataset/train/X_train.txt") training_data <- cbind(training_subject, training_labels, training_features) data <- rbind(test_data, training_data) feature_indexes <- c(1:6,41:46,81:86,121:126,161:166,201,202,214,215,227,228,240,241,253,254,266:271,345:350,424:429,503,504,516,517,529,530,542,543) data <- data[,c(1,2,feature_indexes+2)] lookup <- function(val){ switch(val,'WALKING','WALKING UPSTAIRS','WALKING DOWNSTAIRS','SITTING','STANDING','LAYING') } for (i in 1:nrow(data)) data[i,2] <- lookup(as.numeric(data[i,2])) data[,2] <- as.factor(data[,2]) column_headers <- c( "subject", "activity", "timeBodyAcceleration-mean()-X", "timeBodyAccelerationmean()-Y", "timeBodyAccelerationmean()-Z", "timeBodyAccelerationStandardDeviation()-X", "timeBodyAccelerationStandardDeviation()-Y", "timeBodyAccelerationStandardDeviation()-Z", "timeGravityAccelerationmean()-X", "timeGravityAccelerationmean()-Y", "timeGravityAccelerationmean()-Z", "timeGravityAccelerationStandardDeviation()-X", "timeGravityAccelerationStandardDeviation()-Y", "timeGravityAccelerationStandardDeviation()-Z", "timeBodyAccelerationJerk-mean()-X", "timeBodyAccelerationJerk-mean()-Y", "timeBodyAccelerationJerk-mean()-Z", "timeBodyAccelerationJerk-StandardDeviation()-X", "timeBodyAccelerationJerk-StandardDeviation()-Y", "timeBodyAccelerationJerk-StandardDeviation()-Z", "timeBodyGyro-mean()-X", "timeBodyGyro-mean()-Y", "timeBodyGyro-mean()-Z", "timeBodyGyro-StandardDeviation()-X", "timeBodyGyro-StandardDeviation()-Y", "timeBodyGyro-StandardDeviation()-Z", "timeBodyGyroJerk-mean()-X", "timeBodyGyroJerk-mean()-Y", "timeBodyGyroJerk-mean()-Z", "timeBodyGyroJerk-StandardDeviation()-X", "timeBodyGyroJerk-StandardDeviation()-Y", "timeBodyGyroJerk-StandardDeviation()-Z", "timeBodyAccelerationMag-mean()", "timeBodyAccelerationMag-StandardDeviation()", "timeGravityAccelerationMag-mean()", "timeGravityAccelerationMag-StandardDeviation()", "timeBodyAccelerationJerkMag-mean()", "timeBodyAccelerationJerkMag-StandardDeviation()", "timeBodyGyroMag-mean()", "timeBodyGyroMag-StandardDeviation()", "timeBodyGyroJerkMag-mean()", "timeBodyGyroJerkMag-StandardDeviation()", "frequencyBodyAccelerationMean()-X", "frequencyBodyAccelerationMean()-Y", "frequencyBodyAccelerationMean()-Z", "frequencyBodyAccelerationStandardDeviation()-X", "frequencyBodyAccelerationStandardDeviation()-Y", "frequencyBodyAccelerationStandardDeviation()-Z", "frequencyBodyAccelerationJerk-mean()-X", "frequencyBodyAccelerationJerk-mean()-Y", "frequencyBodyAccelerationJerk-mean()-Z", "frequencyBodyAccelerationJerk-StandardDeviation()-X", "frequencyBodyAccelerationJerk-StandardDeviation()-Y", "frequencyBodyAccelerationJerk-StandardDeviation()-Z", "frequencyBodyGyro-mean()-X", "frequencyBodyGyro-mean()-Y", "frequencyBodyGyro-mean()-Z", "frequencyBodyGyro-StandardDeviation()-X", "frequencyBodyGyro-StandardDeviation()-Y", "frequencyBodyGyro-StandardDeviation()-Z", "frequencyBodyAccelerationMag-mean()", "frequencyBodyAccelerationMag-StandardDeviation()", "frequencyBodyAccelerationJerkMag-mean()", "frequencyBodyAccelerationJerkMag-StandardDeviation()", "frequencyBodyGyroMag-mean()", "frequencyBodyGyroMag-StandardDeviation()", "frequencyBodyGyroJerkMag-mean()", "frequencyBodyGyroJerkMag-StandardDeviation()") colnames(data) <- column_headers write.table(data,file="tidy_data.txt",row.name=F)
c621b16f3ee0bb4ff322529168c712f18443621d
[ "Markdown", "R" ]
2
Markdown
arwagner/GettingAndCleaningData
7a8a410f7d4578afd9054ddee5663649c7db7c07
bcdd37624ea73bc8a3f7d21cf56365f50ae430d5
refs/heads/master
<repo_name>djsime1/scraps<file_sep>/future.py from math import * import time import graphics as gr win = gr.GraphWin("f u t u r e",500,500,False) win.setBackground("black") msg = "welcome to the future" ml = [] r = 0 def ez(w,h,o,v=0): global r x = w*cos(radians(r+o))+250 y = h*sin(radians(r+o))+250+v return gr.Point(x,y) for i in range(len(msg)): txt = gr.Text(gr.Point(550+(50*i),75),msg[i]) txt.setFill("white") txt.setSize(25) txt.setStyle("bold") txt.draw(win) ml.append(txt) cube = [] cube.append(gr.Line(ez(150,60,0,-30),ez(150,60,90,-30))) cube.append(gr.Line(ez(150,60,90,-30),ez(150,60,180,-30))) cube.append(gr.Line(ez(150,60,180,-30),ez(150,60,270,-30))) cube.append(gr.Line(ez(150,60,270,-30),ez(150,60,0,-30))) cube.append(gr.Line(ez(150,60,0,150),ez(150,60,90,150))) cube.append(gr.Line(ez(150,60,90,150),ez(150,60,180,150))) cube.append(gr.Line(ez(150,60,180,150),ez(150,60,270,150))) cube.append(gr.Line(ez(150,60,270,150),ez(150,60,0,150))) cube.append(gr.Line(ez(150,60,0,150),ez(150,60,0,-30))) cube.append(gr.Line(ez(150,60,90,150),ez(150,60,90,-30))) cube.append(gr.Line(ez(150,60,180,150),ez(150,60,180,-30))) cube.append(gr.Line(ez(150,60,270,150),ez(150,60,270,-30))) for i in cube: i.setWidth(4) i.setFill("white") i.draw(win) hint = gr.Text(gr.Point(250,75),"c l i c k") hint.setFill("white") hint.setSize(25) hint.setStyle("bold") hint.draw(win) win.getMouse() hint.undraw() while not win.closed: m = win.checkMouse() for i in cube: i.undraw() cube = [] cube.append(gr.Line(ez(150,60,0,-30),ez(150,60,90,-30))) cube.append(gr.Line(ez(150,60,90,-30),ez(150,60,180,-30))) cube.append(gr.Line(ez(150,60,180,-30),ez(150,60,270,-30))) cube.append(gr.Line(ez(150,60,270,-30),ez(150,60,0,-30))) cube.append(gr.Line(ez(150,60,0,150),ez(150,60,90,150))) cube.append(gr.Line(ez(150,60,90,150),ez(150,60,180,150))) cube.append(gr.Line(ez(150,60,180,150),ez(150,60,270,150))) cube.append(gr.Line(ez(150,60,270,150),ez(150,60,0,150))) cube.append(gr.Line(ez(150,60,0,150),ez(150,60,0,-30))) cube.append(gr.Line(ez(150,60,90,150),ez(150,60,90,-30))) cube.append(gr.Line(ez(150,60,180,150),ez(150,60,180,-30))) cube.append(gr.Line(ez(150,60,270,150),ez(150,60,270,-30))) for i in cube: i.setWidth(4) i.setFill("white") i.draw(win) for i in range(len(msg)): ml[i].move(-2,75+(25*sin((r/10)+(i*5)))-ml[i].getAnchor().getY()) if r == 810: for i in ml: i.move(1620,0) r = 0 r += 1 time.sleep(1/60) win.flush()<file_sep>/joystick.py import graphics as gr import math import time win = gr.GraphWin("joystick",500,500,False) ring = gr.Circle(gr.Point(250,250),199) deg = 0 win.setBackground("black") ring.setFill("black") ring.setWidth(2) ring.setOutline("white") ring.draw(win) dot = gr.Circle(gr.Point(0,0),10) dot.setWidth(0) dot.setFill("blue") dot.draw(win) line = gr.Line(gr.Point(0,0),gr.Point(0,0)) line.setFill("green") line.setWidth(2) line.draw(win) win.flush() while not win.closed: mp = win.getCurrentMouseLocation() m = win.checkMouse() s = win.checkScroll() deg += s if m: deg = abs(math.degrees(math.atan2(m.x-250,m.y-250))-180) dot.undraw() dot = gr.Circle(gr.Point(200*math.cos(math.radians(deg-90))+250,200*math.sin(math.radians(deg-90))+250),20) dot.setWidth(0) dot.setFill("red") dot.draw(win) line.undraw() line = gr.Line(gr.Point(250,250),mp) line.setFill("green") line.setWidth(2) line.draw(win) win.flush() time.sleep(1/60)<file_sep>/ball.py # <[ IMPORTS ]> import graphics as gr import time # <[ VARIABLES ]> w = 1400 h = 700 xpos = 150 ypos = 150 xvel = 50 yvel = -50 rad = 50 win = gr.GraphWin("Ball demo",w,h) # <[ FUNCTIONS ]> def bounce(x,y): global xvel global yvel print("Boing!") if x: xvel = xvel*-.8 if y: yvel = yvel*-.8 def moveto(o,x,y=None): if y != None: # X and Y given ox = o.getCenter().x oy = o.getCenter().y dx = x - ox dy = y - oy o.move(dx,dy) else: # Point given y = x.y x = x.x ox = o.getCenter().x oy = o.getCenter().y dx = x - ox dy = y - oy o.move(dx,dy) # <[ MAIN ]> win.setBackground("dimgray") c = gr.Circle(gr.Point(xpos,ypos),rad) c.setFill("seagreen4") c.setWidth(2) c.setOutline("seagreen1") c.draw(win) p = win.getMouse() #moveto(c,p) while True: time.sleep(.015) p = win.checkMouse() if p: moveto(c,p) xvel*=1.2 yvel*=1.2 xpos = c.getCenter().x ypos = c.getCenter().y yvel+=2 if ypos+(yvel/10)>=h-rad or ypos+(yvel/10)<=rad: bounce(0,1) if xpos+(xvel/10)>=w-rad or xpos+(xvel/10)<=rad: bounce(1,0) if ypos <= rad: yvel+=2 c.move(xvel/10,yvel/10) win.close()<file_sep>/README.md # *DJ'(s crap)* ### Assorted python files with HD graphics! Last update: 4/25/2020 [Download zip of all files](https://github.com/djsime1/scraps/archive/master.zip) ## Table of Contents: (In order of most epic to least epic) - graphics.py - spiral.py - future.py - ball.py - joystick.py - skittles.py ## graphics.py The library that does all things! [(Using my forked version)](https://github.com/djsime1/pythonGraphics) ## Spirals! (spiral.py) Points in a sphere. Scroll to modify turn factor. Try setting tf (turn factor) on line 7 to values like 0.5 or the golden ratio. If you're going to increase the count (number of dots) above 500, I recommend commenting out line 21 and changing line 22 to `c.setFill("white")` ## Spinning cube (future.py) 3D vector model proof of concept. ## Bouncing Ball (ball.py) A very simple physics simulation. Click anywhere to teleport and speed up the ball. ## Joystick thing? (joystick.py) Takes a point and returns a degree value upon a circle. Click anywhere to move along circle, or scroll to increase/decrease degree. ## Rainbow road (skittles.py) Used to test my [middle click](https://github.com/djsime1/pythonGraphics/commit/3425d3586adb216c6d6421eb8d16e4785b498053) and [scroll detection](https://github.com/djsime1/pythonGraphics/commit/63820dc7ed55b9c1083d9447774c532257f2ad07) modifications to graphics.py. Scroll to scroll, middle click to print a message.<file_sep>/spiral.py import graphics as gr from math import * from colorsys import hsv_to_rgb import time count = 500 tf = 0 #(1+sqrt(5))/2 #Golden ratio dots = [] win = gr.GraphWin("Spiral",600,600,False) win.setBackground("black") def draw(): global count global dots for i in range(count): dist = sqrt(i/count)*250 ang = 2*pi*tf*i x = dist*cos(ang) y = dist*sin(ang) c = gr.Circle(gr.Point(x+300,y+300),2) v = hsv_to_rgb(i/count,1,1) c.setFill(gr.color_rgb(int(v[0]*255),int(v[1]*255),int(v[2]*255))) c.setWidth(0) c.draw(win) dots.append(c) draw() win.flush() while not win.closed: m = win.checkScroll() if m: for i in dots: i.undraw() dots = [] tf += 0.00001*m draw() win.flush() #time.sleep(1/30)<file_sep>/skittles.py from graphics import * from colorsys import hsv_to_rgb win = GraphWin("taste the rainbow",400,300,False) pos = 0 bars = [] for i in range(360*3): bars.append(Rectangle(Point(0,i*4),Point(400,i*4+4))) bars[i].setWidth(0) r = int(hsv_to_rgb(i/360,1,1)[0]*255) g = int(hsv_to_rgb(i/360,1,1)[1]*255) b = int(hsv_to_rgb(i/360,1,1)[2]*255) bars[i].setFill(color_rgb(r,g,b)) bars[i].move(0,-360*4) bars[i].draw(win) win.flush() while not win.closed: time.sleep(1/60) m = win.checkMouseMiddle() s = win.checkScroll() if m: print("this demo is sponsored by skittles") if s != 0: for i in bars: i.move(0,s*16)
e6f5c559472924a8ff5ff6218a48489675602bd3
[ "Markdown", "Python" ]
6
Python
djsime1/scraps
20fa7e4a57774151fa952bedf9d4df948827386f
1e1abe4715b0e8726c8e4805fedcf65d61940839
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; public class DemoScript : MonoBehaviour { //Unity Inspector variables public string InputText = "Your Right to left text here..."; public RTLService.RTL.NumberFormat NumberFormat = RTLService.RTL.NumberFormat.KeepOriginalFormat; public bool IsLtrText = false; public int WordWrapBias = 0; public GUISkin Skin; public Texture ArrowSign; //private variables string _inputText = ""; RTLService.RTL.NumberFormat _numberFormat; bool _isLtrText = false; int _wordwarpBias = 0; bool _needRefreshText = true; string _convertedText = ""; string strNeededCode = ""; // Update is called once per frame void Update() { _needRefreshText = false; //Check if text parameters are changes if (_inputText != InputText) { _inputText = InputText; _needRefreshText = true; } if (_numberFormat != NumberFormat) { _numberFormat = NumberFormat; _needRefreshText = true; } if (_isLtrText != IsLtrText) { _isLtrText = IsLtrText; _needRefreshText = true; } if (_wordwarpBias != WordWrapBias) { _wordwarpBias = WordWrapBias; _needRefreshText = true; } if (_needRefreshText) { strNeededCode = string.Format("RTLService.RTL.GetText(InputText, RTL.{0}, {1}, {2});", _numberFormat, _isLtrText.ToString().ToLower(), _wordwarpBias); _convertedText = RTLService.RTL.GetText(InputText, _numberFormat, _isLtrText, _wordwarpBias); } } void OnGUI() { GUI.skin = Skin; GUI.color = Color.white; /////////////////////////////////////////////////////////////////////////////////////// GUI.Label(new Rect(6, 4, 600, 20), "RTL Plugin 4.0 : Right to left text format (Arabic, Hebrew, Persian, Afghan, Urdu, Kurd)", Skin.customStyles[2]); /////////////////////////////////////////////////////////////////////////////////////// InputText = GUI.TextArea(new Rect(6, 25, 460, 150), _inputText); GUI.DrawTexture(new Rect(500, 42, 200, 120), ArrowSign, ScaleMode.StretchToFill); GUI.Label(new Rect(565, 90, 200, 120), "Unity's default", Skin.customStyles[0]); /////////////////////////////////////////////////////////////////////////////////////// if (GUI.Button(new Rect(6, 190, 100, 25), "ArabicFormat")) { NumberFormat = RTLService.RTL.NumberFormat.ArabicFormat; } if (GUI.Button(new Rect(104, 190, 100, 25), "EnglishFormat")) { NumberFormat = RTLService.RTL.NumberFormat.EnglishFormat; } if (GUI.Button(new Rect(206, 190, 130, 25), "KeepOriginalFormat")) { NumberFormat = RTLService.RTL.NumberFormat.KeepOriginalFormat; } GUI.Label(new Rect(6, 220, 120, 25), "Number Format :"); switch (NumberFormat) { case RTLService.RTL.NumberFormat.ArabicFormat: GUI.Label(new Rect(112, 220, 130, 25), "ArabicFormat"); break; case RTLService.RTL.NumberFormat.EnglishFormat: GUI.Label(new Rect(112, 220, 130, 25), "EnglishFormat"); break; case RTLService.RTL.NumberFormat.KeepOriginalFormat: GUI.Label(new Rect(112, 220, 130, 25), "KeepOriginalFormat"); break; } GUI.Label(new Rect(6, 240, 120, 25), "Is left to right text :"); IsLtrText = GUI.Toggle(new Rect(125, 240, 25, 25), _isLtrText, ""); GUI.Label(new Rect(150, 240, 100, 25), "WordWarp Bias :"); string newbias = GUI.TextField(new Rect(250, 240, 40, 22), _wordwarpBias.ToString()); int.TryParse(newbias, out WordWrapBias); // GUI.Label(new Rect(6, 298, 352, 25), "RTL source code you would use in Update method:"); GUI.color = Color.green; GUI.Label(new Rect(6, 320, 570, 35), strNeededCode); // GUI.DrawTexture(new Rect(500, 215, 200, 120), ArrowSign, ScaleMode.StretchToFill); GUI.Label(new Rect(570, 265, 190, 120), "RTL Options", Skin.customStyles[0]); /////////////////////////////////////////////////////////////////////////////////////// GUI.color = Color.yellow; GUI.Box(new Rect(6, 362, 464, 154), ""); GUI.Box(new Rect(6, 362, 464, 154), ""); GUI.Label(new Rect(9, 365, 460, 150), _convertedText, Skin.customStyles[1]); GUI.DrawTexture(new Rect(500, 385, 200, 120), ArrowSign, ScaleMode.StretchToFill); GUI.Label(new Rect(574, 435, 190, 120), "RTL Result", Skin.customStyles[0]); /////////////////////////////////////////////////////////////////////////////////////// } } <file_sep>using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.IO; public class GameController : MonoBehaviour { public Sprite[] spriteLetters; public Sprite[] spriteDiacrits; public GameObject letterPrefab; public GameObject diacritPrefab; public GameObject inputPrefab; public TextAsset letterList; public TextAsset module; public float yInput; public float yLetters; private Dictionary<string, Sprite> imgDict; private Dictionary<string, string> transDict; private GameObject letterParent; private GameObject inputBoxParent; private GUIText arabicGUIText; private GUIText transGUIText; private string arabicComma = "\u060C"; private string defaultTransMessage = "Enter an Arabic word to see its translation"; // Use this for initialization void Start () { imgDict = new Dictionary<string, Sprite>(); transDict = CreateTranslationDictionary(module.text); string[] letterArray = letterList.text.Split('\n'); var moduleList = module.text.Split('\n'); var roots = moduleList[0].Split(','); var tiles = moduleList[1].Split(','); foreach (var key in transDict.Keys) { Debug.Log("key: " + key); } // if (transDict.ContainsKey(RTLService.RTL.GetText(moduleList[2].Replace(arabicComma, "")))) // Debug.Log("test successful"); // else // Debug.Log("test failed"); for (int i = 0; i < letterArray.Length; i++) { imgDict.Add(letterArray[i], spriteLetters[i]); } letterParent = new GameObject(); letterParent.name = "Letters"; letterParent.transform.position = new Vector3(0f, yLetters); inputBoxParent = new GameObject(); inputBoxParent.name = "Input Boxes"; inputBoxParent.transform.position = new Vector3(0f, yInput); var leftOffset = ((float)tiles.Length) / 2f - 0.5f; Debug.Log ("LeftOffset = " + leftOffset); for (var i = 0; i < tiles.Length; i++) { var x = leftOffset - (1f * i); CreateLetter(tiles[i], x); } for (var i = 0; i < 9; i++) { if (i < 3 | i > 5) CreateInputBox(i, 6f - 1.5f * i, yInput); else CreateInputBox(i, roots[i-3], 6f - 1.5f * i, yInput); } arabicGUIText = GameObject.Find("Arabic Text GUI").GetComponent<GUIText>(); transGUIText = GameObject.Find("Translation Text GUI").GetComponent<GUIText>(); transGUIText.text = defaultTransMessage; } // Update is called once per frame void Update () { var key = arabicGUIText.text; if (transDict.ContainsKey(key)) { transGUIText.text = transDict[key]; } else { transGUIText.text = defaultTransMessage; } } // // public GameObject[] CreateInputRow(int len, int firstRootChar, float y, string[] rootLetters) { // GameObject[] row = new GameObject[9]; // for (int i = 0; i < len; i++) { // if (i == firstRootChar) { // i += rootLetters.Length - 1; // continue; // } // row[i] = CreateInputBox(i, 6f - 1.5f * i, y); // } // // for (int i = firstRootChar; i < firstRootChar + rootLetters.Length; i++) { // row[i] = CreateInputBox(i, rootLetters[i-firstRootChar], 6f - 1.5f * i, y); // } // return row; // } public GameObject CreateLetter(string character, float xDefault) { Vector3 defaultPosition = new Vector3(xDefault, 0f, -1f); return CreateLetter(character, imgDict[character], defaultPosition); } public GameObject CreateLetter(string character, Sprite sprite, float xDefault) { Vector3 defaultPosition = new Vector3(xDefault, 0f, -1f); return CreateLetter(character, sprite, defaultPosition); } public GameObject CreateLetter(string character, Sprite sprite, Vector3 defaultPosition) { GameObject clone = (GameObject) Instantiate(letterPrefab, defaultPosition, Quaternion.identity); clone.GetComponent<SpriteRenderer>().sprite = sprite; clone.GetComponent<LetterController>().character = character; clone.transform.parent = letterParent.transform; clone.name = character; return clone; } public GameObject CreateInputBox(int index, float x, float y) { return CreateInputBox(index, "", new Vector3(x,y)); } public GameObject CreateInputBox(int index, string rootLetter, float x, float y) { return CreateInputBox(index, rootLetter, new Vector3(x,y)); } public GameObject CreateInputBox(int index, string rootLetter, Vector3 pos) { GameObject clone = (GameObject) Instantiate(inputPrefab, pos, Quaternion.identity); clone.GetComponent<InputBoxController>().Index = index; clone.transform.parent = inputBoxParent.transform; clone.name = "Input Box " + index; if (!rootLetter.Equals("")) { clone.GetComponent<SpriteRenderer>().sprite = imgDict[rootLetter]; clone.GetComponent<InputBoxController>().RootLetter = rootLetter; } return clone; } public Dictionary<string, string> CreateTranslationDictionary(string module) { var dict = new Dictionary<string, string>(); var moduleArray = module.Split('\n'); var key = RTLService.RTL.GetText(moduleArray[2].Replace(arabicComma, "")); Debug.Log(key); Debug.Log(moduleArray[6]); dict.Add(key, moduleArray[6]); for (var i = 7; i < moduleArray.Length; i += 6) { key = RTLService.RTL.GetText(moduleArray[i].Replace(arabicComma, "")); if (!dict.ContainsKey(key)) { Debug.Log(key); Debug.Log(moduleArray[i+5]); dict.Add(key, moduleArray[i+5]); } } return dict; } public string Reverse(string s) { if (s == null) return ""; var charArray = s.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } } <file_sep>Building a game to help teach Arabic to intermediate-level students. You can find a functioning prototype here: http://jbkelleher.com/arabicgame/<file_sep>using UnityEngine; using System.Collections; public class InputTextController : MonoBehaviour { [HideInInspector] public string[] inputArray = new string[9]; private GUIText gText; private string inputString; private string defaultText; // Use this for initialization void Start () { defaultText = "This is where arabic is displayed, yo"; gText = this.gameObject.guiText; gText.text = defaultText; } // Update is called once per frame void Update () { inputString = ""; for (int i = 0; i < inputArray.Length; i++) inputString += inputArray[i]; if (inputString == "") gText.text = defaultText; else gText.text = RTLService.RTL.GetText(inputString); } public void UpdateGUI(string input, int index) { inputArray[index] = input; } } <file_sep>using UnityEngine; using System; using System.IO; using System.Collections; public class LetterController : MonoBehaviour { public string character; public Vector3 defaultPosition; private bool held; private GameObject box; // Use this for initialization void Start () { defaultPosition = transform.position; } // Update is called once per frame void Update () { if (held) { Vector3 newPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); newPosition.z = defaultPosition.z; transform.position = newPosition; } else if (box == null) { var letterParent = GameObject.Find("Letters"); transform.position = defaultPosition + letterParent.transform.position; } //else the tile is left where it is, i.e. in the input box } void OnMouseDown() { held = true; if (box != null) { box.GetComponent<InputBoxController>().EmbeddedTile = null; // box = null; } } void OnMouseUp() { held = false; if (box != null) { GameObject et = box.GetComponent<InputBoxController>().EmbeddedTile; if (et != null) { et.transform.position = et.GetComponent<LetterController>().defaultPosition; et.GetComponent<LetterController>().box = null; } box.GetComponent<InputBoxController>().setET(this); Debug.Log(box.GetComponent<InputBoxController>().EmbeddedTile.Equals(this.gameObject)); Vector3 newPosition = box.transform.position; newPosition.z = defaultPosition.z; this.transform.position = newPosition; } } // public void LetterCollisionReplacement(GameObject coming, GameObject going) { // GameObject box = coming.GetComponent<LetterController>().box; // LetterCollisionReplacement(coming, going, box); // } // // public void LetterCollisionReplacement(GameObject coming, GameObject going, GameObject box) { // going.transform.position = going.GetComponent<LetterController>().defaultPosition; // going.GetComponent<LetterController>().box = null; // box.GetComponent<InputBoxController>().EmbeddedTile = coming; // // Vector3 newPosition = box.transform.position; // newPosition.z = defaultPosition.z; // coming.transform.position = newPosition; // } void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.tag == "InputBox" && !other.gameObject.GetComponent<InputBoxController>().IsRoot) { Debug.Log("Set box: " + other.transform.name); box = other.gameObject; } } void OnTriggerExit2D(Collider2D other) { if (other.gameObject.tag == "InputBox" && other.gameObject == this.box) { InputBoxController bc = other.gameObject.GetComponent<InputBoxController>(); bc.EmbeddedTile = null; Debug.Log("Setting that box to null"); box = null; } } } <file_sep>using UnityEngine; using System; using System.Collections; public class InputBoxController : MonoBehaviour { public int Index; [HideInInspector] public bool Occupied { get; set; } [HideInInspector] public string ETLetter { get; set; } private Sprite defaultSprite; private SpriteRenderer spriteRenderer; private GameObject _embeddedTile; [HideInInspector] public GameObject EmbeddedTile { get { Debug.Log("Getting ET"); return this._embeddedTile; } set { this._embeddedTile = value; Debug.Log ("Setting ET"); if (value == null) { Occupied = false; ETLetter = ""; spriteRenderer.sprite = defaultSprite; } else { Debug.Log("Setting occupied to true"); Occupied = true; ETLetter = this._embeddedTile.GetComponent<LetterController>().character; spriteRenderer.sprite = null; } } } [HideInInspector] public bool IsRoot { get; set; } [HideInInspector] public string RootLetter { get; set; } private InputTextController textControl; public void setET(LetterController lc) { EmbeddedTile = lc.gameObject; } // Use this for initialization void Start () { spriteRenderer = this.gameObject.GetComponent<SpriteRenderer>(); defaultSprite = spriteRenderer.sprite; textControl = GameObject.Find("Arabic Text GUI").GetComponent<InputTextController>(); if (!string.IsNullOrEmpty(RootLetter)) { IsRoot = true; ETLetter = RootLetter; Occupied = true; } else { IsRoot = false; ETLetter = ""; Occupied = false; } } // Update is called once per frame void Update () { textControl.UpdateGUI(ETLetter, Index); } }
bbe5d0c2eaeaee04502ce2b9bf2b5cb234bf319f
[ "C#", "Text" ]
6
C#
jameskelleher/ArabicGame
cda2623ae00b4453a9c30c11b7c6d494a5eea91a
880141461f9863f729f2904f45beefc984f6b2b1
refs/heads/main
<file_sep>/** * Face recognition to detect user's emotion * and check if the user is concentrated */ var app = new Vue({ el: '#app', data: function() { return { visible: false } } }) var emotion = null; var isHere = true; var isConcentrated = true; const video = document.createElement("video"); var mediaStream = null; var studyImage = document.getElementById("studyStatus"); var timeSlots = new Array(); var startTime = null; var startSecond = null; var endTime = null; var slot = null; var concentrationVal = 100; var faq = document.getElementById("faq"); var goToReport = document.getElementById("report"); var website = document.getElementById("website"); var homepage = document.getElementById("homepage"); var free = document.getElementById("free"); var boom = document.getElementById("boom"); var chong = document.getElementById("chong"); var life = document.getElementById("life"); goToReport.addEventListener('click',function(){ chrome.tabs.update({url:"/report.html"}); }); faq.addEventListener('click',function(){ chrome.tabs.create({url:"https://github.com/shawPLUSroot/fOoOcus/issues/5"}); }) website.addEventListener('click',function(){ chrome.tabs.create({url:"/website.html"}); }) free.addEventListener('click',function(){ chrome.tabs.create({url:"/free.html"}); }) chong.addEventListener('click',function(){ chrome.tabs.create({url:"/pomodoro-clock.html"}); }) boom.addEventListener('click',function(){ chrome.tabs.create({url:"/pomodoro-clock.html"}); }) life.addEventListener('click',function(){ chrome.tabs.create({url:"/pomodoro-clock.html"}); }) function getTop(arr){ var yMin = -1; for(var index = 0; index < arr.length; index++){ yMin = Math.min(yMin,arr[index].y); } return yMin; } function getMidPos(arr){ var xSum = 0; var ySum = 0; for(var index = 0; index < arr.length; index++){ xSum = xSum+arr[index].x; ySum = ySum+arr[index].y; } return new Array(xSum/arr.length,ySum/arr.length); } var startMo = document.getElementById("startMonitor"); var stopMo = document.getElementById("stopMonitor"); Promise.all([ faceapi.nets.tinyFaceDetector.loadFromUri("/models"), faceapi.nets.faceLandmark68Net.loadFromUri("/models"), faceapi.nets.faceRecognitionNet.loadFromUri("/models"), faceapi.nets.faceExpressionNet.loadFromUri("/models"), faceapi.nets.ageGenderNet.loadFromUri("/models") ]).then( startMo.addEventListener('click',function(){ activeIt(); }), stopMo.addEventListener('click',function(){ if(mediaStream !== null){ if(mediaStream.active = true){ mediaStream.getTracks()[0].stop(); stopMo.disabled = true; startMo.disabled = false; var myDate = new Date(); var tempHour = myDate.getHours(); var tempMin = myDate.getMinutes(); if(tempMin < 10){ tempMin = "0"+tempMin; } endSecond = myDate.getTime(); slot = endSecond - startSecond; endTime = tempHour + ":" + tempMin; var arr = new Array(); arr[0] = startTime; arr[1] = endTime; arr[2] = slot; arr[3] = concentrationVal; arr[4] = emotion; timeSlots.push(arr); console.log(timeSlots); chrome.storage.sync.set({key: timeSlots},function(){}); } } }) ) function activeIt(){ concentrationVal = 100; stopMo.disabled = false; startMo.disabled = true; var myDate = new Date(); var tempHour = myDate.getHours(); var tempMin = myDate.getMinutes(); startSecond = myDate.getTime(); if(tempMin < 10){ tempMin = "0"+tempMin; } startTime = tempHour + ":" + tempMin; navigator.mediaDevices.getUserMedia({ video: true }).then(stream => { video.autoplay = true; video.srcObject = stream; mediaStream = stream; video.addEventListener('play',()=>{ const displaySize = {width: video.videoWidth,height:video.videoHeight}; const canvas = faceapi.createCanvasFromMedia(video); setInterval(async () => { const detections=await faceapi.detectAllFaces(video,new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions(); const resizedDetections = faceapi.resizeResults(detections,displaySize); canvas.getContext("2d").clearRect(0,0,canvas.width,canvas.height); // Check whether webcam can capture faces if(resizedDetections && Object.keys(resizedDetections).length > 0){ isHere = true; // Get user emotions const expressions = resizedDetections[0].expressions; const maxValue = Math.max(...Object.values(expressions)); const emotionArray = Object.keys(expressions).filter( item => expressions[item] === maxValue ); emotion = emotionArray[0]; // Get user landmarks const landmarks = resizedDetections[0].landmarks; const jaw = getTop(landmarks.getJawOutline()); const nose = new Array(landmarks.getNose()[3].x,landmarks.getNose()[3].y); const mouth = getMidPos(landmarks.getMouth()); const leftEyeBbrow = landmarks.getLeftEyeBrow(); const leftPupil = getMidPos(leftEyeBbrow); const rightEyeBrow = landmarks.getRightEyeBrow(); const rightPupil = getMidPos(rightEyeBrow); const distLeftX = Math.abs(nose[0]-leftPupil[0]); const distRightX = Math.abs(nose[0]-rightPupil[0]); const distLeftY = Math.abs(nose[1]-leftPupil[1]); const distRightY = Math.abs(nose[1]-rightPupil[1]); const absDisX = Math.abs(distLeftX-distRightX); const absDisY = Math.abs(distLeftY-distRightY); isConcentrated = absDisX <= 50 && absDisY <= 20; console.log("Everything works"); getStudyStatus(); }else{ // Unable to detect users isHere=false; getStudyStatus(); } },700) }) });} function getStudyStatus(){ if(!isConcentrated || !isHere){ concentrationVal -=5 studyImage.src='img/distracted.png'; }else{ studyImage.src='img/focus.png'; } }<file_sep><p align="center"> <img src="img/introductionIcon.png"> </p> <p>A chrome extension which allows you to monitor yourself to imporve your study efficiency and learn anything with your own cartoon partner. </p> ## How to start to use Step 1: You can either download the zip file and uncompress it or run the following command in terminal: ```bash git clone https://github.com/shawPLUSroot/fOoOcus.git ``` <p>Step 2: Please open your chrome browser. Next, go to chrome://extensions/ and enable Developer Mode by clicking the toggle switch next to Developer mode.</p> <img src="img/intro.png"> <p>Step 3: Now your browser should be like the image below. Click the Load unpacked button and select the extension fOoOcus directory from where it was cloned to.</p> <img src="img/intro1.png"> ## Inspiration During the COVID-19 tough time, universities and schools have to choose to make classes change from in person into online, students across the world have to adapt it. However, many of them have trouble fitting themselves in time slots of classes, focusing on the contents that the educators tell and doing homework lonely. So we wanted to provide an application for students to imporve their efficiency and help them go through this tough period. ## What's next for fOoOcus Face-api only supports six emotions, in this case, we cannot combine it with the feature of detecting if the user study efficiently and give positive feedback in time. Next, we would train more models to ensure the study partner can "talk" with the user according to their emotions for better learning. Besides, we want to manage a feature for note center, which would make the best advantage of online learning; You can easily select the text from pdf, html and mobi files and store it. Then we would alert you to review according to forgetting curve. ## LICENSE <a href="LICENSE"> <img src="https://img.shields.io/badge/License-MIT-yellow.svg"> </a><file_sep>const states={ START:'start', PAUSE:'pause', STOP:'stop' } const clock_states={ WORK:'work', REST:'rest' } var audio=document.getElementById("sound"); var theme=document.getElementsByClassName("selected"); var minute=25; var second=00; var clock=new Vue({ el:'#container', data(){ return{ minutes:minute, seconds:second, session_value:25, break_value:5, state:states.STOP, clock_state:clock_states.WORK, select:[ {name:"forest",show:true}, {name:"ocean",show:false}, {name:"rainy",show:false}, {name:"peace",show:false}, {name:"cafe",show:false} ], bgs:[ {name:"forest",value:"https://cdn.pixabay.com/photo/2012/09/15/02/22/forest-56930_1280.jpg"}, {name:"ocean",value:"https://cdn.pixabay.com/photo/2017/03/27/14/49/beach-2179183_1280.jpg"}, {name:"rainy",value:"http://imgsrc.baidu.com/image/c0%3Dpixel_huitu%2C0%2C0%2C294%2C40/sign=ff44e1376c09c93d13ff06b7f6459db0/5366d0160924ab18a1784a0e3efae6cd7b890b98.jpg"}, {name:"peace",value:"http://pic1.win4000.com/wallpaper/2/58a53eb5d456e.jpg"}, {name:"cafe",value:"http://pic1.win4000.com/wallpaper/2018-03-16/5aab633f77eb7.jpg"} ] }; }, computed:{ min:function(){ if(this.state===states.STOP){ if(this.minutes!==this.session_value){ this.minutes=this.session_value; } } if(this.minutes<10){ return '0'+this.minutes; } return this.minutes; }, sec:function(){ if(this.seconds<10){ return '0'+this.seconds; } return this.seconds; } }, methods:{ tick:function(){ if(this.seconds!==0){ this.seconds--; return; } if(this.minutes!==0){ this.minutes--; this.seconds=59; return; } //judge work or rest this.clock_state= this.clock_state===clock_states.WORK?clock_states.REST:clock_states.WORK; if(this.clock_state=== clock_states.WORK){ this.minutes=minute; }else { this.minutes=this.break_value; } }, start:function(){ this.state=states.START; this.tick(); this.Interval= setInterval(this.tick,1000); }, stop_clock:function(){ this.state=states.STOP; clearInterval(this.Interval); this.clock_state=clock_states.WORK; this.minutes=minute; this.seconds=0; }, pause_clock:function(){ this.state=states.PAUSE; clearInterval(this.Interval); }, selectsound:function(e){ console.log(this.$refs.con); this.$refs.con.style.background="url("+this.bgs[1].value+")"; this.select.forEach(se=>se.show=false); switch(e.name){ case "forest":audio.setAttribute("src","http://joeweaver.me/codepenassets/freecodecamp/challenges/build-a-pomodoro-clock/forest.mp3"); e.show=true; this.$refs.con.style.backgroundImage="url("+this.bgs[0].value+")"; break; case "ocean": audio.setAttribute("src","http://joeweaver.me/codepenassets/freecodecamp/challenges/build-a-pomodoro-clock/ocean.mp3"); this.$refs.con.style.backgroundImage="url("+this.bgs[1].value+")"; e.show=true; break; case "rainy": audio.setAttribute("src", "http://joeweaver.me/codepenassets/freecodecamp/challenges/build-a-pomodoro-clock/rain.mp3"); this.$refs.con.style.backgroundImage="url("+this.bgs[2].value+")"; e.show=true;break; case "peace": audio.setAttribute("src","http://joeweaver.me/codepenassets/freecodecamp/challenges/build-a-pomodoro-clock/peace.mp3"); this.$refs.con.style.backgroundImage="url("+this.bgs[3].value+")";e.show=true; break; case "cafe": audio.setAttribute("src","http://joeweaver.me/codepenassets/freecodecamp/challenges/build-a-pomodoro-clock/cafe.mp3"); this.$refs.con.style.backgroundImage="url("+this.bgs[4].value+")"; e.show=true;break; } }, //increase&decrease five minutes increSession:function(){ this.session_value+=5; }, decreSession:function(){ this.session_value-=5; }, increBreak:function(){ this.break_value+=5; }, decreBreak:function(){ this.break_value-=5; } } }); var btn = document.getElementById("open_url_new_tab"); btn.addEventListener('click',function(){ chrome.tabs.create({url:"/homePage.html"}); },false)<file_sep>var blockAll = document.getElementById("blockAll"); var blockPart = document.getElementById("blockPart"); var blackList = ["https://facebook.com/","https://www.reddit.com/","https://www.youtube.com/"]; function deleteFromBlackList(url,arr){ var index = arr.indexOf(url); if(index > -1){ arr.splice(index,1); } } function isURL(str) { var pattern = new RegExp('^(https?:\\/\\/)'+ // protocol '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string '(\\#[-a-z\\d_]*)?$','i'); // fragment locator return !!pattern.test(str); } var site = document.getElementById("site"); var addURL = document.getElementById("addURL"); var removeURL = document.getElementById("removeURL"); if(addURL){ addURL.addEventListener('click',function(){ var tempURL = site.value; site.value=""; if(isURL(tempURL)){ blackList.push(tempURL); console.log(blackList); alert("Add successfully"); }else{ alert("URL is not valid"); } }) } if(removeURL){ removeURL.addEventListener('click',function(){ var tempURL = site.value; site.value=""; if(isURL(tempURL)){ deleteFromBlackList(tempURL,blackList); alert("Remove successfully"); }else{ alert("URL is not valid, We can only block url where the format is https://..."); } }) } function blockRequest(details) { return {cancel: (details.url.indexOf("https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js") == -1 && details.url.indexOf("https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js") == -1 && details.url.indexOf("google.com/") == -1 && details.url.indexOf("https://cdn.bootcss.com") == -1 && details.url.indexOf("https://cdn.jsdelivr.net/npm/[email protected]") == -1 && details.url.indexOf("https://cdn.bootcdn.net/ajax/libs/element-ui/2.13.2/index.js") == -1 && details.url.indexOf("https://cdn.bootcdn.net/ajax/libs/element-ui/2.13.2/theme-chalk/index.css") == -1 && details.url.indexOf("https://fonts.googleapis.com/css2?family=Quicksand&display=swap") == -1 && details.url.indexOf("http://joeweaver.me/codepenassets/freecodecamp/challenges/build-a-pomodoro-clock/forest.mp3") == -1 && details.url.indexOf("http://joeweaver.me/codepenassets/freecodecamp/challenges/build-a-pomodoro-clock/ocean.mp3") == -1 && details.url.indexOf("http://joeweaver.me/codepenassets/freecodecamp/challenges/build-a-pomodoro-clock/rain.mp3") == -1 && details.url.indexOf("http://joeweaver.me/codepenassets/freecodecamp/challenges/build-a-pomodoro-clock/peace.mp3") == -1 && details.url.indexOf("http://joeweaver.me/codepenassets/freecodecamp/challenges/build-a-pomodoro-clock/cafe.mp3") == -1 && details.url.indexOf("https://cdn.pixabay.com/photo/2012/09/15/02/22/forest-56930_1280.jpg") == -1 && details.url.indexOf("http://pic1.win4000.com/wallpaper/2018-03-16/5aab633f77eb7.jpg") == -1 && details.url.indexOf("https://cdn.pixabay.com/photo/2017/03/27/14/49/beach-2179183_1280.jpg") == -1 && details.url.indexOf("http://imgsrc.baidu.com/image/c0%3Dpixel_huitu%2C0%2C0%2C294%2C40/sign=ff44e1376c09c93d13ff06b7f6459db0/5366d0160924ab18a1784a0e3efae6cd7b890b98.jpg") == -1 && details.url.indexOf("http://pic1.win4000.com/wallpaper/2/58a53eb5d456e.jpg") == -1 )}; } function blockAllWeb(){ chrome.webRequest.onBeforeRequest.addListener( blockRequest, {urls: ["http://*/*", "https://*/*"] }, ["blocking"] ); } function blockPartWeb(){ chrome.webRequest.onBeforeRequest.removeListener( blockRequest, {urls: ["http://*/*", "https://*/*"] }, ["blocking"] ); chrome.webRequest.onBeforeRequest.addListener( blockRequest, {urls: blackList }, ["blocking"] ); } if(blockAll){ blockAll.addEventListener('click',function(){ blockAllWeb(); alert("You have blocked all websites except for google and some other ones to ensure the extension can run normally.") }) } if(blockPart){ blockPart.addEventListener('click',function(){ blockPartWeb(); alert("You have blocked all blacklist websites!") }) }
b92732e3cc83a673b32f5267f70e29c65c68309e
[ "JavaScript", "Markdown" ]
4
JavaScript
shawPLUSroot/fOoOcus
0a318a6cb9cc02a1306ff589d6da0e4348b6f88b
6daec5a1af9de7d5463a0d7f1d9c6834f801b97f
refs/heads/master
<repo_name>xaviibaez/Android-Data-Base-SQLite<file_sep>/app/src/main/java/com/example/pc/mecagoenmismuertosv5/PreferenciesColors.java package com.example.pc.mecagoenmismuertosv5; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toolbar; /** * Created by Pc on 17/01/2018. */ public class PreferenciesColors extends AppCompatActivity{ Toolbar mToolbar; Button mRedColor; Button mGreenColor; Button mYellowColor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_preferencies_colors); Log.i("XAVI", "1"); mToolbar = (Toolbar) findViewById(R.id.toolbar); Log.i("XAVI", "2"); mRedColor = (Button) findViewById(R.id.btnRed); mGreenColor = (Button) findViewById(R.id.btnGreen); mYellowColor = (Button) findViewById(R.id.btnYellow); mToolbar.setTitle(getResources().getString(R.string.app_name)); if(getColor() != getResources().getColor(R.color.colorPrimary)){ mToolbar.setBackgroundColor(getColor()); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ getWindow().setStatusBarColor(getColor()); } storeColor(getResources().getColor(R.color.colorRed)); } mRedColor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mToolbar.setBackgroundColor(getResources().getColor(R.color.colorRed)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ getWindow().setStatusBarColor(getResources().getColor(R.color.colorRed)); } storeColor(getResources().getColor(R.color.colorRed)); } }); mGreenColor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mToolbar.setBackgroundColor(getResources().getColor(R.color.colorGreen)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ getWindow().setStatusBarColor(getResources().getColor(R.color.colorGreen)); } storeColor(getResources().getColor(R.color.colorGreen)); } }); mYellowColor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mToolbar.setBackgroundColor(getResources().getColor(R.color.colorYellow)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ getWindow().setStatusBarColor(getResources().getColor(R.color.colorYellow)); } storeColor(getResources().getColor(R.color.colorYellow)); } }); } private void storeColor(int color){ SharedPreferences mSharedPreferences = getSharedPreferences("ToolbarColor", MODE_PRIVATE); SharedPreferences.Editor mEditor = mSharedPreferences.edit(); mEditor.putInt("color", color); mEditor.apply(); } private int getColor(){ SharedPreferences mSharedPreferences = getSharedPreferences("ToolbarColor", MODE_PRIVATE); int selectedColor = mSharedPreferences.getInt("color", getResources().getColor(R.color.colorPrimary)); return selectedColor; } } <file_sep>/app/src/main/java/com/example/pc/mecagoenmismuertosv5/PreferenciesNormalsLoginMuyCutre.java package com.example.pc.mecagoenmismuertosv5; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import android.widget.TextView; /** * Created by Pc on 22/01/2018. */ public class PreferenciesNormalsLoginMuyCutre extends AppCompatActivity{ EditText campUser, campPass; TextView txtUser, txtPass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_preferencies_cutre); campUser = (EditText) findViewById(R.id.campUser); campPass = (EditText) findViewById(R.id.campPass); txtUser = (TextView) findViewById(R.id.txtUser); txtPass = (TextView) findViewById(R.id.txtPass); setToolbar();// Añadir action bar if (getSupportActionBar() != null) // Habilitar up button getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void setToolbar() { // Añadir la Toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } public void onClick(View view) { Intent miIntent = null; switch (view.getId()){ case R.id.btnGuardar: guardarPrefencies(); break; case R.id.btnCarregar: //miIntent = new Intent(ConsultaPreferenciesCutre.this, PreferenciesIdioma.class); carregarPreferencies(); break; } if (miIntent!=null){ startActivity(miIntent); } } private void carregarPreferencies(){ SharedPreferences preferences = getSharedPreferences("credencials", Context.MODE_PRIVATE); String user = preferences.getString("user","No existeix"); String pass = preferences.getString("pass","No existeix"); txtUser.setText(user); txtPass.setText(pass); } private void guardarPrefencies(){ SharedPreferences preferences = getSharedPreferences("credencials", Context.MODE_PRIVATE); String user = campUser.getText().toString(); String pass = campPass.getText().toString(); SharedPreferences.Editor editor = preferences.edit(); editor.putString("user", user); editor.putString("pass", pass); editor.commit(); campUser.setText(""); campPass.setText(""); } } <file_sep>/app/src/main/java/com/example/pc/mecagoenmismuertosv5/RegistreUsuariActivity.java package com.example.pc.mecagoenmismuertosv5; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.Toast; import android.support.v7.widget.Toolbar; import com.example.pc.mecagoenmismuertosv5.utilitats.Utilitats; /** * Created by Pc on 11/01/2018. */ public class RegistreUsuariActivity extends AppCompatActivity { EditText campId, campNom, campCognom, campTelefon; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registre_usuari); campId = (EditText) findViewById(R.id.campIdUsuari); campNom = (EditText) findViewById(R.id.campNom); campCognom = (EditText) findViewById(R.id.campCognom); campTelefon= (EditText) findViewById(R.id.campTelefon); setToolbar();// Añadir action bar if (getSupportActionBar() != null) // Habilitar up button getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void setToolbar() { // Añadir la Toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } public void onClick(View view) { registrarUsuaris(); } private void registrarUsuaris() { ConexioSQLiteHelper con = new ConexioSQLiteHelper(this,"bd_usuaris",null,1); SQLiteDatabase db = con.getWritableDatabase(); String insert = "INSERT INTO " + Utilitats.TAULA_USUARI + " ( " + Utilitats.ID_USUARI + "," + Utilitats.NOM_USUARI + "," + Utilitats.COGNOM_USUARI + "," + Utilitats.TELEFON_USUARI + ")" + " VALUES (" + campId.getText().toString() + ", '" + campNom.getText().toString() + "','" + campCognom.getText().toString() + "','" + campTelefon.getText().toString() + "')"; Toast.makeText(getApplicationContext(),"Usuari registrat", Toast.LENGTH_LONG).show(); netejar(); db.execSQL(insert); db.close(); } private void netejar() { campId.setText(""); campNom.setText(""); campCognom.setText(""); campTelefon.setText(""); } } <file_sep>/app/src/main/java/com/example/pc/mecagoenmismuertosv5/ConsultaUsuariRecycler.java package com.example.pc.mecagoenmismuertosv5; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import com.example.pc.mecagoenmismuertosv5.adaptadors.LlistaUsuarisAdapter; import com.example.pc.mecagoenmismuertosv5.entitats.Usuari; import com.example.pc.mecagoenmismuertosv5.utilitats.Utilitats; import java.util.ArrayList; /** * Created by Pc on 16/01/2018. */ public class ConsultaUsuariRecycler extends AppCompatActivity { ArrayList<Usuari> llistaUsuaris; RecyclerView recyclerViewUsuaris; ConexioSQLiteHelper con; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_consulta_usuari_recycler); con = new ConexioSQLiteHelper(getApplicationContext(),"bd_usuaris",null,1); llistaUsuaris = new ArrayList<>(); recyclerViewUsuaris = (RecyclerView) findViewById(R.id.recyclerUsuaris); recyclerViewUsuaris.setLayoutManager(new LinearLayoutManager(this)); consultarLlistaUsuaris(); LlistaUsuarisAdapter adapter = new LlistaUsuarisAdapter(llistaUsuaris); recyclerViewUsuaris.setAdapter(adapter); setToolbar();// Añadir action bar if (getSupportActionBar() != null) // Habilitar up button getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void setToolbar() { // Añadir la Toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } private void consultarLlistaUsuaris() { SQLiteDatabase db = con.getReadableDatabase(); Usuari usuari = null; // listaUsuarios=new ArrayList<Usuario>(); Cursor cursor = db.rawQuery("SELECT * FROM "+ Utilitats.TAULA_USUARI,null); while (cursor.moveToNext()){ usuari = new Usuari(); usuari.setId_usuari(cursor.getInt(0)); usuari.setNom(cursor.getString(1)); usuari.setCognom(cursor.getString(2)); usuari.setTelefon(cursor.getString(3)); llistaUsuaris.add(usuari); } } } <file_sep>/app/src/main/java/com/example/pc/mecagoenmismuertosv5/utilitats/Utilitats.java package com.example.pc.mecagoenmismuertosv5.utilitats; /** * Created by Pc on 11/01/2018. */ public class Utilitats { //Constants taula usuari public static final String TAULA_USUARI = "usuari"; public static final String ID_USUARI = "id_usuari"; public static final String NOM_USUARI = "nom"; public static final String COGNOM_USUARI = "cognom"; public static final String TELEFON_USUARI ="telefon"; public static final String CREAR_TAULA_USUARI = "CREATE TABLE " + TAULA_USUARI + " (" + ID_USUARI + " INTEGER PRIMARY KEY AUTOINCREMENT, " //INTEGER + NOM_USUARI + " TEXT," + COGNOM_USUARI + " TEXT," + TELEFON_USUARI + " TEXT" + ")"; //Constants taula productes public static final String TAULA_PRODUCTE = "producte"; public static final String ID_PRODUCTE = "id_producte"; public static final String NOM_PRODUCTE = "nom_producte"; public static final String QUANTITAT_PRODUCTE = "quantitat"; public static final String ID_COMPRADOR = "id_comprador"; public static final String CREAR_TAULA_PRODUCTE = "CREATE TABLE " + TAULA_PRODUCTE + " (" + ID_PRODUCTE +" INTEGER PRIMARY KEY AUTOINCREMENT, " + NOM_PRODUCTE +" TEXT, " + QUANTITAT_PRODUCTE +" INTEGER," + ID_COMPRADOR +" INTEGER" + ")"; } <file_sep>/app/src/main/java/com/example/pc/mecagoenmismuertosv5/ConsultaProducteOpcions.java package com.example.pc.mecagoenmismuertosv5; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.example.pc.mecagoenmismuertosv5.utilitats.Utilitats; /** * Created by Pc on 18/01/2018. */ public class ConsultaProducteOpcions extends AppCompatActivity { EditText documentID,campNomConsulta, campQuantitat; ConexioSQLiteHelper con; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_consulta_producte_eliminar_editar); con = new ConexioSQLiteHelper(getApplicationContext(),"bd_usuaris",null,1); documentID = (EditText) findViewById(R.id.documentID); campNomConsulta = (EditText) findViewById(R.id.campNomConsulta); campQuantitat = (EditText) findViewById(R.id.campQuantitat); setToolbar();// Añadir action bar if (getSupportActionBar() != null) // Habilitar up button getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void setToolbar() { // Añadir la Toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } public void onClick(View view) { switch (view.getId()){ case R.id.btnConsultar: consultarUsuari(); break; case R.id.btnActualitzar: actualizarUsuario(); break; case R.id.btnEliminar: eliminarUsuario(); break; } } private void eliminarUsuario() { SQLiteDatabase db = con.getWritableDatabase(); String[] parametres = {documentID.getText().toString()}; db.delete(Utilitats.TAULA_PRODUCTE,Utilitats.ID_PRODUCTE + "=?", parametres); Toast.makeText(getApplicationContext(),"Producte eliminat", Toast.LENGTH_LONG).show(); documentID.setText(""); netejar(); db.close(); } private void actualizarUsuario() { SQLiteDatabase db = con.getWritableDatabase(); String[] parametres = {documentID.getText().toString()}; ContentValues values = new ContentValues(); values.put(Utilitats.NOM_PRODUCTE,campNomConsulta.getText().toString()); values.put(Utilitats.QUANTITAT_PRODUCTE,campQuantitat.getText().toString()); db.update(Utilitats.TAULA_PRODUCTE, values,Utilitats.ID_PRODUCTE + "=?", parametres); Toast.makeText(getApplicationContext(),"Producte actualitzat",Toast.LENGTH_LONG).show(); netejar(); db.close(); } private void consultarUsuari() { SQLiteDatabase db = con.getReadableDatabase(); String[] parametres = {documentID.getText().toString()}; try { Cursor cursor = db.rawQuery("SELECT " + Utilitats.NOM_PRODUCTE + "," + Utilitats.QUANTITAT_PRODUCTE + " FROM " + Utilitats.TAULA_PRODUCTE + " WHERE " + Utilitats.ID_PRODUCTE + "=?", parametres); cursor.moveToFirst(); campNomConsulta.setText(cursor.getString(0)); campQuantitat.setText(cursor.getString(1)); }catch (Exception e){ Toast.makeText(getApplicationContext(),"El document no existeix", Toast.LENGTH_LONG).show(); netejar(); } } private void netejar() { campNomConsulta.setText(""); campQuantitat.setText(""); } } <file_sep>/app/src/main/java/com/example/pc/mecagoenmismuertosv5/OpcionsConsultaUsuari.java package com.example.pc.mecagoenmismuertosv5; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.support.v7.widget.Toolbar; /** * Created by Pc on 16/01/2018. */ public class OpcionsConsultaUsuari extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_opcions_consulta_usuari); ConexioSQLiteHelper con = new ConexioSQLiteHelper(this,"bd_usuaris",null,1); setToolbar();// Añadir action bar if (getSupportActionBar() != null) // Habilitar up button getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void setToolbar() { // Añadir la Toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } public void onClick(View view) { Intent miIntent = null; switch (view.getId()){ case R.id.btnConsultaNormal: miIntent = new Intent(OpcionsConsultaUsuari.this, ConsultaUsuari.class); break; case R.id.btnConsultaRecycler: miIntent = new Intent(OpcionsConsultaUsuari.this, ConsultaUsuariRecycler.class); break; } if (miIntent!=null){ startActivity(miIntent); } } } <file_sep>/app/src/main/java/com/example/pc/mecagoenmismuertosv5/DetallProducte.java package com.example.pc.mecagoenmismuertosv5; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import android.support.v7.widget.Toolbar; import com.example.pc.mecagoenmismuertosv5.entitats.Producte; import com.example.pc.mecagoenmismuertosv5.utilitats.Utilitats; /** * Created by Pc on 13/01/2018. */ public class DetallProducte extends AppCompatActivity { ConexioSQLiteHelper con; TextView campIdProducte, campNomProducte, campQuantitat; TextView campIdUsuari, campNomUsuari, campCognomUsuari, campTelefonUsuari; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detall_producte); con = new ConexioSQLiteHelper(getApplicationContext(),"bd_usuaris",null,1); campIdUsuari = (TextView) findViewById(R.id.campIdUsuari); campNomUsuari = (TextView) findViewById(R.id.campNom); campCognomUsuari = (TextView) findViewById(R.id.campCognom); campTelefonUsuari = (TextView) findViewById(R.id.campTelefon); campIdProducte = (TextView) findViewById(R.id.campIdProducte); campNomProducte = (TextView) findViewById(R.id.campNomProducte); campQuantitat = (TextView) findViewById(R.id.campQuantitat); Bundle producteEnviat = getIntent().getExtras(); Producte producte = null; if(producteEnviat!=null){ producte= (Producte) producteEnviat.getSerializable("producte"); campIdProducte.setText(String.valueOf(producte.getId_producte())); campNomProducte.setText(producte.getNom_producte().toString()); campQuantitat.setText(String.valueOf(producte.getQuantitat())); consultarPersona(producte.getId_comprador()); } setToolbar();// Añadir action bar if (getSupportActionBar() != null) // Habilitar up button getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void setToolbar() { // Añadir la Toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } private void consultarPersona(Integer idPersona) { SQLiteDatabase db = con.getReadableDatabase(); try { String superConsulta = "SELECT " + Utilitats.ID_USUARI + ", " + Utilitats.NOM_USUARI + ", " + Utilitats.COGNOM_USUARI + ", " + Utilitats.TELEFON_USUARI + " FROM " + Utilitats.TAULA_USUARI + " WHERE " + Utilitats.ID_USUARI + " = " + idPersona.toString(); Cursor c = db.rawQuery(superConsulta, null); if(c != null){ c.moveToFirst(); } campIdUsuari.setText(c.getString(0)); campNomUsuari.setText(c.getString(1)); campCognomUsuari.setText(c.getString(2)); campTelefonUsuari.setText(c.getString(3)); c.close(); db.close(); } catch (Exception e){ Toast.makeText(getApplicationContext(),"El document no existeix", Toast.LENGTH_LONG).show(); campIdUsuari.setText(""); campNomUsuari.setText(""); campCognomUsuari.setText(""); campTelefonUsuari.setText(""); } } } <file_sep>/app/src/main/java/com/example/pc/mecagoenmismuertosv5/ConexioSQLiteHelper.java package com.example.pc.mecagoenmismuertosv5; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.example.pc.mecagoenmismuertosv5.utilitats.Utilitats; /** * Created by Pc on 11/01/2018. */ public class ConexioSQLiteHelper extends SQLiteOpenHelper { public ConexioSQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(Utilitats.CREAR_TAULA_USUARI); db.execSQL(Utilitats.CREAR_TAULA_PRODUCTE); } @Override public void onUpgrade(SQLiteDatabase db, int versioAntiga, int versioNova) { db.execSQL("DROP TABLE IF EXISTS " + Utilitats.TAULA_USUARI); db.execSQL("DROP TABLE IF EXISTS " + Utilitats.TAULA_PRODUCTE); onCreate(db); } } <file_sep>/app/src/main/java/com/example/pc/mecagoenmismuertosv5/entitats/Usuari.java package com.example.pc.mecagoenmismuertosv5.entitats; import java.io.Serializable; /** * Created by Pc on 11/01/2018. */ public class Usuari implements Serializable { private int id_usuari; private String nom, cognom, telefon; public Usuari(int id_usuari, String nom, String telefon) { this.id_usuari = id_usuari; this.nom = nom; this.telefon = telefon; } public Usuari(){ } public int getId_usuari() { return id_usuari; } public void setId_usuari(int id_usuari) { this.id_usuari = id_usuari; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getCognom() { return cognom; } public void setCognom(String cognom) { this.cognom = cognom; } public String getTelefon() { return telefon; } public void setTelefon(String telefon) { this.telefon = telefon; } }
522c03504f29a279a8e03212e6ef7df4517b7f6f
[ "Java" ]
10
Java
xaviibaez/Android-Data-Base-SQLite
86d6fda876a97393a8bed711389f88f5692d46e1
6fa5f8d740eaf1dbdcbb9138dc0fd296d28160ff
refs/heads/master
<file_sep>class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable before_create :check_domain enum role: [:business , :manager, :employee] scope :managers, ->(domain){where("role_type like 'manager' && domain = ?",domain)} def business? true if self.role_type == "business" end def manager? true if self.role_type == "manager" end private def check_domain domain = self.email.split("@").last if User.where("domain = ?",domain).any? self.role_type = :employee else self.role_type = :business end end end <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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) user = CreateAdmin.new.call puts 'CREATED ADMIN USER: ' << user.email User.create( [ {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "business"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "manager"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "employee"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "employee"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "employee"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "employee"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "employee"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "employee"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "employee"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "employee"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "employee"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "employee"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "employee"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "employee"}, {email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", role_type: "employee"}, ]) <file_sep>class UsersController < ApplicationController before_filter :authenticate_user! after_action :verify_authorized, except: [:show] before_filter :set_user,except: [:index, :show] def index @users = User.all authorize @users end def show @user = User.find(params[:id]) unless current_user.business? unless @user == current_user redirect_to root_path, :alert => "Access denied." end end end def edit end def update if @user.update_attributes(secure_params) redirect_to users_path, :notice => "User updated." else redirect_to users_path, :alert => "Unable to update user." end end def destroy unless user == current_user user.destroy redirect_to users_path, :notice => "User deleted." else redirect_to users_path, :notice => "Can't delete yourself." end end def add_employee @users = User.where("domain = ? && role_type like 'employee' && manager_id = '' ",@user.domain) if @users.empty? gflash :now, :error => "There is no unallocated employees" end authorize @users if params[:user_id].present? User.where("id in (?)",params[:user_id].values.map(&:to_i)).update_all(:manager_id => params[:id]) end end private def secure_params params.require(:user).permit(:email,:role_type) end def set_user @user = User.find(params[:id]) authorize @user end end
f5af872b903d4473508aa73baa177e72b8d0695c
[ "Ruby" ]
3
Ruby
ankita-agrawal24/role_based_system
7cb0c0a43edc25ca94fcb7aebd9a84983703e7aa
5b30983ba581e024628b2bc4c0bc3e0b839a957d
refs/heads/main
<file_sep>from finviz.screener import Screener import finviz import threading import alpaca_trade_api as tradeapi skey = "Insert Secret Key" apiKey = "Insert API Key" apiEndpoint = "Insert Endpoint" api = tradeapi.REST(apiKey,skey) watchList = [ "TSLA","AMD","NVDA","XLNX","MSFT","NFLX","SPY","AAPL","DIS","FB","NIO","AMZN","TWTR" ] def isMarketOpen(): clock = api.get_clock() return clock.is_open def positionExists(symbol,portfolio): for position in portfolio: if (symbol == position.symbol): return True return False def buyStock(sym,amount): print("Buying {} shares of {}".format(amount,sym)) api.submit_order( symbol=sym, qty=amount, side='buy', type='market', time_in_force='gtc' ) def sellStock(sym,amount): api.submit_order( symbol=sym, qty=amount, side='sell', type='market', time_in_force='opg', ) def autoTrade(): while (isMarketOpen()): account = api.get_account() if account.trading_blocked: print('Account is currently restricted from trading.') return buyingpower = account.buying_power #start by opening new positions limitPerStock = buyingpower/len(watchList) print("Buying Power {}".format(buyingpower)) print("Limit Per Stock {}".format(limitPerStock)) portfolio = api.list_positions() for i in watchList(): if (positionExists(i,portfolio)): continue else: data = finviz.get_stock(i) sma20 = float(data['SMA20'].replace("%","")) if (sma20 < 0): #we buy the stock price = float(data['Price']) quanitity = 0 while ((quanitity+1) * price < limitPerStock and (quanitity+1) * price < buyingpower): quanitity += 1 if (quanitity == 0): continue buyStock(i,limitPerStock) for position in portfolio: profit = position.unrealized_pl percentChange = (profit/position.cost_basis) * 100 if (percentChange > 5): sellStock(position.symbol,position.qty) print("Market is Closed") autoTrade()
ec2c0723453060d9fa2e759250876d8cb1ccf5f2
[ "Python" ]
1
Python
nickrr7001/SMA20-Trading-Bot
5d181b6d607a7e31d8ae6a3a089c7c5138de6766
9a89fb635d6736319619b011acc0953a66420a31
refs/heads/master
<file_sep>**<NAME> Personal Project** # PyMC3 Examples `pymc3_examples` ##### 2019Q4 Experimental models to demonstrate `pymc3` capabilities. Where suitable, I will submit these Notebooks for inclusion in the [pymc3 documentation](https://docs.pymc.io/nb_examples/index.html) Note: + Each Notebook is designed to be standalone with a suggested MVP condaenv install, but you can also just install the env for this project. + This project is hosted publicly on [GitHub](https://github.com/jonsedar/pymc3_examples). + This README is MacOS oriented --- # 1. Setup Development Environment ## 1.1 Libraries, Compilers, IDEs ### 1.1.1 Continuum Anaconda Python 64bit This repo uses Python 3.6.* Download Anaconda distro at [https://www.continuum.io/downloads](https://www.continuum.io/downloads) ### 1.1.2 C++ compiler Theano devs recommend using `clang` (aka `clang++`) by default which you can install using Xcode Command Line Tools ```zsh $> xcode-select --install ``` It's also possible to use g++ (gcc), but in my experience that's about 1/2 the speed. e.g. install via Homebrew ```zsh $> brew update && brew upgrade `brew outdated` $> brew install gcc ``` ...optional cleanup of old versions afterwards ```zsh $> brew cleanup ``` Note: 1. By default `gcc` is symlinked / points to `clang` on MacOS 2. It _is_ possible to install a particular version of `gcc` via Homebrew, but this gets installed to a versioned dir e.g. `/usr/local/Cellar/gcc/9.3.0_1/bin/gcc-9` and by default is not symlinked from `gcc`, rather it is available as `gcc-9` 3. Regardless, it is best to use `clang` because theano is/was developed to this and is optimized (much faster) 4. Note you then don't need to configure the cxx in `.theanorc`, it uses `clang` by default ## 1.2 Configs, Dotfiles ### 1.2.1 Global git config `~/.gitconfig` ``` yaml [user] name = $YOUR_USERNAME email = $YOUR_EMAIL [filter "lfs"] clean = git-lfs clean -- %f smudge = git-lfs smudge -- %f process = git-lfs filter-process required = true ``` ### 1.2.2 Theano config `~/.theanorc` ``` yaml [global] device=cpu ``` ### 1.2.3 Optional: jupyter configs if not already setup ```zsh $> jupyter notebook --generate-config $> jupyter qtconsole --generate-config $> jupyter nbconvert --generate-config ``` ## 1.3 Clone Code and Create Environment ### 1.3.1 Git clone the repo to your workspace ```zsh $> git clone https://github.com/jonsedar/pymc3_examples.git $> cd pymc3_examples/ ``` ### 1.3.2 Setup a virtual environment for Python libraries **IMPORTANT NOTE:** We're not using the latest python here because we want stability for the `pymc3` and `theano` installs. Pay extra attention to the `.theanorc` config ```zsh $> conda env create --file condaenv_pymc3_examples.yml $> activate pymc3_examples ``` Cheat sheet of conda commands available [online here](https://conda.io/docs/_downloads/conda-cheatsheet.pdf). #### b. Additional packages via pip ```zsh $> /.pip_install.sh ``` #### c. Additional jupyterlab theme Requires [NodeJS](https://nodejs.org/en/) ```zsh $> jupyter labextension install @telamonian/theme-darcula ``` ### 1.3.3 Test installation of scientific packages A quick and cheap way to confirm your binaries are good and the installation works! #### 1.3.3.1 Test BLAS / MKL config View the BLAS / MKL install ``` zsh $> python -c "import numpy as np; np.__config__.show()" ``` Example output... ```zsh mkl_info: libraries = ['mkl_rt', 'pthread'] library_dirs = ['/Users/jon/anaconda/envs/pymc3_examples/lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['/Users/jon/anaconda/envs/pymc3_examples/include'] blas_mkl_info: libraries = ['mkl_rt', 'pthread'] library_dirs = ['/Users/jon/anaconda/envs/pymc3_examples/lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['/Users/jon/anaconda/envs/pymc3_examples/include'] blas_opt_info: libraries = ['mkl_rt', 'pthread'] library_dirs = ['/Users/jon/anaconda/envs/pymc3_examples/lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['/Users/jon/anaconda/envs/pymc3_examples/include'] lapack_mkl_info: libraries = ['mkl_rt', 'pthread'] library_dirs = ['/Users/jon/anaconda/envs/pymc3_examples/lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['/Users/jon/anaconda/envs/pymc3_examples/include'] lapack_opt_info: libraries = ['mkl_rt', 'pthread'] library_dirs = ['/Users/jon/anaconda/envs/pymc3_examples/lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['/Users/jon/anaconda/envs/pymc3_examples/include'] ``` #### 1.3.3.2 Test `numpy` install ``` zsh $> python -c "import numpy as np; np.test()" ``` Example output... ```zsh 7285 passed, 80 skipped, 167 deselected, 12 xfailed, 3 xpassed, 2 warnings in 355.51 seconds ``` #### 1.3.3.3 Test `scipy` install ``` zsh $> python -c "import scipy as sp; sp.test()" ... many tests will run and output a results summary e.g. ... ``` Example output... ```zsh 14522 passed, 1274 skipped, 1225 deselected, 79 xfailed, 10 xpassed, 25 warnings in 777.53 seconds ``` #### 1.3.3.4 OPTIONAL Test `pymc3` install Method 1: ```zsh $> python -m pytest -xv --cov=pymc3 --cov-report=html pymc3/ ``` Method 2: Takes ~90mins on my Macbook 2017 :/ ``` zsh $> python -c "import pymc3 as pm; pm.test()" ``` Example output... ```zsh TBD ``` #### 1.3.3.5 OPTIONAL Test `theano` install Takes forever, see [installation docs](http://deeplearning.net/software/theano/install_macos.html) Quicker: ``` zsh $> python -c "import theano; theano.test()" ``` Alternative (takes ~3 hours) ``` zsh $> theano-nose -s ... many tests will run and output a results summary e.g. ... ``` ## 1.4 General Python Dev - Useful stuff ### 1.4.1 List large objects currently consuming RAM As per [https://stackoverflow.com/questions/40993626/list-memory-usage-in-ipython-and-jupyter](https://stackoverflow.com/questions/40993626/list-memory-usage-in-ipython-and-jupyter) ``` python import sys # These are the usual ipython objects, including this one you are creating ipython_vars = ['In', 'Out', 'exit', 'quit', 'get_ipython', 'ipython_vars'] # Get a sorted list of the objects and their sizes sorted([(x, sys.getsizeof(globals().get(x))) for x in dir() if not x.startswith('_') and x not in sys.modules and x not in ipython_vars], key=lambda x: x[1], reverse=True) ``` ### 1.4.2 Clean up conda packages Remove unused packages and tarballs etc as explained [https://conda.io/docs/commands/conda-clean.html](https://conda.io/docs/commands/conda-clean.html) ``` zsh $> conda clean -v -a ``` NOTE @2019-01-19 there's an [open bug](https://github.com/conda/conda/pull/7149) in `conda` on Windows that the `~/AppData/Local/Continuum/Anaconda3/pkgs/.trash` directory needs manual emptying afterwards ### 1.4.3 Specify number of CPUs for MKL to use Ought to provide a speed-boost for MKL operations (many numpy, scipy operations under the hood). See [docs](https://docs.anaconda.com/mkl-service/) ```zsh $> python -c "import mkl; mkl.set_num_threads(4); print(mkl.get_max_threads()) 4 ``` ### 1.4.4 MVP Jupyter Widget Interactive widgets are cool. Beware potential issue with lax requirements. Ensure `conda_*.yaml` contains correct pairs of : ```yaml - ipywidgets==6.0.0 - widgetsnbextension==2.* ``` ```python from ipywidgets import widgets from IPython.display import display text = widgets.Text() text.on_submit(lambda x: print('hello {}'.format(x.value))) display(text) ``` ### 1.4.5 Basic debugging / introspection Straight breakpoint: ```python import pdb; pdb.set_trace() ``` Or print, often helpful if you can't set a breakpoint ```python for att in dir(myobject): print(att, getattr(myobject, att)) ``` --- # Data See `data/README_DATA.md` --- # General Notes --- **<NAME> &copy; 2020**<file_sep>pip install pymc3==3.8 theano arviz==0.6.* daft
bf1cd04d883b93d93f08aa5a8463c263c8bc0303
[ "Markdown", "Shell" ]
2
Markdown
jonsedar/pymc3_examples
a17997460bfe158667db2b53f2f36cf9647388cd
e552d930c87731c04c1be0aa8007ae2e26d8816f
refs/heads/master
<repo_name>utsargo/utsargo.github.io<file_sep>/_posts/2015-10-18-আমি-এক-যক্ষ-মহানগরীর.markdown --- title: আমি এক যক্ষ মহানগরীর... date: 2015-10-18 00:00:00 Z tags: - গানবাজনা layout: post comments: true --- আজকে আড্ডায় বসে হঠাৎ এক স্মৃতিকাতরতায় পেয়ে বসল। প্রসঙ্গ ভূপেন হাজারিকার গান। মনে পড়ে গেল এক স্পিকারের প্যানাসনিক ক্যাসেট। সে কবেকার কথা! প্রথম কৈশোরের শেষভাগ। সমস্তদিন ফাঁকে ফাঁকে ভূপেন হাজারিকার গান। 'মানুষ মানুষের জন্যে'। ঘুরিয়ে ঘুরিয়ে বারবার শোনা। জাপানি টিডিকে ক্যাসেটে যত্নে রেকর্ড করা সব গান। একটা রেকর্ডিং-এর দোকান ছিল, প্রথমে নিউমার্কেটে, অনেক পরে বায়তুন-নূর মসজিদের তলায়। শালা দুলাভাই মিলে চালাত সেই দোকান। দুলাভাই লোকটির নাম ছিল মোদাচ্ছের। আমরা তাঁকে বলতাম বাংলা গানের মাস্টার। যেমন বিশাল তাঁর সংগ্রহ, তেমনি অদ্ভুত স্মৃতিশক্তি। হাজার হাজার গানের সুরকার, গীতিকার ও শিল্পীর নাম ছিল তাঁর নখদর্পনে। গান শোনার নেশায় পেয়েছিল অল্প বয়সেই। গোঁফের রেখা দেখা দেবার আগে থেকেই, অতি কষ্টে জমানো মূদ্রা কয়টি পকেটে নিয়ে, সাইকেল চেপে যেতাম গান তুলতে। নানারকম গানের দিকে আগ্রহ দেখে মোদচ্ছের কাকা আমাকে খুবই ভালবাসতেন। প্রতি ক্যাসেটে পাঁচ টাকা ছাড় ছিল আমার জন্য। ৬০মিনিটের একটা জাপানি টিডিকের দাম ছিল ৪৫ টাকা। আর রেকর্ডিং ফি ২০ টাকা। কাকা সব মিলিয়ে ৬০ টাকা রাখতেন। তাও সবসময় পকেটে থাকত না। কখনো ৫-১০ টাকা বাকি রেখে আসতাম। তা আবার তিনি ইচ্ছে করেই ভুলে যেতেন। যদি জিগ্যেস করতাম, "কাকা, আগের কয়ডা টাকা পাতেন না আমার কাছে?" তিনি থুতনির একগোছা দাড়ি চুলকোতে চুলকোতে মনে করার ভঙ্গিতে বলতেন,"তা তো মনে হয় পাতাম কাকা, কিন্তু কয়টাকা মনে-টনে নেই। যাক, তুমি তার চেয়ে আমারে এট্টা নেভি সিগারেট খাওয়ায়ে দাও, তালিই হবেনে।" বলে অতিরহস্যময় স্নেমিশ্রিত একটা হাসি দিতেন। সেই লোকটা, এক প্রকার বাড়ির পাশের লোকটা দুম করে একদিন মরে গেল, আমি খোঁজও রাখিনি। হঠাৎ হঠাৎ সেই শীর্ণদেহি বৃদ্ধকে মনে পড়ে ঝপ করে চোখে জল চলে আসে। যা হোক, বলছিলাম ভূপেনের গানের কথা। সেই কিশোর মনে গানগুলো এমনভাবে গেঁথে গিয়েছিল, যাকে বলে একেবারে 'রিড অনলি মেমরি' হয়ে গেছে। চোখ ছল ছল করে, বেহুলা বাংলা, গঙ্গা আমার মা, বিস্তীর্ণ দুপাড়ে, সাগর সঙ্গমে, আমি এক যাযাবর, শীতের শিশিরে ভেজা, দোলা, একখানা মেঘ ভেসে এলো আকাশে-- এরকম আরো কত কত গান। ওহ হো, তারপর ওই গানগুলো! জীবন খুঁজে পাবি, ধমধমাধম ধমধমাধম জীবন মাদল বাজে, শারদীয় শিশিরে-- আহা কী সব গান। ইচ্ছে করে একেকটা গান নিয়ে আলাদা করে বলি। আমার তাতে ক্লান্তি হবে না একটুও, কিন্তু এই ছোট লেখাটি যারা দয়া করে পড়ছেন, তাদের ধৈর্য্যের বিরাট পরীক্ষা হয়ে যাবে, তাতে কোনো সন্দেহ নেই। আমি অতএব, দুটো গানের কথা বিশেষ করে বলতে চাই। একটা হলো আমি- আমি এক যাযাবর। বুঝতে শেখার আগে থেকেই এই গানটা কেন যেন আমায় টানত। পরে বুঝেছি এই গানটার মধ্যে একরকমের আন্তর্জাতিকতা আছে। শুনলেই এক যাযাবর বিশ্বনাগরিকের ছবি ভেসে ওঠে মনে। সকল দেশের সকল মানুষের সাথে একধরণের আত্মীয়তা অনুভব করি মনে মনে। লিরিকটা খেয়াল করলেই বোঝা যাবে, এ গানটা একেবারেই অন্য জাতের। "আমি এক যাযাবর, পৃথিবী আমারে আপন করেছে, ছেড়েছি সুখের ঘর॥" প্রথমেই দেশ-জাতির গণ্ডি ভাঙার ঘোষণা। তারপর সেই অদ্ভূত লাইনগুলো-- _আমি গঙ্গার থেকে মিসিসিপি হয়ে ভোলগার মুখ দেখেছি_ _আমি অটোয়ার থেকে অস্ট্রিয়া হয়ে প্যারিসের ধূলো মেখেছি_ _আমি ইলোরার থেকে রঙ নিয়ে দূরে শিকাগো শহরে দিয়েছি_ _আমি গালিবের শের তাশখন্দের মিনারে বসে শুনেছি_ _আমি মার্কটোয়েনের সমাধিতে বসে বর্গীর কথা বলেছি..._ শুনতে শুনতে মনটা দেহের খাঁচা ছেড়ে সেসব অচিন জায়গার সন্ধানে বেরিয়ে পড়ে। তার পরের লাইনগুলোতেই ফুটে ওঠে আরেক চিত্র। শোষণ-বৈষম্য-বঞ্চনার। _বহু যাযাবর লক্ষ্যবিহীন, আমার রয়েছে পণ_ _রঙের খনি যেখানে দেখেছি রাঙিয়ে নিয়েছি মন_ _আমি দেখেছি অনের গগনচুম্বী অট্টালিকার সারি_ _তার ছায়াতেই দেখেছি অনেক গৃহহীন নরনারী_ _আমি দেখেছি অনেক গোলাপ-বকুল ফুটে আছে থরে থরে_ _আবার, দেখেছি না-ফোটা ফুলের কলিরা ঝরে গেছে অনাদরে_ _প্রেমহীন ভালবাসা দেশে দেশে ভেঙেছে সুখের ঘর..._ সেই অল্প বয়সে পৃথিবীব্যাপী বৈষম্যের এই সহজ চিত্র মনে কীরকম দাগ কেটেছিল তা বুঝতেই পারছেন। সেই ঘোর থেকে আজো বেরোতে পারিনি। আরেকটা গানের কথা বলি। এ গানটা ভাললাগার তালিকায় যুক্ত হয়েছে অনেক পরে এসে। যখনকার কথা এতক্ষণ বলেছি তখনি নয়। এ গানটা একটা রোমান্টিক গান। একখান মেঘ ভেসে এল আকাশে। গোড়াতে এ গান আমার একদম ভাল লাগত না। (তখন অবশ্য কোনো রোমান্টিক গানই ভাল্লাগতো না। মাথায় একধরণের এন্টি-রোমান্টিসিজম ভর করেছিল।) এই গানের দুটি লাইন আছে, যে কারণে বড় হবার পরে গানটি মনে গেঁথে গেছে। লাইন দুটি হলো- _আমি এক যক্ষ মহানগরীর_ _যারে ডাকি কেন তার পাই না সাড়া.._ তা, ছোটবেলায় কালিদাসস্য মেঘদূতম্ তো আর পড়ে পারিনি! বিরহী যক্ষের মর্ম কী করে বুঝব! সে বোঝার বয়সও তখন হয় নি। তার উপর সে যক্ষ যদি হয় নাগরিক যক্ষ, বাপরে বাপ! [ফারুখ ভাই](https://www.facebook.com/farukh.siddhertho "ফারুখ সিদ্ধার্থ") দারুণ বলেছেন। "যক্ষ কী বস্তু যদি না জানো, তবে ওই হাহাকার কী করে বুঝবে!" যা হোক, এ গান, বলা ভাল এই দুটি লাইন যতবার যতবার শুনি ততবার ততবারই বুকের মধ্যে যে তীব্র হাহাকার তৈরি হয় তা বুঝিয়ে বলার ক্ষমতা আমার নেই। আজো আনন্দ-বিষাদে নাগরিক একাকিত্বে এই দুটি লাইন বারংবার ঘুরেফিরে মনে আসে-- _আমি এক যক্ষ মহানগরীর_ _যারে ডাকি কেন তার পাই না সাড়া_ _চোখে তাই ঝরঝর বৃষ্টিধারা...._ <file_sep>/_posts/2014-09-11-রসনাবিলাস.markdown --- title: রসনাবিলাস date: 2014-09-11 00:00:00 Z tags: - রসনাবিলাস layout: post comments: true --- ### প্রস্তাবনা কী খাওয়াটাই না খেলাম! আহা! কী খাওয়াটাই না খেলাম! একটুখানি কচুশাক। তাতে মাছ-টাছ কিচ্ছু নেই। কী জাদুতে এমন অপূর্ব অমৃততুল্য হয়ে উঠল, ঠিক বুঝতে পারলাম না। কচুশাকের পায়েস বললে খুব একটা অত্যুক্তি হবে না। সাথে একটা হৃষ্টপুষ্ট কাঁচাঝাল ঘুঁটে নেওয়ার পর পুরো আস্বাদটাই অন্য স্তরে চলে গেল। মাকে জিগ্যেস করলাম, “ও মা! কী দেছো এতে!”। মা বলল, “কী দিছি? এট্টু নারকেল কোরা, এট্টু পাঁচফোড়ন, আর একমুঠ বাদাম। চিনি-টিনি দিই নাই আজকে।” এ কচুশাক বাজার থেকে কিনতে হয়নি। একজনের ভিটে থেকে মুফতে চেয়ে আনা। বাকিটা আমার মা’র রান্নার জাদু। গতকালের ওলের সালুন থেকে গিয়েছিল অনেকটাই। আজ চেটেপুটে সবটুকু খেলাম। প্রতি গ্রাসে আবারও সেই অনির্বচনীয় অনুভুতি। চই ঝালটাও ছিল এক্কেবারে বাঙলায় যাকে বলে- ফাসক্লাস! তার সুঘ্রাণেই পেট চুঁই চুঁই করে ওঠে। শেষে বুনো আমড়ার অম্বল। এ আমড়াও পয়সা দিয়ে কেনা না। বাজারে বুনো আমড়া সচরাচর পাওয়াও যায় না। কিছুদিন আগে মা যশোর গিয়েছিলো বেড়াতে। সেখান থেকে প্রায় একবস্তা নিয়ে এসেছে। তা-ই হিমবাক্সে রেখে রেখে খাওয়া চলছে। এও আরেক অদ্ভুত বস্তু। স্বাস্থ্যে আমারই মত‒ অস্থি-চর্মসার কিন্তু ভুবন-ভুলানো তার আঘ্রাণ। খাওয়াটা তো জম্পেশ হলো। কিন্তু আমি ভাবছিলাম অন্য কথা। আজকের দিনের ‘পুলাপান’; তাদের খাদ্য-খাবারে বৈচিত্র্য দিন দিন কমে যাচ্ছে। বড় বড় ব্রান্ডের চিপস্, বার্গার, পিৎজা, মুরগীর মাংস ভাজা এইসব স্বপ্নে-বাস্তবে খেয়ে খেয়ে স্বাভাবিক খাদ্যাভাসের বারোটা বেজে যাচ্ছে। সোজা কথায় ‘যা খেয়ে গুষ্টি বাঁচবে’ তা খেতে শেখার আগ্রহ হারিয়ে যাচ্ছে এদের। আমার এক ভাইপোর কথা বলি। নাম বলে তাকে লজ্জ্বা দিতে চাই না। সে ব্যাটা চিংড়ি মাছ আর আলু ছাড়া আর কোনো তরিতরকারি বা মাছ খায় না। কী দশা হবে এদের! খুঁজলে প্রায় প্রত্যেক পরিবারে এরকম একটি-দুটি ‘মাল’ পাওয়া যাবে। তাই ভাবছিলাম, সাধারণ প্রতিদিনকার খাবারে যে বৈচিত্র্য আমি উপভোগ করার সুযোগ পেয়েছি, তা একটু একটু করে লিখে ফেলব। তাতে যদি এদের জিভে একটু জল আসে, যদি এরা এসব শাক-পাতা-তরিতরকারি খেতে আগ্রহী হয়। ‘যা খেয়ে গুষ্টি বাঁচবে’, তা যদি এরা একটু খেতে শেখে! <file_sep>/index.html --- title: আদ্যপান্ত layout: default --- <main class="content" role="main"> {% if paginator.page == 1%} {% for post in site.tags["sticky"] %} <article class="preview"> <header> <div class="sticky"> <i class="fa fa-bookmark" aria-hidden="true"></i> </div> <h1 class="post-title"><a href="{{ post.url }}">{{post.title}}</a></h1> <div class="post-meta"><time class="post-date" datetime="{{ post.date | date_to_xmlschema}}">...</time></div> </header> <section class="post-excerpt"> {% if post.excerpt_separator %} <p>{{ post.excerpt}}&hellip;</p> {% else %} {{ post.content }} {% endif %} </section> {% if post.excerpt_separator %} <p class="readmore"><a href="{{post.url}}">আরো পড়ুন <i class="fa fa-chevron-right"></i></a></p> {% endif %} <div class="article-footer"> <section class="social-icons-post index-social"> <div class="social-icon"> <a href="https://www.facebook.com/sharer/sharer.php?u={{site.url}}{{ post.url }}" onclick="window.open(this.href, 'facebook-share','width=580,height=296');return false;"><i class="fa fa-facebook" aria-hidden="true"></i></a> <a href="http://twitter.com/share?text={{post.title}}&url={{site.url}}{{ post.url }}" onclick="window.open(this.href, 'twitter-share', 'width=550,height=235');return false;"><i class="fa fa-twitter" aria-hidden="true"></i></a> <a href="https://plus.google.com/share?url={{site.url}}{{ post.url }}" onclick="window.open(this.href, 'google-plus-share', 'width=490,height=530');return false;"><i class="fa fa-google-plus" aria-hidden="true"></i></a> </div> </section> <section class="meta"> {% if post.orig_date or post.location %} <div class="post-meta-bottom">{% if post.orig_date %}<time class="post-date bottom-meta" datetime="{{ post.orig_date | date_to_xmlschema }}">...</time>{% endif %} {% if post.location %}<div class="bottom-meta">{{ post.location }}</div>{% endif %} </div> {% endif %} </section> </div> </article> {% endfor %} {% endif %} {% for post in paginator.posts %} {% if post.layout != "redirected" %} <article class="preview"> <header> <h1 class="post-title"><a href="{{ post.url }}">{{post.title}}</a></h1> <div class="post-meta"><time class="post-date" datetime="{{ post.date | date_to_xmlschema}}">...</time></div> </header> <section class="post-excerpt"> {% if post.excerpt_separator %} <p>{{ post.excerpt}}&hellip;</p> {% else %} {{ post.content }} {% endif %} </section> {% if post.excerpt_separator %} <p class="readmore"><a href="{{post.url}}">আরো পড়ুন <i class="fa fa-chevron-right"></i></a></p> {% endif %} <div class="article-footer"> <section class="social-icons-post index-social"> <div class="social-icon"> <a href="https://www.facebook.com/sharer/sharer.php?u={{site.url}}{{ post.url }}" onclick="window.open(this.href, 'facebook-share','width=580,height=296');return false;"><i class="fa fa-facebook" aria-hidden="true"></i></a> <a href="http://twitter.com/share?text={{post.title}}&url={{site.url}}{{ post.url }}" onclick="window.open(this.href, 'twitter-share', 'width=550,height=235');return false;"><i class="fa fa-twitter" aria-hidden="true"></i></a> <a href="https://plus.google.com/share?url={{site.url}}{{ post.url }}" onclick="window.open(this.href, 'google-plus-share', 'width=490,height=530');return false;"><i class="fa fa-google-plus" aria-hidden="true"></i></a> </div> </section> <section class="meta"> {% if post.orig_date or post.location %} <div class="post-meta-bottom">{% if post.orig_date %}<time class="post-date bottom-meta" datetime="{{ post.orig_date | date_to_xmlschema }}">...</time>{% endif %} {% if post.location %}<div class="bottom-meta">{{ post.location }}</div>{% endif %} </div> {% endif %} </section> </div> </article> {% endif %} {% endfor %} {% if paginator.total_pages > 1 %} <nav class="myPagination" role="pagination"> {% if paginator.previous_page %} <a class="newer-posts" href="{{ paginator.previous_page_path | prepend: site.baseurl | replace: '//', '/' }}"><i class="fa fa-chevron-left"></i> পরবর্তী</a> {% else %} <span class="newer-posts"><i class="fa fa-chevron-left"></i> পরবর্তী</span> {% endif %} <span class="page-number">পৃষ্ঠা {{paginator.page | replace: '0', '০' | replace: '1', '১' | replace: '2', '২' | replace: '3', '৩' | replace: '4', '৪' | replace: '5', '৫' | replace: '6', '৬' | replace: '7', '৭' | replace: '8', '৮' | replace: '9', '৯'}} (মোট {{paginator.total_pages | replace: '0', '০' | replace: '1', '১' | replace: '2', '২' | replace: '3', '৩' | replace: '4', '৪' | replace: '5', '৫' | replace: '6', '৬' | replace: '7', '৭' | replace: '8', '৮' | replace: '9', '৯'}}পৃষ্ঠা)</span> {% if paginator.next_page %} <a class="older-posts" href="{{ paginator.next_page_path | prepend: site.baseurl | replace: '//', '/' }}">পূর্ববর্তী <i class="fa fa-chevron-right"></i></a> {% else %} <span class="older-posts">পূর্ববর্তী <i class="fa fa-chevron-right"></i></span> {% endif %} </nav> <nav class="myPagination" role="pagination"> {% for page in (1..paginator.total_pages) %} {% if page == paginator.page %} <em>{{ page | replace: '0', '০' | replace: '1', '১' | replace: '2', '২' | replace: '3', '৩' | replace: '4', '৪' | replace: '5', '৫' | replace: '6', '৬' | replace: '7', '৭' | replace: '8', '৮' | replace: '9', '৯' }}</em> {% elsif page == 1 %} <a href="{{ paginator.previous_page_path | prepend: site.baseurl | replace: '//', '/' }}">{{ page | replace: '0', '০' | replace: '1', '১' | replace: '2', '২' | replace: '3', '৩' | replace: '4', '৪' | replace: '5', '৫' | replace: '6', '৬' | replace: '7', '৭' | replace: '8', '৮' | replace: '9', '৯'}}</a> {% else %} <a href="{{ site.paginate_path | prepend: site.baseurl | replace: '//', '/' | replace: ':num', page }}">{{ page | replace: '0', '০' | replace: '1', '১' | replace: '2', '২' | replace: '3', '৩' | replace: '4', '৪' | replace: '5', '৫' | replace: '6', '৬' | replace: '7', '৭' | replace: '8', '৮' | replace: '9', '৯'}}</a> {% endif %} {% endfor %} </nav> {% endif %} </div> </main> <file_sep>/_posts/2018-05-11-murile-and-the-bull-from-the-moon.markdown --- title: মুরহিলে ও চাঁদ মুলুকের ষাঁড় date: 2018-05-11 00:20:00 +06:00 tags: - আফ্রিকার রূপকথা - শিশুতোষ - রূপকথা - উপকথা layout: post comments: true --- <h4><i>একটি আফ্রিকান রূপকথার রূপান্তর</i></h4> অনেক কাল আগে, আফ্রিকা দেশে মুরহিলে নামে এক ছেলে ছিল। মুরহিলের মা মনে করতো ছেলেটা একেবারে অকম্মার ঢেঁকি। সারাক্ষণ তাকে গালমন্দ করতেই থাকতো। সে যা করতো, কিছুই তার মায়ের মনে ধরত না, একটা কিছু খুঁত ধরাই চাই। নিত্যি-নিত্যি এই অপমানে তিতিবিরক্ত হয়ে মুরহিলে তার বাপের একটা বসবার টুল চেয়ে নিল। এই টুলটা ছিল তাদের বংশের চৌদ্দ পুরুষের পুরোনো একটা জাদুর টুল। সেই টুলের উপরে বসে যতরকমের মন্তর-তন্তর তার জানা ছিল, সব আওড়াতে লাগলো। হঠাৎ টুলটা মাটি ছেড়ে উপরে উঠে গেল। আর সাঁ সাঁ করে ছুটে চললো চাঁদের দিকে। চাঁদ মুলুকে নেমে মুরহিলে প্রথমেই লোকজনকে জিগ্যেস করলো, “তুমাগে সদ্দারের বাড়িডা কোনদিকি কও দিনি?” চাঁদ মুলুকের লোকজন বলল, “তা তোমারে বলবো কেন? আমাদের সর্দারের বাড়ির ঠিকানা নিয়ে তোমার কী কাজ?” মুরহিলে বললো, “দাদা গো, দিদি গো, মাসি গো, মেসো গো, আমি বৈদেশী লোক। কিছুই তো চিনি না, তুমরা যা কবা আমি করে দেব। তুমরা খালি সদ্দারের বাড়ির ঠিকানাডা কও।" চাঁদ মুলুকের লোকেরা তখন তার কাছে পৃথিবীর খবরাখবর জানতে চাইলো। মুরহিলে যা জানে সব বললো। যা জানে না তাও সব বলে দিল বানিয়ে বানিয়ে। চাঁদ মুলুকের লোকেরা তার মুখে নিত্যনতুন আশ্চর্য সব খবর শুনে বেজায় খুশি হলো। বলে দিল সর্দারের বাড়ির হদিশ। সর্দারের গাঁয়ে পৌঁছে তো মুরহিলে অবাক! এরা তো এখনো সেই আদিম যুগে পড়ে আছে! আগুন জ্বালাতে জানে না, মাংস খায় কাঁচা, বাসনপত্তর কিছুই নেই, রাতে ঠাণ্ডায় কাঁপে ঠক-ঠক করে! মুরহিলে কাঠে কাঠ ঘষে আগুন জ্বালালো। তাজ্জব ব্যাপার! এমন কাণ্ড চাঁদ মুলুকের লোক কখনো দেখেনি। সর্দারের তো চক্ষু ছানাবড়া। এমন লোককে তো হাতছাড়া করা চলে না! মুরহিলে সর্দার আর চাঁদমুলুকের তাবৎ লোকের খুব প্রিয়পাত্র হয়ে উঠলো। চাঁদ মুলুকের সর্বকালের সবচেয়ে বড় জাদুকর বলে লোকে তার জয়ধ্বনি করতে লাগলো। তার এই আশ্চর্য কাজের জন্য চাঁদের দেশের মানুষেরা তাকে অনেককিছু উপহার দিল। উপহার বলতে, সে দেশের রেওয়াজ হলো গুণীজনদের অনেকগুলো গরু-বাছুর আর অনেকগুলো বৌ উপহার দেয়া। কিন্তু, মুরহিলে এমন কাজ করেছে, যা চাঁদের দেশের ইতিহাসে কেউ কখনো করেনি। তাই, সর্দারের একার পক্ষে তাকে উপযুক্ত উপহার দিয়ে পোষালো না। গ্রামের সব লোক, মানে মেয়ের বাপেরা এলো মুরহিলেকে তাদের জামাই করতে। অনেকগুলো বউ আর অনেকগুলো গরু-বাছুর পেয়ে সে রাতারাতি বিরাট বড়লোক হয়ে গেল! চাঁদ মুলুকে বেশ কিছুদিন সুখে কাটিয়ে মুরহিলে এবার দেশে ফেরার আয়োজন করলো। মনে তার বিরাট গর্ব: এবার মা দেখবে, তার ছেলে কীরকম একটা কেউকেটা লোক হয়েছে! সেজন্যে সে তার বন্ধু তোতাপাখিকে দেশে পাঠাল তার যাত্রার আগাম সুখবর প্রচার করার জন্য। এদিকে হয়েছে কী, মুরহিলে তো দেশে নেই অনেকদিন। তার পরিবার ভেবেছে অকম্মা ছেলেটা বুঝি মরে-হেজে গেছে চাঁদে গিয়ে। সে যে বেঁচে আছে তা তার পরিবারের কেউই বিশ্বাস করতে চায় না। মুরহিলেকে গিয়ে তোতা যখন এই সংবাদ দিল, মরহিলে বললো, “তুই ব্যাটা বড় মিথ্যুক তোতা! তুই আসলে যাসইনি আমার বাপ-মায়ের কাছে। এদিক-ওদিক উড়ে ঘুরেফিরে এসে এখন ফালতো খবর দিচ্ছিস!” তোতা বলল, “বটে! আমি মিথ্যুক! দাঁড়া, দেখাচ্ছি তোকে!” বলেই তোতা আবার পাখা ঝাপটে চলে গেলে। পৃথিবী থেকে লাঠি হাতে মুরহিলের থুত্থুরে বুড়ো বাপকে ধরে আনলো। এবার বাপেরও বিশ্বাস হলো ছেলে বেঁচে আছে, আর ছেলেও বাপকে দেখে বেজায় খুশি। এবারে মুরহিলে নিশ্চিন্ত মনে পাঁজি দেখে পৃথিবীতে যাওয়ার দিনক্ষণ ঠিক করলো। সে কী জমকালো আয়োজন! তার পাঁচ কুড়ি বউ আর সোয়া শ'খানেক ছেলেপুলেদের ভাল ভাল জামাকাপড় পরিয়ে হীরে-জহরত দিয়ে সাজালো। আরো সাথে যাবে হাজার হাজার গরু-বাছুর। বিরাট কাফেলা! মনে মনে ভাবলো, “এবারে মা নিশ্চয়ই তাজ্জব বনে যাবে!” কিন্তু, মুশকিল হলো, এত লোকজন আর এত এত গরুবাছুর তো জাদুর টুলে চাপিয়ে নিয়ে যাওয়া যায় না! কী করা যায়? শেষমেশ তারা পায়ে হেঁটেই পৃথিবীর পথে রওনা দিলো। কিন্তু চাঁদ কি আর পৃথিবী থেকে এট্টুসখানি দূরে! সে যে অনেক দূর! মুরহিলে খানিক পথ গিয়ে হাঁপিয়ে উঠলো। তার পা আর চলে না। তার সাথে আসা চাঁদ মুলুকের বেশ তাগড়া এক ষাঁড় তখন তাকে গিয়ে বললো, “বাপু, তুমি আমার আমার মনিব, তোমার এ কষ্ট তো আমার আর সহ্য হয় না। আমি জাদু জানি। সেই জাদুতে তোমাদের সক্কলকে দুনিয়াতে নিয়ে যেতে পারি। তবে হ্যাঁ, কথা দিতে হবে, আমাকে তুমি খাবে না।" মুরহিলে তাকে কথা দিল, তাকে কখনো মেরে ফেলবে না, কখনো খাবে না। খুশি হয়েই কথা দিল। এমন জাদুর বলদ কার বাথানে আছে আর! ষাঁড় তখন আশ্চর্য জাদুবলে মুরহিলেকে দলবলসমেত পৃথিবীতে পৌঁছে দিল। মুরহিলেকে ফিরে পেয়ে পরিবারের লোকেরা আনন্দে শিউরে উঠলো, তাদের চোখ ঠিকরে গেল মুরহিলে আর তার নতুন সংসারের জাঁকজমক দেখে। এমনকি তার যে মা তাকে উঠতে-বসতে তুচ্ছজ্ঞান করতো, সেই মায়ের তো এখন আহ্লাদ আর অহংকারে মাটিতে পা পড়ে না। তার যেমন স্বভাব! সে লোকের বাড়ি বাড়ি গিয়ে ছেলের গুণকীর্তন শুরু করলো। মুরহিলে তার বাপ-মা আর বাড়ির সকলকে ডেকে বলল, “দেখ, এই বলদের জন্য আমি আজ বাড়ি ফিরতে পেরেছি। খবরদার, একে কখনো মারবে না।" সবাই তাতে একবাক্যে রাজি। দিন পেরিয়ে মাস গেল, মাস পেরিয়ে বছর গেল। ষাঁড়টাকে না মারার জন্য যে প্রতিজ্ঞা তারা করেছিল, তা সবাই গেল ভুলে। তাছাড়া, হাজার হাজার গরু-বাছুরের মধ্যে কোনটা কোন ষাঁড়, তা কী ছাই কারো মনে আছে নাকি! একদিন তাই, মুরহিলের বাপ-মা সেই ষাঁড়টাকেই মেরে ফেললো খাওয়ার জন্য। মুরহিলের মা তেল-মসলা দিয়ে বেশ কষে রান্না করলো সেই ষাঁড়ের মাংস। সেদিন সন্ধেবেলা, মুরহিলে বসেছে খেতে। মাংসের টুকরো তাকে দেখে কথা বলে উঠলো, “মুরহিলে! তুমি কথা রাখলে না! মেরে ফেললে আমাকে!” মুরহিলে পাত্তা দিল না। যেই না মুরহিলে মাংসের টুকরোটা মুখে পুরেছে, ওমনি স্বয়ং পৃথিবী তাকে কপ করে গিলে ফেললো, কবর দিয়ে দিলো মাটির তলার চির-অন্ধকারে। <small><strong>বিশেষ দ্রষ্টব্য: গল্পটির বাঙলা ভাষায় এই রূপান্তরিত সংস্করণের সর্বসত্ব লেখক কর্তৃক সংরক্ষিত। বাণিজ্যিক উদ্দেশ্যে ছাপা বা অন্য মাধ্যমে এটি ব্যবহার না করার জন্য অনুরোধ রইলো।</strong></small> <file_sep>/_posts/2016-07-20-বান্ধবী-সমাচার.markdown --- title: বান্ধবী সমাচার date: 2016-07-20 00:00:00 Z tags: - তত্ত্বতালাশ layout: post comments: true --- <p style="text-align: right; font-size:small; text-decoration:italic">তবুও তোমায় জেনেছি, নারি, ইতিহাসের শেষে এসে; মানবপ্রতিভার<br> রূঢ়তা ও নিষ্ফলতার অধম অন্ধকারে<br> মানবকে নয়, নারি, শুধু তোমাকে ভালোবেসে<br> বুঝেছি নিখিল বিষ কী রকম মধুর হতে পারে ।<br> ‒জীবনানন্দ দাশ</p> হালে 'বান্ধবী' কথাটাকে ইংরেজি 'গার্লফ্রেন্ড' শব্দটার সমার্থক হিসেবে ব্যবহারের চল শুরু হয়েছে। খুবই অসৎ চেষ্টা। কেননা, বান্ধবী কথাটা মোটেও গার্লফ্রেন্ডের সমার্থক না। ইংরেজিতে গার্লফ্রেন্ড বলতে যা বোঝায় তা বাংলাতে 'প্রেমিকা' কথাটার একটা লঘুতর সংস্করণ। কেননা, প্রেমিকা শব্দটির যে সুগভীর আবেদন আছে, তা গার্লফ্রেন্ড শব্দটিতে নেই। অপরদিকে, বান্ধবী কথাটা মূলগতভাবে বন্ধু শব্দের লিঙ্গান্তর। তার সাথে রোমান্স না প্রেমের কোনো সম্পর্ক নেই। কিছুদিন আগে পর্যন্তও সহপাঠিনী বা সমবয়সী বা শৈশব থেকে একসাথে বেড়ে ওঠা কোনো মেয়ে বন্ধুকে একটা ছেলের জন্য বান্ধবী পরিচয় দিতে কোনো অসুবিধে ছিল না। গার্লফ্রেন্ডের সমার্থক হিসেবে কথাটা চালু করার চেষ্টার ফলে সেটি আজকাল একটু কষ্টসাধ্য হয়ে পড়েছে। যদি বলি, 'মেয়েটি আমার বান্ধবী।' তখন উল্টো প্রশ্ন, 'মানে গার্লফ্রেন্ড?' তখন ব্যাখ্যা দিতে হয়, 'না, স্রেফ বন্ধু।' প্রশ্নকর্তা তাতেও সন্তুষ্ট হন না, 'আরে কিছু থাকলেও বা কী সমস্যা! লজ্জা পাচ্ছ কেন?' একটি শব্দের সহজ সুন্দর অর্থকে একটি দুরভিসন্ধিমূলক অর্থ দ্বারা প্রতিস্থাপনের এই চেষ্টা খুবই দুঃখজনক। কেন আমি মেয়ে বন্ধুটিকে বান্ধবী বলতে চাই, তার একটা কারণ আছে। কারণ, বান্ধবী শব্দটি বন্ধুর চেয়ে আরো গভীর, ব্যপক ও মমতাপূর্ণ। বান্ধবী, সে কোনো ছেলের বান্ধবী হোক বা কোনো মেয়ের, অপর কোনো 'বন্ধু'র চেয়ে বেশি সহৃদয়, নির্ভরযোগ্য ও সহনশীল। কারণ, ঐতিহাসিকভাবে নারীরা মানবচরিত্রের শ্রেষ্ঠ কিছু গুণাবলী অর্জন করেছে। সেগুলো পুরুষ এখনো অর্জন করে উঠতে পারে নি। পুরুষ অধিপতি চরিত্রে থাকায় সমাজের কাছ থেকে সে গড়পড়তায় শোষকের মনস্তত্ত্ব অর্জন করেছে। ফলে মানুষের (মানুষটি পুরুষ বা নারী যাই হোক) একজন পুরুষ বন্ধু যতখানি সহৃদয় চরিত্র, নারীবন্ধু তার চেয়ে বেশি সহৃদয় হয়। এই কারণে, বন্ধুর চেয়ে বান্ধবী গুণগতভাবে উন্নত। বান্ধবী কথাটা ব্যবহার করতে গিয়ে একধরণের প্যারাডক্স তৈরি হয়। ধরুন, আমার একটি বান্ধবী আছে। একজন বলে বসলো, 'ওর সাথে তো তোমার প্রেম।' আমি সবিনয়ে বলি, "না, আপনার সাথে আমার যেমন বন্ধুতা হওয়া সম্ভব, ওর সাথেও তেমনি বন্ধুত্ব।" মন্তব্যকারীর উত্তর, "ওটাও একরকমের প্রেম।" তা বটে। বাংলা ভাষায় প্রেম শব্দটার বিবিধ অর্থ আছে। রকমফেরও আছে বহু। দেশপ্রেম, ভাতৃপ্রেম, বন্ধুপ্রেম, ঈশ্বরপ্রেম প্রভৃতি। আমার বান্ধবীর সাথে আমার যে সম্পর্ক, তা এরকম কোনো না কোনো অর্থে বা রকমফেরে প্রেম বলে চালিয়ে দেয়া যায়। কিন্তু, মনে রাখতে হবে প্রেম বলতে মানুষ প্রথমত বোঝে 'যুবকযুবতীর ধ্বংসরহিত ভাববন্ধন' (বঙ্গীয় শব্দকোষ, হরিচরণ বন্দ্যোপাধ্যায়) অর্থাৎ রোমান্স। অতএব, যে কোনো সম্পর্ককে প্রেম বলে চালিয়ে দিতে গেলে মানুষের পক্ষে সেটাকে একটা রোমান্টিক সম্পর্ক ভেবে নেয়ার সুযোগ থাকে। সেটি কখনো কখনো বিব্রতকর। বান্ধবীর সাথে আমার যে সম্পর্ক তাতে ভালবাসা বিলক্ষণ আছে, আমার অপরাপর বন্ধুদের প্রতি যেমন থাকে। তার চেয়ে হয়তো একটু বেশিই আছে। কিন্তু তা বলে, সেটা রোমান্স হতে হবে তা নয়। সুতরাং, বান্ধবী কথাটা উচ্চারণ করলেই রোমান্সের গন্ধ খোঁজাটা একটা বিকৃতির লক্ষণ। <file_sep>/_posts/2015-05-13-ঘাটকোল.markdown --- title: ঘাটকোল, মায়াচেলা ও অন্যান্য date: 2015-05-13 00:00:00 Z tags: - রসনাবিলাস - কচুতত্ত্ব - শাকতত্ত্ব - মাৎস্যতত্ত্ব - ভর্তা layout: post comments: true --- দু-এক ফোঁটা বৃষ্টির জল পড়লেই তারা মাথা তুলে দাঁড়ায়। তিনকোনা চকচকে পাতা নিয়ে। কিছুদিন যেতে না যেতেই সব সোমত্থ লকলকে ডাঁটা। মাথায় সেই তিনকোনা চকচকে পাতা। কেউ বলে ঘাটকুল, কেউ বলে ঘাটকোল। কচুবংশীয় এ শাকটি আমার আশৈশবের প্রিয় বস্তু। মূলত ভর্তা খেতে হয়। চিংড়ির সাথেই জমে ভালো। কারো কারো মতে এর নানাবিধ ঔষধি গুণাগুণ আছে। যেমন, ঘাটকোল ভর্তা খেলে নাকি গায়ের ব্যথা-বিষ সেরে যায় (আপসোস! মনেরটা সারে না)। আমার গায়ে তেমন বিষব্যথা কোনোকালেই হয় নি, তাই সেটা পরখ করে দেখার সুযোগ ঘটে নি। তবে খেতে যে অমৃততুল্য (এবং অপরাপর কচুজাতীয়দের মত এরও যে কিছু পুষ্টিগুণ আছে) তাতে কোনো সন্দেহ নেই। অবশ্য, ঝাঁঝটা যাদের সহ্য হয় না এবং যাদের অহেতুক 'কচুভীতি' আছে যারা খাদ্যাখাদ্য বিষয়ে ইংরেজিতে যাকে বলে 'জাজমেন্টাল', তারা হয়তো ভিন্ন কথা বলবেন। কিন্তু যে কোনো সংস্কারবর্জিত সুরসিক রসনাবিলাসী আমার সাথে একমত হবেন, সে কথা হলপ করে বলতে পারি। মাইকেল বাংলাভাষা নিয়ে নিজের নির্বুদ্ধিতার জন্য আক্ষেপ করে বলেছিলেন‒ কেলিনু শৈবালে ভুলি কমল কানন। কথাটা বাংলার বনে-বাদাড়ে বেড়ে ওঠা অজস্র প্রকারের শাকলতার ক্ষেত্রেও খাটে। 'আঁচল ভরিয়া' কত যে মণিরত্ন সে 'ধরিয়া' রেখেছে, তার 'রূপখনি' সম্পূর্ণ আবিষ্কার করা এ অর্বাচীনের কর্ম নয়। আপসোসের বিষয় হলো, যে মা-মাসি-পিসি-খুড়ী শ্রেণী এ বিষয়ে সম্যক জ্ঞান রাখতেন, যাদের পূণ্যস্পর্শে এইসকল বুনো পত্র-পুষ্প-লতা-স্কন্দ বেহেশ্‌তি চিজে পরিণত হতো, সেই শ্রেণীটি ক্রমশ বিলুপ্ত হতে চলেছে। আমি যেন তাই মধুকবির মত স্বপ্নাদেশ পাই‒ ওরে বৎস, শোন, মাতৃকোষ রতনের রাজি ইত্যাদি; এবং দত্তকূলোদ্ভব কবির মতই সেই আদেশ মাথা পেতে নিয়ে বলি‒ মধুহীন কোরো না গো তব মনকোকনদে। পুনশ্চঃ কেবল ঘাটকোল দিয়ে আজকের রসনাপর্ব সমাপ্ত করলে কচু জাতির প্রতি আমার সাতিশয় পক্ষপাতিত্ব প্রকাশ পায়। কেননা আজকের অন্য পদটিও ঘাটকোলের চেয়ে কিছু অংশে কম যান না। মৌরলা, এ অঞ্চলে যার নাম মায়াচেলা সেটি রসিকজন মাত্রই এক নামে চেনেন। স্বচ্ছশরীরিণী এ মাছটি স্বাদে এবং গুণে অতুলনীয় বলা চলে। আজকে সক্কাল বেলা উঠে গেছিলাম বাজারে। বোশেখ মাস। মাছের আকাল। সারা বজারময় কুৎসিত তেলাপিয়া কিলবিল করছে। তারই মধ্যে একটা থালিতে রূপোর মত চকচকে এ মাছ কয়টার দিকে আমার চোখ আপরাধীর সন্ধানে থাকা ঘুষখোর পুলিশের চোখের মত আটকে গেল। সাইজেও সচরাচর যেমন মায়াচেলা পাওয়া যায় তার চেয়ে বেশ বড়। আমার মায়ের ভাষায় 'চলা চলা'। সেই চলা চলা মায়াচেলা উপযুক্ত মূল্যে খরিদ করে বাড়ি চলে আসলাম। আগের দিন রাতে ডাঁটা শাক কিনেছিলাম, জাত ও লক্ষণ বিচারে তা সুমিষ্ট হওয়ার কথা (হয়েছেও তাই)। সেই ডাঁটা দিয়ে এই চলা চলা চেলা মাছের একটা লম্বা ঝোল হলে কেমন হবে তা ভাবতে গিয়েই আমি কিশোর বয়সের প্রেমের মত পুলকিত হয়ে উঠছিলাম। অবশেষে ঠিক দুপ্পরবেলা (যখন ভূতে মারে ঢেলা) সেই বহু প্রতীক্ষিত অতুল রসদ আস্বাদনের সুযোগ ঘটল। কী বলব মশাই! আমার মাকে একটা নোবেল দেয়া উচিৎ এ হেন উদর-শান্তি বিধান করার জন্য। মুখে দিয়েই মনে মনে প্রিয় একটি ঋক উচ্চারণ করলাম‒ মধুবাতা ঋতায়তে ইত্যাদি (এ ঋকে আলো, বাতাস, নদী, গাছ, ঊষা, সন্ধ্যা সবকিছু মধুময় হওয়ার আকাঙ্খা প্রকাশ পেলেও মাছের কোনো উল্লেখ নেই। তখনকার আর্যরা বোধহয় মাছ খেতে জানত না)। <file_sep>/_posts/2015-05-19-ব্রাহ্মীশাক.markdown --- title: ব্রাহ্মী শাক date: 2015-05-19 06:00:00 +06:00 tags: - রসনাবিলাস - শাকতত্ত্ব layout: post comments: true fimage: "/images/ব্রাহ্মী-শাক-Bacopa-monnieri.jpg" --- <a href="/images/ব্রাহ্মী-শাক-Bacopa-monnieri.jpg" data-toggle="lightbox" data-title="ব্রাহ্মী শাক <i>Bacopa monnieri</i>"><img class="img-fluid" src="/images/ব্রাহ্মী-শাক-Bacopa-monnieri.jpg" alt="তেলাকুচ-Coccinia grandis" style="width:50% !imporant; float:lefft;"/></a>শিল্পীরা বড় বড় ওস্তাদের নাম নেয়ার সময়, তাদের গান গাইবার সময় কানে হাত ছোঁয়ান। যেমন, কোনো শিল্পী যদি মিঞা-কি-মল্লার গান, তবে আগে কানে হাত ছুঁইয়ে নেন। এটা একপ্রকার বিনয় প্রকাশ- "যে গান ওস্তাদের ওস্তাদ মিঞা তানসেন সৃষ্টি করেছেন, গেয়েছেন; তা আমি গাওয়ার দুঃসাহস করছি।" আমিও তেমনি কোনো প্রসঙ্গে আমার ওস্তাদ সৈয়দ মুজতবা আলীর নাম নিলে কানে হাত ছোঁয়াই- যে বিষয়ে রসরাজ সৈয়দ মুজতবা আলী লিখে গেছেন সে বিষয়ে আমিও ক্বচিৎ-কদাচিৎ দু-এক বাক্য লিখবার দুঃসাহস করি। ওস্তাদ বলেন, খাদ্যবীণার ছয়টি তার। তাঁর লেখায় অবশ্য টক, ঝাল, মিষ্টি, তিতে ও নোনতা স্বাদের উল্লেখ পাই। ষষ্ঠ তারটি যে কী, তা তিনি লিখে যান নি। আমি হিসেব করে দেখলাম ষষ্ঠ তারটি হলো কটু বা কষ্টা স্বাদ। এই ছয়টি তারের মধ্যে পূর্ববাংলা, মানে বাংলাদেশের রান্নায় তিনটি স্বর মূখ্য- টক, ঝাল, তিতে। ওস্তাদ লিখব লিখব করেও বাঙালী রসনা নিয়ে বিশেষ কিছু লেখেন নি, যত লিখেছেন মোগলাই রান্না নিয়ে। বোধকরি দীর্ঘকাল পূর্ববাংলার বাইরে শান্তিনিকেতনে ও ততঃপর নানা প্রবাসে থাকায় এ বিষয়ে তাঁর আর লেখা হয়ে ওঠে নি। বিপরীতক্রমে, আমি খাঁটি চাঁড়াল বংশোদ্ভূত, নিজের এলাকার বাইরে জগৎ আছে তা বিশ্বাস করতে কষ্ট হয়, বদহজমের ভয়ে মোগলাই রান্না বেশি খেতে সাহস করি না, বরং এই বাংলার চাষাভুষোর রান্নাই আমার প্রধান খাদ্য। তাই বাংলার রসনা নিয়ে একান্তই নিজের অভিজ্ঞতার উপরে ভর করে দু-চারটি কথা মাঝে মাঝে বলার চেষ্টা করি। পদ্মার ভাটিতে গড়ে ওঠা ভূমির একটি বিশেষ বৈশিষ্ট্য আছে। এ অঞ্চলে যে বহুল প্রকারের শাকপাতা আপনাআপনি জন্মে তা দুনিয়ার আর কোথাও জন্মায় কিনা আমার জানা নেই। তাই শাকপাতা খাওয়ার ব্যাপারে এতদঞ্চলের মানুষের (বিশেষত তাদের যারা খুব বেশি ভদ্দরলোক নন) অভ্যাস বাংলাদেশের আর কারো সাথে মেলে না। হেলঞ্চ, মালঞ্চ, নটে, কাঁটানটে, ছেঁচি, ভাইতো, কলমি, আমরুলি, থানকুনি, গিমি, ব্রাহ্মী, কাঁথাছেড়া বা কাঁথাবুচুড়ে, হরেকরকম কচুশাক-- এরকম অজস্র প্রকারের শাক এ তল্লাটে আপনিই জন্মায়। চাষফাষ বিশেষ করা লাগে না। প্রত্যেকটি শাকের আবার একাধিক জাতও আছে। তাদের মধ্যে রয়েছে স্বাদের অতিসূক্ষ্ম তারতম্য। যা হোক, এতখানি ভূমিকা করলাম যে জন্যে সেইটে এবার বলে ফেলি। আজকে দুপুর রোদে বাড়ি ফিরে গরমে কাহিল অবস্থা। খিদেয় মাথা ভোঁ ভোঁ করছে, অথচ মুখে রুচি নেই একটুও। খেতে বসে জানে পানি পেলাম। ব্রাহ্মী শাক! শাকমাত্রই আমার প্রিয় বস্তু। তবে এ শাকটি একটু বেশিই প্রিয়। রুচি উৎপাদনে এর তুলনা হয় না। ভাজা ব্রাহ্মী শাক থেকে একপ্রকার ঘিয়ের মত সুঘ্রাণ বের হয়। শাকটি তিতে গোত্রভুক্ত। কবিরাজরা বলেন এই শাকে নাকি স্মৃতিশক্তি বাড়ে। তার প্রত্যক্ষ প্রমাণ আমি অবশ্য পাই নি। কারণ, ছোটবেলা থেকেই এ শাক আমি খাই, কিন্তু আজ পর্যন্ত পরীক্ষার খাতায় একটি প্রশ্নের উত্তরও আমি হুবহু মুখস্ত লিখতে পারি নি। ভুলে যাওয়ার ব্যাপারে আমার দক্ষতা বন্ধুজনের কাছে অবিদিত নয়। তবে খেতে ভালো এবং রুচিকর তাতে কোনো সন্দেহ নেই। প্রকৃতির প্রতিকূল পরিবেশে লড়াই করে বাঁচতে গিয়ে বহুরকম পুষ্টি উপাদানও এই বিরুৎ তার দেহে সঞ্চয় করে, তাতেও কোনো সন্দেহ নেই। সবচেয়ে বড় কথা, এক্কেবারে মুফতে, মানে মাগনা পাওয়া যায়। একটি পয়সা খরচ করতে হয় না ব্রাহ্মী শাক জোগাড় করার জন্য। আর কী চাই! <file_sep>/_posts/2015-05-25-অন্য-ছবিও-আঁকো.markdown --- title: অন্য ছবিও আঁকো! date: 2015-05-25 00:00:00 Z tags: - তিক্তকথা layout: post comments: true --- _এঁকো না কখনো স্বদেশের মুখ_ _তোবড়ানো গাল ভেঙে যাওয়া বুক_ _মরোমরো তার পরানভোমরা_ _বসে আঁকো, বসে আঁকো!_ _–কবীর সুমন_ ক্ষুধার যে একটি যন্ত্রণা আছে এবং তা সে যন্ত্রণা যে সর্বসুখযন্ত্রণহর; তা প্রতি বক্‌ৎ-এ যারা পেটপুরে চর্ব্যচোষ্য খেয়ে বড় হয়েছেন তারা ঠিক বুঝতে পারবেন না। ক্ষুধা ও খাবার বিষয়ক আলোচনা তাই তাদের কাছে নিতান্তই হীন ও আতরাফ জাতের মনে হবে তাতে আশ্চর্য কী! কিন্তু আমি জন্ম নিয়েছি ও বেড়ে উঠেছি ক্ষুধার রাজ্যে। নিজে সে যন্ত্রণা খুব প্রত্যক্ষভাবে অনুভব করার সুযোগ না হলেও ক্ষুধা নামক প্রবৃত্তি যে মানুষের আছে এবং তার নিবৃত্তি যে অনিবার্য একটি প্রয়োজন; তা বিলক্ষণ উপলব্ধি করেছি। আমি অতএব, ক্ষুধা নিবৃত্তির পথে অশনি সংকেত পেলে যারপরনাই চঞ্চল হয়ে উঠি এবং সর্বমার্গ পরিত্যাজ্যতে উদরমার্গের শরণ নিতে বাধ্য হই। সেই চিত্তচাঞ্চল্য থেকেই লিখতে বসা। আটকা পড়েছিলাম বয়রা বাজারে জামাই-এর চায়ের দোকানে। তুমুল বৃষ্টিতে। জামাই-এর ব্রিফ হিস্ট্রি অর্থাৎ সংক্ষিপ্ত ইতিহাসটি বলে নিই। জামাই এ অঞ্চলে জামাই হয়ে এসেছিলেন চাকরীর সন্ধানে। চাকরী-বাকরী না পেয়ে শেষে একটি চায়ের দোকান খুলে বসেন। হাতের গুণ ছিল, অচিরাৎ তিনি একজন গুণী চা-শিল্পী হিসেবে আবির্ভূত হন এবং রসিকজনের প্রিয়ভাজন হয়ে ওঠেন। তো, সেই দোকানে তুমুল বর্ষায় আটকে পড়েছি আমি আর মেহেদী ভাই। এককাপ কড়া লিকারের চায়ে চুক-চুক করে চুমুক দিতে দিতে মেহেদী ভাইকে বললাম, “ভাই, বিষয়টা কেমন ‘বসে আঁকো’ মার্কা হয়ে যাচ্ছে না?” ভাই বললেন, “কীরকম, কীরকম?” আমি বললাম, “এই যে আমরা শিল্প-সাহিত্য-চেতনা-দেশপ্রেম নিয়ে এত কথা বলছি, কিন্তু কদিন পরে চালের দরটা যে হু হু করে বাড়বে! তখন আমার মত লোক, এই মাগ্যির বাজারে কুল্লে দশটি হাজার টাকা আয় করতে যার কোষ্ঠ কঠিন হতে হতে মার্বেল-গুলি হয়ে যায়, তার কী উপায় হবে!” ভাই গম্ভীর হয়ে বললেন, “হুম।” আমি আবার শুরু করলাম, “গেলো বছর বোরোর সময়ে ব্রি-বালাম আঠাশের সরকারি দর ছিল প্রায় এগারোশ’ টাকা আর রত্নার মত মোটা ধানের দর ছিল আটশ’ টাকা। সেবার সরকার ধানও কেনা শুরু করেছিল ঠিক সময়ে প্রায়। ফলে ধানের বাজার ছিলো রমরমা। চাষাভুষোর দলের মুখে সেবার হাসি দেখেছিলাম। গত একটা বছর তাই চালের দরও মোটামুটি সাধ্যের মধ্যে ছিল। কিন্তু এবার যে একেবারে উল্টো! গত হপ্তা থেকে সরকারের চাল কেনার কথা থাকলেও আজ মে মাসের ২৪ তারিখ পর্যন্তও চাল কেনার কোনো তোড়জোড় নেই। এদিকে হু হু করে শস্তার চাল ঢুকছে বাজারে ইন্ডিয়া থেকে। দর পড়ে যাওয়ার অজুহাত দেখিয়ে ফড়েরা জলের দরে ধান কিনে মহাজনের গুদামে ঢুকাচ্ছে। এরপর সব ধান যখন গুদামে ঢুকে যাবে, তখন চালের দাম আবার বাড়ালে কার সাধ্যি আর কমায়! উপসংহারে, আমার মহাবিপদ!” শুনে ভাই বললেন, "শোন্ তাহলে-"। বলে যে কাহিনি বয়ান করলেন তা শুনে আমার চক্ষু চড়কগাছ। তলে তলে এত! সে কাহিনির অনুপুঙ্খ তথ্যাদি আমার মোটা মগজে ধরে রাখা দুষ্কর। তবে মূল ব্যাপারটা মোটামুটি এরকম। চালের বাজারের এই কলকব্জা নাড়ায় আসলে একশ্রেণীর ব্যবসায়ী। তাদের ভাইবেরাদররাই আবার সংসদে বসে। তাই ওইসকল ব্যবসায়ীর স্বার্থ রক্ষা করে চলা এই দেশনেতাদের বিশেষ কর্তব্য। চালের দরকার প্রতি বকৎ-এ। তাই এ জিনিসটাকে গুদোমে ভরে ফোঁটায় ফোঁটায় বাজারে ছাড়তে পারলে নিশ্চিত লাভ। সে লাভকে নিশ্চিত করতে ভাইবেরাদরের লাভের (Love) অন্ত নেই। কেননা, সে লাভের ঝড়তি-পড়তি তাদের থলেতেও জমা হয়। সবই তো ভাইবেরাদর! একেই নাকি বলে ‘সিন্ডিকেট’! শুনে-টুনে আমি একটু মিইয়ে গেলাম। তারপরে পেলাম ভয়। কেন? না, কেবল আগামী সিজনে চালের দাম বাড়ার ভয় না, আরো বড় ভয়। শুনতে পাই এবার নাকি যে ধান ফলাতে প্রতি মণে ৭০০ টাকা খরচ হয়েছে, তা চাষী ৪০০-৪৫০ টাকায় বিক্রি করতে বাধ্য হচ্ছে বাজারের কলে পড়ে। তার নগদ টাকা দরকার। যে দোকানে অ্যাদ্দিন সদাই খেয়েছে, সে দোকানে একগাদা টাকা বাকি। পাম্পঅলাকে জলের টাকা দিতে হবে। টাকা পাবে সারের মহাজন। উপরি সার দেয়ার সময় ইউরিয়ার আকাল ছিল। সারের গায়ে তখন আগুন। সেই আগুন-দরই মহাজনের খাতায় লেখা। সব মিলিয়ে তার বড় ত্রিশঙ্কু অবস্থা। তাই চারশ’ হোক আর দুশ’ হোক সরকারের কেনার অপেক্ষায় না থেকে ধান তাকে বেচতেই হচ্ছে। কিন্তু ঢাল-তলোায়ার বিহীন নিধিরাম চাষার এ লড়াই আর কদ্দিন! রণে ভঙ্গ তো সে দিল বলে! হয় ধান চাষ ছেড়ে আর কিছু চাষ করবে, নয়তো শহরে এসে রিকশা চালাবে, মুটেগিরি করবে, ইট ভাঙবে। এইরকম একে একে সব ধানচাষী যদি চাষবাস থেকে উৎখাত হয় (হচ্ছে এবং আরো হবে, সবুর করুন), দেশে যদি একটি ধানের কণাও আর উৎপন্ন না হয়, তবে বিদেশ থেকে আসা শস্তার চাল কি আর শস্তা থাকবে? তখন প্রতি দানা চাল যদি আমদের সোনার দরে কিনতে হয়, আর কীইবা আমাদের করার থাকবে? চোখের সামনে পষ্ট দেখতে পাচ্ছি, আজকে যে চাল তিরিশ টাকায় কিনে খাচ্ছি কাল তা পঁয়তাল্লিশ টাকা হলো বলে। তাতেই আমার রীতিমত নাভিশ্বাস উঠে যাবে। কারণ, চুরি-চামারি তো আমার বাপ আমাকে শিখিয়ে যান নি, ইনকাম সাকুল্যে দশটি হাজার টাকা। সেটি তো আর বিশেষ বাড়ছে না। কিন্তু পরশু বা তরশু যখন চালের দাম চারগুণ হবে (হওয়াটা মোটেও অসম্ভব নয়, যদি দেশে চাষী না থাকে), তখন কী উপায় হবে! শিল্প-সাহিত্য-চেতনা-দেশপ্রেম তখন আমার কোন পিতৃপুরুষের ছেরাদ্দে লাগবে‌! অতএব, বন্ধুগণ, ভাবুন। ভাবাটা জরুরী। বিপদটা আমার; কিন্তু আমার একলার না, সকলেরই। এই বাজার নামক দানবের যে জটিল অঙ্গসংস্থান, তার রূপটি সাধারণের কাছে তুলে ধরা দরকার। আমি গুণতে জানি না, খালি কম পড়লে টের পাই। সেই টেরটা পেয়ে যা বুঝেছি, তাই বললাম। যারা গুণতে জানেন তারা একটু গুণেটুনে বলুন। যারা অন্য আড্ডায় মশগুল, তারা একটু কান ফেরান, শুনুন। আপনাদের প্রতি গ্রাস ভাতের দোহাই, পাখি ও ফুল বিষয়ক আলোচনা মুলতুবি রেখে আপাতত ধানচাল বিষয়ে কথা বলুন। সুমনের যে গানটা দিয়ে শুরু করেছিলাম তারই শেষ লাইন কটা দিয়ে শেষ করি- _আমিও ভণ্ড অনেকের মত_ _গান দিয়ে ঢাকি জীবনের ক্ষত।_ _তবু বলি শোনো, দেখতে ভুলো না_ _অন্য ছবিও আঁকো!_ _অন্য ছবিও আঁকো!_ <file_sep>/_posts/2015-06-04-tare-koy-prem.markdown --- title: তারে কয় প্রেম date: 2015-06-04 06:00:00 +06:00 tags: - তত্ত্বতালাশ comments: true layout: post --- হরিচরণ বন্দ্যোপাধ্যায়ের বঙ্গীয় শব্দকোষে প্রেম শব্দটির ডজনখানেকের বেশি অর্থ দেয়া আছে। সেগুলো যথাক্রমে- প্রিয়ভাব, সৌহার্দ্দ, স্নেহ, ভালবাসা, ভ্রাতৃবাৎসল্য, যুবক-যুবতীর ধ্বংসরহিত ভাববন্ধন, অনুরাগ, প্রণয়, বিয়োগাসহিষ্ণুতা (বিয়োগ+অসহিষ্ণুতা), হর্ষ, নর্ম্ম, কৃষ্ণের ইন্দ্রিয়প্রীতির ইচ্ছা, গাঢ় রতি বা অনুরাগ। শব্দটির ব্যুৎপত্তি নির্দেশ করা আছে- প্রিয়+ইমন্। অর্থাৎ প্রিয়ভাব। প্রিয় শব্দটি আবার তৈরী হয়েছে প্রী ধাতু অ প্রত্যয় যোগে (√প্রী+অ)। প্রী ধাতুর অর্থ দেয়া আছে প্রীতি বা প্রীতিভাব। প্রিয় শব্দটির আবার গোটা আষ্টেক মানে। প্রীণয়িতা, অভীষ্ট, দয়িত, বল্লভ, অভিমত, প্রীতিকর, সহজপ্রীতিমান্, অনুরাগী প্রভৃতি। এখন শব্দটিকে কলিম খান নির্দেশিত বর্ণভিত্তিক-ক্রিয়াভিত্তিক শব্দার্থবিধিতে ফেলা যাক। মূল ধাতুটি প্রী। অর্থাৎ, প্+র্+ঈ। প্ = পালন-পান-প্রাপণ, র্ = রহন-ভক্ষণ-রক্ষণ ও ঈ = সক্রিয়। পালন রহন/রক্ষণ সক্রিয়। এর সাথে আছে অ প্রত্যয়। অ = অস্তিত্বন। সাকুল্যে প্রিয় (√প্রী+অ) কথাটির মানে দাঁড়ায় যে অস্তিত্বে পালন সক্রিয় থাকে (রহন=থাকা)। আবার আমরা এও বলতে পারি পালন-রক্ষণ (পালন করা ও রক্ষা করা) উভয়ই সক্রিয় যে অস্তিত্বে তাই 'প্রিয়'। এবার আসি ইমন্ প্রত্যয়ে। ই+ম্+অ+ন্। ই = সক্রিয়ন, ম্ = সীমায়ন। আর অন্ দ্বারা চলিষ্ণু ঘটনার নাম ব‌োঝায়। চলন, বলন, কথন ইত্যাদি। কেন এমন হয়? কলিম খানের মতটি হলো, অ = অস্তিত্বন ও ন্ = নাকরণ-অনকরণ। অনবচ্ছিন্ন অস্তিত্বের নেতিকরণ করেলই তাকে গতিলশীল করা হয়। যেমন ধরা যাক, একটা ফুটবল। দাঁড়িয়ে আছে চুপচাপ। নড়ছে-চড়ছে না। দিলাম এক লাথি। ধাঁ বেগে ছুটে গেল। যখন সে দাঁড়িয়ে ছিল, তখন ছিল একটি অনবচ্ছিন্ন সাম্যের মধ্যে। মহাবিজ্ঞানী নিউটন একে বললেন জড়তা। বলপ্রয়োগ না করলে স্থির বস্তু স্থির ও চলমান বস্তু চলমান থাকবে। সেই সাম্যভঙ্গ হলেই বলটি চলিষ্ণু হলো। তখন তার নড়ন(নড়্-অন্)-চড়ন(চড়্-অন) ঘটে। অতএব, ইমন্ হলো কোনো আধারে (সীমায়) ক্রিয়ার সক্রিয় ভাব। তাই প্রেম প্রিয়তার একটি বন্ধন বা আধার। এমনই বন্ধন যা পালন-রক্ষণে সক্রিয় থাকে। তা সক্রিয় থাকে নিরন্তর 'অন্' প্রক্রিয়ার মধ্য দিয়ে। অর্থাৎ অজস্র নেতির নেতিকরণের মধ্য দিয়েই প্রেম টিকে থাকে। এখন, দেখতে হবে প্রেম শব্দটি যতক্ষেত্রে ব্যবহৃত হয়, সর্বত্র এই সূত্র মেনে চলে কিনা। কবিগুরু বলেছেন, 'প্রেমের ফাঁদ পাতা ভুবনে'। যথার্থ কথা। দুনিয়াতে প্রেমের রূপ ও বৈচিত্র্যের অন্ত নেই। মরমী কবি বিজয় সরকার যেমন ঈশ্বর বিষয়ে বলেন, 'বহুনামে ধরাধামে কত রঙ্গ যে দেখি!' তেমনই বিচিত্র রঙ্গে লীলাময় প্রেম। নর-নারীর প্রেম, দেশপ্রেম, পরকীয়া প্রেম, কৃষ্ণপ্রেম, বন্ধুপ্রেম, বাৎসল্যপ্রেম, বইপ্রেম, ক্রীড়াপ্রেম, পশুপ্রেম, বৃক্ষপ্রেম, প্রকৃতিপ্রেম; যেদিকে তাকাই শুধু প্রেম আর প্রেম। দেখা দরকার, আমরা ব্যুৎপত্তি নির্ণয় করে যে শব্দার্থ নিষ্কাশন করেছি তা এই সকল প্রেমের ক্ষেত্রে ন্যূনতম শর্ত হিসেবে কাজ করে কিনা। আমি প্রয়োগ করে দেখেছি কাজ করে। সকল প্রেমের তত্ত্বতালাশ এ স্থলে বাঞ্ছনীয় নয়। অতএব হাঁড়ির দু একটি ভাত টিপে দেখা যাক। ধরা যাক, দেশপ্রেম। 'দেশে জন্মালেই দেশ আপন হয় না', বলেন রবীন্দ্রনাথ (এই হয়েছে এক জ্বালা। এই বুড়োকে বাদ দিকে কিছুই গুছিয়ে বলবার জো নেই!)। দেশপ্রেমের প্রশ্ন আসলেই তাকে রক্ষা করার প্রশ্ন আসে। দেশে সকল শুভ সম্ভাবনাকে পালন করে বিকশিত করার প্রশ্ন আসে। তা করতে গিয়ে অসংখ্য নেতির সাথে লড়াই করা প্রশ্ন আসে। অতএব পালন-রক্ষণার্থ নেতির বা অশুভের বা বাধা-বিপত্তির সাথে লড়াই দেশপ্রেমের একটি শর্ত। আবার ধরুন আপনি বইপ্রেমী লোক। আপনাকে বইয়ের যথাযথ রক্ষণাবেক্ষণ করতে হবে। তা করতে হবে পোকামাকড়, আর্দ্রতা ইত্যদির সাথে লড়াই করেই। কিম্বা আপনি বৃক্ষপ্রেমী মানুষ। আজ যে মহীরুহ চারা তাকে ছাগলে যাতে না মুড়োয় সেই ব্যবস্থাটি করাই তো আপনার প্রেমের প্রকাশ। অথবা, বন্ধুপ্রেমের কথাই ধরুন। বন্ধু বিপদে পড়লে আপনি নিশ্চয়ই তাকে রক্ষা করেন। ছাত্রাবস্থায় দরিদ্র প্রিয় বন্ধুটির পালনের ভারও নিয়েছেন নিশ্চয়ই। ঝগড়া-বিবাদ, মান-অভিমান নিশ্চয়ই হয়েছে। সেগুলোর নেতিকরণ অর্থাৎ সমাধান করেই বন্ধুত্ব অগ্রসর হয়েছে। ভাতে উতোল এসে গেলো। আরেকটি চাল পরীক্ষা করি এবার। যুবক-যুবতীর ধ্বংসরহিত ভাববন্ধন। নরনারীর এমন প্রেম খুঁজে পাওয়া বিরল যা কিনা অসংখ্য প্রকার বাধাবিপত্তি মোকাবেলা করে অগ্রসর হয় নি (দু-একটি নিপাতনে সিদ্ধ ব্যতিক্রম থাকতে পারে)। কত না কাব্যকাহিনি, উপন্যাস, নাটক নির্মিত হয়েছে কেবল নরনারীর প্রেম নিয়ে। লাইলি-মজনু, শিরি-ফরহাদ, রোমিও-জুলিয়েট, রাধা-কৃষ্ণ আরো কত! কখনো প্রেমিকা সংকল্পবদ্ধ- ভয়বাধা সব অভয়মূর্তি ধরি পন্থ দেখায়ব মোর। কখনো লাইলির খোঁজে মজনু পাগলপারা। মরুপথে ক্যারাভান থেকে ক্যারাভানে খুঁজে বেড়াচ্ছে তার জান-ই-মন-এর দিশা। অথবা জুলিয়েটের আর্তি - “O Romeo, Romeo, wherefore art thou Romeo? Deny thy father and refuse thy name...”। সব প্রেমিকযুগলই পালন করে কিছু সংকল্প, স্বপ্ন ও আকাঙ্খা। পরস্পরকে রক্ষা করতে চায়, এমনকি জীবনের বিনিময়ে। সে সব আমরা সিনেমাতেও দেখি হামেশাই। আক্রান্ত নায়িকাকে রক্ষা করছে নায়ক অথবা নায়িকা দরিদ্র নায়ককে রক্ষা করছে তার দোর্দণ্ডপ্রতাপ ক্ষমতাবান পিতা 'চৌধুরী সাহেবের' রোষ থেকে। অতএব, এ পর্যন্ত যা দেখা যাচ্ছে দেশপ্রেমই হোক আর লাইলি-মজনুর প্রেমই হোক, প্রেম হতে হলে বা প্রেম করতে হলে দুটো শর্ত মানতে হবে। এক, সম্পর্কটির আধারে বহুবিধ বিষয় পালন ও রক্ষণ করতে হবে। দুই, তা করতে গিয়ে বহু রকমের নেতির বিরুদ্ধে লড়াই করতে হবে। নইলে পাশ্চাত্যের অনুকরণে উপরিভাসা কিছু একটা হবে বটে, কিন্তু তা বাংলা ব্যুৎপত্তি সিদ্ধার্থ প্রেম হবে না। <file_sep>/_posts/2015-10-31-boro-howa-prosonge.markdown --- title: বড় হওয়া প্রসঙ্গে date: 2015-10-31 06:00:00 +06:00 tags: - তত্ত্বতালাশ comments: true layout: post --- আশৈশব গুরুজনেরা মাথায় হাত রেখে আশীর্বাদ করেছেন, “বড় হও বাবা, মানুষ হও।” বাক্যের শেষ অংশটুকু বুঝতে বিশেষ কষ্ট হয়নি। খুবই স্পষ্ট। তারা চেয়েছেন, আমি যেন ন্যূনতম মানবিক গুণসম্পন্ন হয়ে বেড়ে উঠি। আমি যেন অমানুষ বা জালেম বা পিশাচ ইত্যাদি না হই। কিন্তু গোল বাঁধল প্রথম অংশ নিয়ে। ‘বড় হওয়া’ কথাটি দিয়ে আসলে মানুষ কী বোঝাতে চায়! তত্ত্ব-তালাশ করতে গিয়ে দেখলাম, কথাটা একটা বিরাট গোলকধাঁধা। ‘বড় হওয়া’ বিষয়টা একেকজন একেকরকম করে বোঝে। যেমন, কেউ বড় হওয়া বলতে বোঝে অনেক টাকাপয়সার মালিক হওয়া। তাঁদের মতে টাকা থাকলে দুনিয়ায় সব হয়। আবার, কেউ বড় হওয়া বলতে বড় প্রতিভাবান হওয়া বোঝে। অর্থাৎ, বড় শিক্ষক, বড় লেখক, বড় গায়ক, বড় আবৃত্তিকার, বড় অভিনেতা, বড় সাধুসন্ন্যাসী, বড় দার্শনিক ইত্যাদি। সবরকমের বড় হওয়াকে একটা সাধারণ সূত্রে আনতে আমার বেশ বেগ পেতে হয়েছে। মোটা দাগে, বড় হওয়ার আসল মানে হলো গুরুত্বপূর্ণ হওয়া। যে কোনো উপায়ে সমাজে কেউকেটা হওয়া। কেউ কেউ বলেবেন- “এ তো খুবই স্বাভাবিক! এটা মানুষের প্রবৃত্তিগত ব্যাপার!” সবিনয়ে তাদের বলি, আমি তা মনে করি না। কেন? সেই কথাই পাড়ি ধীরেসুস্থে। বড় হওয়ার দরকার কেন? সেটা কি বেশি ভোগের স্পৃহা থেকে উদ্ভূত? যদি তা হয়, সেই ভোগস্পৃহা কি স্বাভাবিক না আরোপিত? বড় হওয়ার প্রচলিত অর্থ অনুযায়ী সকল মানুষের কি বড় হওয়া সম্ভব? যদি সম্ভব না হয়, তবে তার সুফল কারা ভোগ করে? শ্রেণীবিভক্ত সমাজে মানুষের উপরে মানুষের শোষণ বলবৎ থাকে। ফলে সমাজটা হয় প্রতিদ্বন্দ্বিতা ও শত্রুতায় পূর্ণ। এ ধরণের সমাজে স্রেফ গ্রাসাচ্ছাদনের জন্যও সংখ্যাগুরু মানুষকে উদয়াস্ত হাড়ভাঙা খাটুনি খাটতে হয়। আর সংখ্যালঘু বিত্তবান অংশ সুখ-সাচ্ছন্দে জীবন অতিবাহিত করে। এই দুই শ্রেণীর মধ্যে আরেক ধরণের লোক থাকে যারা ‘না ঘরকা, না ঘাটকা’। তারা প্রচুর বিত্তশালী না, আবার হতদরিদ্রও না। এরা বিত্তবান সমাজের চুঁইয়ে পড়া উচ্ছিষ্টের সুফল ভোগ করে এবং শয়নে-স্বপনে-জাগরণে ওই শ্রেণীভুক্ত হওয়ার স্বপ্ন দেখে। চেষ্টা করে ‘বড়লোক’ হওয়ার। এই চেষ্টাটাকে তারা বলে ‘জীবনসংগ্রাম’, ‘স্ট্রাগল্’। এই স্ট্রাগলেরই অভীষ্ট হলো ‘বড় হওয়া’, যা কেউ কেউ হয়, অধিকাংশই হয় না। বড় হতে পারলে এক ধরণের সামাজিক মর্যাদা পাওয়া যায়, সেটা সমাজে এক ধরণের নিরাপত্তা। অধিকতর সুখ-সাচ্ছন্দে থাকা যায়। মোট কথা, ভোগের মাত্রা বহুগুণ বাড়ানো যায়। এখনকার প্রশ্নটি হলো এই অতিভোগের ইচ্ছা ‘কতখানি খাঁটি, আর কতখানি জল মেশানো’? পুঁজিবাদী অর্থনীতির ভোগের চ্যাপ্টারটা খুললেই দেখা যাবে লেখা আছে, “ভোগ একটি মানসিক ধারণা।” অর্থাৎ, সত্যিকার জৈবিক প্রয়োজন না থাকলেও মানুষ ভোগ করে। ভোগের পিছনে কিছু উদ্দীপনা কাজ করে। খেয়াল করে দেখবেন, সাবান, জুতো, টেলিভিশন, চিপস্, ক্রাকার্স ইত্যাদি জিনিসের কোম্পানিগুলো মাঝে মাঝে বিশেষ অফার দেয়। হালে সবচেয়ে বেশি অফার দেয় মোবাইল ফোন অপারেটররা। সব অফারের মূলকথা হলো অল্প টাকায় পণ্যটির বেশি একক কেনার সুযোগ। এটা একধরণের উদ্দীপক বা স্টিমুলি। এই স্টিমুলি দিয়ে মানুষের ভোগের আকাঙ্ক্ষা বাড়িয়ে তোলা হয়। এই রকম অসংখ্য স্টিমুলি ব্যাবসাদাররা মানুষের উপর প্রয়োগ করে। কারণ, তাদের বেশি বেশি মাল বেচা দরকার। সমাজের মাতব্বর যখন ব্যবসাদাররা, তখন সেই সমাজের মূল উদ্দেশ্যই থাকে মাল বেচা ও পকেট ভরা। তাই, সেই সমাজের তাবৎ সংস্কৃতিক উপাদানও এই বেচাবিক্রির প্রক্রিয়াকে অনুসরণ করে চলে। যা হাটে তোলা যায় না, তা এ সমাজে অচল। তাই, বড় হওয়ার ধারণাটিকে তারা শ্রেণী-নির্বিশেষে ছড়িয়ে দিতে চায়। কারণ, বড় হওয়ার আকাঙ্ক্ষা তৈরি হলে অনিবার্যভাবে ভোগের আকাঙ্ক্ষা বাড়বে। আর ভোগের আকাঙ্ক্ষা বাড়লে বেচাবিক্রি বাড়বে। বেচাবিক্রি বাড়লে অর্থাগম বেশি হবে। গোটা ব্যাপারটা মোটেও এরকম সরল নয়। এটি একটি বিরাট কর্মযজ্ঞ। পুরো প্রক্রিয়াটি ধরে রাখতে একটি বিরাট সমন্বিত কাঠামো গড়ে উঠেছে। একদিকে আছে শিক্ষা-ব্যবস্থা। যার দ্বারা এই ভোগের চক্র বুদ্ধিবৃত্তিকভাবে টিকে থাকে। শিক্ষার প্রতিটি পর্যায়ে ‘বড় হওয়ার’ ‘সুমহৎ’ আকাঙ্ক্ষাকে আরো জোরদার করে তোলা হয়। আরেকদিকে রয়েছে গণমাধ্যম, যা কিনা সাধারণের ভিতরে ভোগের ইচ্ছা উস্কে দেয়ার কাজটি জারি রাখে। তারা আমাদের শেখায়, মা সারাজীবন গরমে কষ্ট পেয়েছেন। মাতৃভক্ত সন্তান তাই অমুক কোম্পানির ফ্রিজ কিনে নৌকায় করে যাচ্ছে মায়ের কাছে। অতএব, অমুক কোম্পানির ফ্রিজ না হলে মায়ের মুখে হাসি ফুটবে না। তারা আরো শেখায়, অমুক ব্রান্ডের শিশুখাদ্য না খেলে আপনার সন্তান বুদ্ধি প্রতিবন্ধী হয়ে বড় হবে। গরীব বাবার কালো-কুচ্ছিত মেয়ের বিয়ে হয় তমুক ব্রান্ডের ফেয়ারনেস ক্রিমের কল্যাণে। অমুক চিপস্ নাকি ‘দরজা বন্ধ করে একা একা’ খেতে হয়। তমুক বডি স্প্রে মাখলে পরকীয়ায় নাকি খুব সুবিধা হয়। আরো আরো বহু উদাহরণ দেয়া যাবে ইচ্ছে করলে। এমনকি, এসব কোম্পানির মুখে দেশপ্রেমের বুলিও আজকাল আমাদের শুনতে হয়। অর্থাৎ, মানুষের সকল ধরণের আবেগই এদের মাল বিক্রির হাতিয়ার এখন। আর এই অধিকতর মাল কিনতে পারার ক্ষমতা অর্জন করারই আরেক নাম বড় হওয়া। ‘বড় হওয়া’ শব্দবন্ধটির একরকমের ভ্রান্তি বা ইল্যুশন থাকে। আরো বেশি ইল্যুশন ও থ্রিল আছে স্ট্রাগল বা জীবনসংগ্রাম শব্দটার মধ্যে। আর ‘বড় হওয়ার জন্য স্ট্রাগল করা’ এই শব্দগুচ্ছটি যে মাত্রার ইল্যুশন তৈরি করে তা তুলনাহীন। এতক্ষণ যে মাল বেচাবিক্রির নগ্ন স্বার্থের কথা বলালাম তার গোটাটাকেই ব্যক্তিমানসে একটা মহত্বের চাদর দিয়ে ঢেকে দেয়া চলে কেবল এই শব্দগুচ্ছ দিয়ে। এইখানে থেমে আবার একটু পিছনে ফেরা দরকার। ধরুন, একটি ছেলে। বাপ নেই, বড় সংসার। বড় ভাইটি অল্প উপার্জন করে। ছেলেটি পড়াশুনা করছে। তাকে বড় হতে হবে। পরিবারের দুঃখ ঘোচাতে হবে। সে প্রাণপণ চেষ্টা করছে বড় হওয়ার। এবার তার ঘর থেকে বেরিয়ে ওইরকম আরেকটি ঘরে ঢুকুন। দেখবেন একই চিত্র। বাংলাদেশের, সারাবিশ্বের, লাখ লাখ, কোটি কোটি পরিবারের একই দৃশ্য। সবাই বড় হতে চাইছে। বড় কিন্তু খুব অল্প লোকেই হবে। কেননা সবাই বড় হয়ে গেলে কারোরই আর বড় হওয়ার দরকার থাকবে না। বড় হওয়ার দরকার আছে, কেননা একদলের অঢেল আছে, আরেক দলের কিচ্ছু নেই গতর ছাড়া। একদল গতর খাটিয়ে খায়, আরেকদল গতর পুষে চলে। এই ভেদ দুনিয়াতে আছে বলেই মানুষের বড় হওয়ার দরকার পড়ে। ব্যক্তির কাছে এই বড় হওয়া দরকারি হতে পারে, কিন্তু মহৎ নয় আদৌ। এমনকি, দৃষ্টিটা আমরা যতই প্রসারিত করব, ততই বড় হওয়ার ধারণাটির অসারত্ব ধরা পড়বে। ততই, আমারা বুঝতে পারব ‘বড় হওয়ার স্ট্রাগল’টা আসলে একটা জুয়াখেলা। এবং চূড়ান্তরকমের অমানবিক জুয়া। এ যেন সেই গাধার নাকের সামনে ঝুলানো মুলোর মত (খুবই পুরোনো কিন্তু সবচেয়ে সঠিক উপমা)। এই বড় হওয়ার প্রক্রিয়া সমাজে চালু থাকলে কারবারী লোকের নানানরকম সুবিধা। বেচাবিক্রির কথাটা আগেই বলেছি, তারও চেয়ে বড় একটি সুবিধা আছে। সংখ্যাগুরু মানুষ এবং বিশেষ করে যারা তাদের মধ্যে আবার প্রাতিষ্ঠানিক শিক্ষাদীক্ষার সুযোগ পেয়েছে, তারা এই জুয়াখেলায় মত্ত থাকে। এই জুয়ার নেশা তাদের ভুলিয়ে দেয়, মানুষের দুর্দশার মূল কারণ ও তার সমাধানসূত্র ব্যক্তিপর্যায়ের ব্যাপার না। মূল গলৎটি সমাজের অর্থনীতির কেন্দ্রে। ব্যবস্থাটি না বদলালে এই হারাজেতার খেলাই চলতে থাকবে, বহুতর মানুষের ভাগ্যের কোনো উন্নতি ঘটবে না। এই বোধহীনতা এই সমাজ টিকিয়ে রাখার সবচেয়ে বড় অস্ত্রগুলোর একটি। তাই এই সমাজে ‘বড় হওয়ার সংগ্রাম’ খুবই মহৎ আর মানবমুক্তির সংগ্রাম খুবই ‘বিপজ্জনক’। এইবারে আবার গোড়ার কথাটায় যাই। প্রহসনটি হলো, ‘বড় হওয়া’ আর ‘মানুষ হওয়া’ একই সাথে সম্ভব কিনা। মানুষ হওয়ার অর্থ যদি সৎ, নির্ভীক, সত্যবাদী, মানবপ্রেমী, পরিবেশ সচেতন ইত্যাদি মানবিক গুণসম্পন্ন হওয়া বোঝায় তবে বড় হওয়া তার আর হয়ে ওঠে না। কেউ তর্কের খাতিরে বলতে পারেন, “আহা! ওসব বাদ দাও। ‘বড় হওয়া’ বলতে তো ‘বড় মানুষ হওয়া’ও বোঝানো যেতে পারে।” এইবার আসলে অট্টহাসির সময়। ঠিকঠাক মানুষ হতে পারলে আবার আলাদা করে বড় মানুষ হওয়ার কী প্রয়োজন, সেটাই আরেকটা রহস্য! <file_sep>/_posts/2016-11-22-letter-from-chief-seattle.markdown --- title: সর্দার সিয়াটলের চিঠি - আমেরিকার প্রেসিডেন্টের উদ্দেশ্যে (১৮৫২) date: 2016-11-22 06:00:00 +06:00 tags: - অনুবাদ comments: true fimage: "/images/Chief_seattle.jpg" layout: post --- <a href="/images/Chief_seattle.jpg" data-toggle="lightbox" data-title="সর্দার সিয়াটল"><img class="thumbnail img-fluid" src="/images/Chief_seattle.jpg" alt="সর্দার সিয়াটল"/></a>ওয়াশিংটনের প্রেসিডেন্ট বলে পাঠিয়েছেন যে তিনি আমাদের জমি কিনতে চান। কিন্তু আকাশ কি আপনি বেচাকেনা করতে পারেন? ভূমি? এই ধারণাটাই আমাদের কাছে আজব! আমরা যদি বাতাসের পরিচ্ছন্নতা আর জলের চকমকির মালিক না হই, তবে আমরা তা বিক্রি করব কীভাবে? এই পৃথিবীর প্রতিটি অংশই আমার মানুষের কাছে পবিত্র। পাইন গাছের প্রতিটি সূঁচালো পাতা, পোকামাকড়ের গুঞ্জন; সবই আমার জনগণের পবিত্র স্মৃতি আর অভিজ্ঞতা। গাছের দেহের ভিতরে বয়ে চলা প্রাণরস আমরা তেমনই জানি, যেমন জানি আমাদের ধমনীতে বয়ে চলা রক্তস্রোত। আমরা এই পৃথিবীর অংশ, এই পৃথিবীও আমাদেরই অংশ। সুরভিত ফুল আমাদের বোন। ভাল্লুক, হরিণ, বিরাট ঈগল; এরা আমাদের ভাই। এই পাহাড়শ্রেণী, এই সরেস তৃণভূমি, এই টাট্টু ঘোড়াটির দেহের ওম, এবং একটি মানুষ— এরা সবাই একই পরিবারের অংশ। নদীর স্রোতে যে উজ্জ্বল জলধারা বয়ে যায় তা নেহায়েতই জল নয় শুধু, তা আমাদের পূর্বপুরুষের রক্ত। আমরা যদি আপনাদের কাছে জমি বিক্রি করি, আপনাদেরকে অবশ্যই মনে রাখতে হবে তা পরম পবিত্র। হ্রদের স্বচ্ছ জ্বলে প্রতিটি অতীন্দ্রিয় প্রতিচ্ছবি আমার মানুষদের জীবনের অগুনতি ঘটনা আর স্মৃতি মনে করিয়ে দেয়। জলের কলোচ্ছ্বাসে আমি আমার পিতা-পিতামহদের কণ্ঠস্বর শুনতে পাই। এইসব নদীরা আমাদের ভাইয়ের মত। তারা আমাদের তেষ্টা মেটায়। আমাদের নৌকা বয়ে নিয়ে যায়, আমাদের বাছাদের মুখে খাবার যোগায়। তাই নদীর প্রতি আপনারা তেমনই সদয় হবেন, যেমন সদয় আপনারা আপনাদের ভাইদের প্রতি। যদি আমরা আমাদের জমি বিক্রি করি, মনে রাখবেন যে বাতাস আমাদের কাছে কত মূল্যবান! মনে রাখবেন, বাতাস তার প্রাণশক্তি দিয়ে আমাদের বাঁচিয়ে রেখেছে। বাতাস আমাদের পিতামহদের প্রথম প্রশ্বাসটি দান করেছে, আর শেষ নিশ্বাসটি গ্রহণ করেছে। বাতাস আমাদের সন্তানদেরও দিয়েছে তার অফুরাণ প্রাণের অংশ। তাই, যদি আমরা আমাদের জমি বিক্রি করি, আপনারা অবশ্যই একে এমনই স্বতন্ত্র ও পবিত্র করে রাখবেন, যেন সেখানে মানুষ যেতে পারে তৃণপুষ্পের সূধাসৌরভে পুষ্ট পরিচ্ছন বায়ু সেবন করতে। আপনারা কি আপনাদের সন্তানদের তা-ই শেখাবেন, যা আমরা আমাদের সন্তানদের শিখিয়েছি? শেখাবেন যে এই পৃথিবী আমাদের মা? যা কিছু এ পৃথিবীর কোলে আছড়ে পড়ে তা সবই তার সন্তান? এটাই আমরা জানি: পৃথিবী মানুষের জন্য নয়, মানুষ এই পৃথিবীর জন্য। সবকিছুই রক্তসম্পর্কের মত যা আমাদের একসূত্রে গেঁথে রেখেছে। জীবনের এই জাল মানুষ বোনে নি, সে বড়জোর তার একটা সুতো মাত্র। এই জালের যেখানে সে যা-ই করুক, সে আসলে নিজেরই উপরেই তা করছে। একটি বিষয় আমরা জানি: আমাদের ঈশ্বর তোমাদেরও ঈশ্বর। এই পৃথিবী তাঁর কাছে মূল্যবান এবং এই পৃথিবীর কোনো ক্ষতি করা তাঁর সাথেই চরম বেআদবি করার সমান। তোমাদের গন্তব্য আমাদের কাছে এক রহস্য! কী হবে, যখন সব মোষ জবাই করা হয়ে যাবে? সবগুলো ঘোড়া যখন বন্দী হয়ে যাবে? কী হবে, যখন বনভূমির গভীরতম অঞ্চল মানুষের গন্ধে পরিপূর্ণ হয়ে যাবে আর সমুচ্চ পাহাড়শ্রেণী আচ্ছন্ন হয়ে যাবে কথাবলা তারে? ঘন ঝোপঝাড় কোথায় থাকবে? চলে যাবে! ঈগলেরা কোথায় থাকবে? চলে যাবে! এই টাট্টু ঘোড়া আর শিকারদের বিদায় জানানোকে কী বলব? বেঁচে থাকার সমাপ্তি আর টিকে থাকার শুরু। যখন শেষ লাল আদিবাসী মানুষটি তার বন্যতা নিয়ে উধাও হবে আর তার তার স্মৃতি কেবলই মেঘের ছায়ার মত এই প্রেইরিতে ঘুরে বেড়াবে, এই তটভূমি আর এই অরণ্য কি সেদিন এখানে থাকবে? আমার মানুষদের একটি আত্মাও কি এখানে থাকবে? আমরা এই পৃথিবীকে তেমনিভাবেই ভালবাসি, যেমনিভাবে সদ্যজাত শিশু তার মায়ের হৃদয়ের ধ্বনি ভালবাসে। তাই যদি আমরা আমাদের জমি তোমাদের কাছে বিক্রি করি, তোমরাও তাকে তেমনই ভালবেসো যেমন আমরা বাসি। তেমনিভাবেই এর যত্ন নিয়ো, যেমন আমরা নিয়েছি। এই ভূমির স্মৃতি যেমনটি আছে ঠিক তেমনই মনের মধ্যে ধরে রেখো। এই ভূমিকে সব সন্তানের জন্য রক্ষা কোরো ও ভালবেসো, যেমন ঈশ্বর আমাদের বাসেন। আমরা যেমন এই ভূমির অংশ, তোমরাও তেমনই। এ পৃথিবী আমাদের কাছে মূল্যবান। তেমনি মূল্যবান তোমাদের কাছেও। একটি কথা আমরা জানি: একজনই ঈশ্বর। সাদা-কালো মানুষে মানুষে ভেদ নেই কোনো, ভেদ শুধু মানুষের সাথে তাঁর। আমরা সবাই সবার ভাই। <file_sep>/_posts/2015-02-19-যাহা-বলিব-সত্য-বলিব.markdown --- title: যাহা বলিব সত্য বলিব date: 2015-02-19 00:00:00 Z tags: - রসনাবিলাস - কচুতত্ত্ব layout: post comments: true --- এ কথা স্বীকার করতে দ্বিধা নেই, আমার রুচিবোধ অত্যন্ত মোটাদাগের। অধিকাংশ ক্ষেত্রেই আমার আনন্দ উপভোগের উপায় খাওয়া-দাওয়া ইত্যাদি নিম্নস্তরের ক্রিয়াক্রর্মের মধ্যে সীমাবদ্ধ। আমি ওস্তাদি গানের চেয়ে বিজয় পাগলেই শান্তি পাই বেশি। কোনো কোনো ক্ষেত্রে রবীন্দ্রনাথের চেয়ে রাধারমণই বেশি টানে আমাকে। আমার অানন্দের সবচেয়ে বড় উপায় হলো খাওয়া। একে যদি লোভ বলে কেউ, তাতেও আমার আপত্তি নেই। একখণ্ড উৎকৃষ্ট মানকচু আর দু’টুকরো শোল মাছের জন্য আমি সহস্রবার বাঙলাদেশে জন্মাতে রাজি আছি। আহা! কোথায় শ্রাবস্তীর কারুকার্য, কোথায় কান্তজীর মন্দির আর কোথায়ই বা মায়া-অ্যাজটেক সভ্যতার স্থাপত্যশৈলী! সফেদ মোলায়েম মানকচুর সাথে সুঠাম শোলমাছের মরণান্ত প্রেমের এইরকম অপরূপ তাজমহলের তুলনা আর কীইবা হতে পারে! একখণ্ড উৎকৃষ্ট চইঝাল যেন শিরাজী সূধার মত সেই প্রেমে ঝাঁজ আর সুগন্ধ ছড়াচ্ছে। হঠাৎ ঈশ্বরে বিশ্বাস করতে ইচ্ছে হচ্ছে। মনে হচ্ছে ঈশ্বরকে প্রশ্ন করি, “হে পরম করুণাময়, পরমপিতা, পরমবিভুতি, পরম ভাগবৎ; স্বর্গে মানকচু আর শোল মাছ পাওয়া যাবে তো?” <file_sep>/_posts/2016-12-27-academy-samachar.markdown --- title: আকাদেমি সমাচার date: 2016-12-27 14:20:00 +06:00 tags: - রঙ্গ - কেরিকেচার - বাঁকা কথা layout: post fimage: "/images/কাক্কেশ্বর.png" comments: true --- <a href="/images/কাক্কেশ্বর.png" data-toggle="lightbox" data-title="শ্রী কাক্কেশ্বর কুচকুচে"><img class="thumbnail img-fluid" src="/images/কাক্কেশ্বর.png" style="float:left;" alt="/images/কাক্কেশ্বর.png"></a>দুপুরবেলা চাট্টি খাওয়ার পরে পোষ মাসে বেশ একটু শীত-শীত করে। লেপের মধ্যে হাত-পা সেঁধিয়ে বেশ একটু মটকা মেরে পড়ে থাকতে নেহাত মন্দ লাগে না। আজকে দুপুরেও সেই আয়োজনই হচ্ছিল। খাওয়াটাও হয়েছে বেড়ে! পুঁই শাকের মিচলির চচ্চড়ি, মৌরলার ঝোল আর আমরুলি শাকের তোফা একটা অম্বল দিয়ে চাট্টি গরম ভাত খেয়ে যেই না লেপ মুড়ি দেবার উদ্‌যোগ কচ্ছি, এমন সময়, কে যেন ভাঙা-ভাঙা ভারী মোটা গলায় ডেকে উঠল, "কাআআআ!" কী আপদ! এই মটকা মারার সময়ে আবার এমন বিচ্ছিরি আওয়াজ করে কে! তাকিয়ে দেখি, উঠোনে কাপড় নাড়া যে তারটি রয়েছে, তার উপরে বসে আছে স্বয়ং কাক্কেশ্বর। শ্রী কাক্কেশ্বর কুচকুচে। দেখে লাফিয়ে উঠলাম। সেই কবেকার কথা! আট বছর বয়সে দেখা হয়েছিল কাক্কেশ্বরের সাথে। কী সব হিসেবটিসেব করার একটা ব্যাবসা খুলেছিল। তারপর, সেই যে কোর্ট চত্ত্বর থেকে পাখা ঝাপটে কোথায় চলে গেল, অ্যাদ্দিন পরে এই দেখা! তাও আমারই উঠোনে! বিশ্বাস হতে চাইছিলো না। ভাবলাম এবারও সেবারকার মত স্বপ্ন দেখছি না তো! চোখটোখ কচলে দেখলাম, না, ঠিকই আছে। কাক্কেশ্বরই। বিস্ময়ের ঘোর কাটিয়ে বললাম, "আরে কাক্কেশ্বর যে!" বুড়ো হয়ে গেছে বেচারা। কুচকুচে উপাধিটা এখন আর তার নামের সাথে যায় না। উষ্কোখুষ্কো পালক, সেই চিক্কণ কৃষ্ণবর্ণ এখন আর নেই। বললাম, "কোত্থেকে অ্যাদ্দিন পরে? কী করছো-টরছো কী আজকাল? তোমার সেই হিসেবের ব্যাবসা আছে এখনো?" কাক্কেশ্বর বলল, "কী যে বলো! এখন হলো কম্পিউটারের যুগ, ডিজিটাল যুগ। আমার হিসেব কী এখন চলে! সে ব্যাবসা লাটে উঠেছে বহুদিন আগে।" একটু এদিক-ওদিক তাকিয়ে চোখ মটকে ফিসফিস করে আমাকে বললো, "একটা নতুন ব্যাবসা খুলেছি!" আমিও অতি আগ্রহে জিগ্যেস করলাম, "কী ব্যাবসা?!!" কাক্কেশ্বর তখন একতাড়া কাগজের মধ্য থেকে একটা কাগজ আমার হাতে দিল। দেখলাম একটা হ্যান্ডবিল। কম্পিউটার কম্পোজ করে ফটোকপি করা। ঘষা ঘষা লেখা, পড়তে একটু কষ্ট হয়। দেখলাম,তাতে লেখা রয়েছে-- <div style="width:100%; padding: 40px; background-color: #dcdcdc; box-shadow: 1px 2px 4px grey;"> <div style="border: 4px double; padding: 20px"> <p style="text-align:center; font-weight:600;">শ্রীশ্রীভূশণ্ডিকাগায় নমঃ<br> শ্রীকাক্কেশ্বর কুচ্‌কুচে<br> ৪১নং গেছোবাজার, কাগেয়াপটি </p> <div style="border-top:2px solid; width: 80%; margin:auto"></div> <p></p> <h2 style="text-align:center;">বাংলা একাডেমী অনুমোদিত</h2> <h3 style="text-align:center;">১ নং দিশি লঘুকৃত রেক্টিফায়েট স্পিরিট বা বংলা মদ</h3> <p style="text-align:justify;"> হে সূরামোদী বঙ্গবাসী, তামাম বঙ্গাল মুলুকে আমরাই বাংলা মদের একমাত্র নির্ভরযোগ্য পরিবেশক। একশতভাগ খাঁটি রেক্টিফায়েড স্পিরিটের সাথে শতভাগ শুদ্ধ পাতিত জল বা ডিস্টিলড্ ওয়াটার মিশিয়ে এই মদ প্রস্তুত করা হয়। আপনার ঠিকানা আমাদের লিখে পাঠালে বা ইমেইল করলে বা এসএমএস করলে আমরা বোতল পার্শেল করে থাকি। মূল্য প্রতি লিটার ২৫০ টাকা, পার্শেল ফি ১০০ টাকা। নেশা না হলে মূল্য ফেরত। </p> <h1 style="text-align:center; font-size: 2rem;"><strong>সাবধান! সাবধান!! সাবধান!!!</strong></h1> <p style="text-align:justify;">আমরা সনাতন বায়সবংশীয় দাঁড়িকুলীন, অর্থাৎ দাঁড়কাক। আজকাল নানাশ্রেণীর পাতিকাক, হেঁড়েকাক, রামকাক প্রভৃতি নীচশ্রেণীর কাকেরাও অর্থলোভে নানারূপ ভেজাল মদের ব্যবসা চালাচ্ছে। সাবধান! তাদের মেথিলেটেড স্পিরিট মিশ্রিত মদ খেয়ে অক্কা পাবেন না!</p> <p style="text-align:center; font-weight:bold;">***<br><strong>মনে রাখবেন, আমরাই বাংলা একাডেমী স্বীকৃতি একমাত্র বাংলা মদ পরিবেশক।</strong></p> </div> </div> <br> আমার তো চক্ষু চড়কগাছ! "কাক্কেশ্বর! কী লিখেছ এসব! বাংলা একাডেমির কাজ তো শুনেছি ভাষাটাষা, বইপত্তর নিয়ে। তারা আবার মদের লাইসেন্স দেয়া শুরু করলো কবে থেকে? আশ্চর্য!" শুনে কাক্কেশ্বর "তাও জানো না!" বলে সেই লাল হুলো বেড়ালটার মত বিশ্রীরকমে ফ্যাঁচ-ফ্যাঁচ হাসতে লাগলো। আমি বললাম, "না জানি না। হেয়ালি না করে ভেঙে বলো তো দেখি ব্যাপারখানা।" কাক্কেশ্বর এক চোখ বুজে কী যেন খানিক ভাবলো। তারপর বলল, "শোনো"। বলেই আবার দু চোখ বুজে বসে রইলো। তারপর, চোখ দুটো খুলে গোল গোল চোখে হড়বড় করে বলতে শুরু করলো, "এদিকে হয়েছে কী, শ্রাবণ প্রকাশনীর রবিন ভাই বাংলা একাডেমিতে বইমেলার ফরম তুলতে গিয়ে শোনে তাকে ফরম দেবে না! কী কাণ্ড! কেন দেবে না!? মহাপরিচালক মুখ খিচিয়ে বলল, 'কেন রে শালা! এখন কেন! তখন তো আমাদের পোঙায় খুব কাঠি দিয়েছিলি। তখন মনে ছিল না? যা ভাগ! দু-বছরের মধ্যে যেন এ তল্লাটে আর না দেখি!' রবিন ভাইও শাসিয়ে এলো, 'দেখব শালা তুমিও কেম্নে মেলা করো। আমি কাউন্টার মেলা ডাকব! হুঁ!' মহাপরিচালক চোখমুখ লাল করে বলল, 'যা যা ফকড়েমি করিসনে! তোদের মত দু পয়সার প্রকাশক আমি 'টুট' দিয়েও গুণি না!' পরদিন হৈ হৈ রৈ রৈ মার মার কাট কাট! মিছিল-সমাবেশ-সেপাই-পল্টন-লাঠি-কাঁদানে গ্যাস, একেবারে ধুন্ধুমার কাণ্ড! প্রকাশকরা সব বেঁকে বসল, বাংলা একাডেমী বারান্দায়ও আর কেউ যায় না। অগত্যা বাংলা একাডেমী বলল, 'বইপত্তরের কাজই বন্ধ। এখন থেকে আমরা বাংলা মদের লাইসেন্স দেব।' আমি খবর পেয়েই কাগেয়াপটি থেকে উড়ে এসে জুড়ে বসে একটা লাইসেন্স নিয়ে নিলাম। শালারা মোটা টাকা খেয়েছে জানো! সব জায়গায় জোচ্চুরি! ব্যাস্! এই হলো আমার নতুন ব্যাবসার গল্প! লাগবে নাকি তোমার? তোমার জন্য কনসেশন আছে।" আমি ভাবছি, এইবেলা কাক্কেশ্বরকে দু লিটারের অর্ডার দেব। খাটের তলায় লুকিয়ে রেখে সন্ধেবেলাটায় বেশ কদিন একটু মৌতাত হবে! বাংলা একাডেমী অনুমোদিত বাংলা বলে কথা! এমন সময়! কে যেন পিছন থেকে ঝুঁটি ধরে টানতে লাগল। শুনলাম মায়ের গলা, "এই ভর সন্ধেবেলায় কেমন ঘুমুচ্ছে দেখ! এমন আটকুঁড়ে ঊনপাঁজুরে ছেলে আমি জম্মে দেখিনি বাপু! কোনো কাজেকম্মে নেই, কেবল পড়ে পড়ে ঘুমোনো! হাড়মাস জ্বালিয়ে খেলো একেবারে! ওঠ হতচ্ছাড়া! ওঠ বলছি!" বুকের মধ্যে তখন বেজে চলেছে-- "আমি দাম দিয়ে কিনেছি বাংলা কারোর দানে পাওয়া নয়...." <img src="/images/bottle2.png" style="border-radius: 0 !important; width: 200px !important; text-align: center;"> <file_sep>/js/common.js $(window).scroll(function() { if ($(this).scrollTop() >= 50) { $('#return-to-top').fadeIn(200); } else { $('#return-to-top').fadeOut(200); } }); $('#return-to-top').click(function() { $('body,html').animate({ scrollTop : 0 }, 500); }); function fancyFootnote(element) { notenum = 0; $(element).each(function(){ $(this).find(".footnotes").find("[id^='fn:']").each(function() { $(this).find(".reversefootnote").each(function () { $(this).remove(); }); var note = document.createElement("div"); did = $(this).attr("id").split(":")[1]; notename = "fnote" + "-" + notenum + "-" + did; note.id = notename; note.className = "fnote"; note.innerHTML = '<div class="note-wrapper">' + $(this).html() + '</div>'; $("body").append(note); $(this).hide(); }); $(this).find("[id^='fnref:']").each(function(){ fid = "fnote" + ":" + notenum + "-" + $(this).attr('id').split(":")[1]; $(this).attr('id', fid); $(this).html('<i class="fa fa-asterisk"></i>'); $(this).click(function(){ f = "fnote-" + $(this).attr('id').split(":")[1]; shownote(f); }); }); notenum += 1; }); }; function shownote(f) { $(".fnote").removeClass("shownote"); $("#" + f).addClass("shownote"); }; $(document).mouseup(function (e){ var container = $(".fnote"); if (!container.is(e.target) && container.has(e.target).length === 0) { container.removeClass("shownote"); } }); <file_sep>/_posts/2017-10-09-aamruli-shaak.markdown --- title: আমরুলি শাক date: 2017-10-09 11:30:00 +06:00 tags: - রসনাবিলাস - অম্বল fimage: "/images/আমরুলি-২.jpg" --- জন্মের সময় বাপ-মা নাম রেখেছিল পঞ্চানন। শিবঠাকুরের নামে। আজ কেউ ডাকে পঁচা কেউ পাঁইচো কেউবা পেঁচা। এইই হয়। লোকে যা ডাকবে তাতেই নাম-পরিচয়। এ বেচারীরও একসময় সংস্কৃত ভাষায় নাম ছিল অম্ললোনী। এখন তার ডাকনাম আমরুল বা আমরুলি। বড়ো মনোহর দেখতে (এবং স্বাদে)। তার গুষ্টিগোত্রের তত্ত্বতালাশ পণ্ডিতরা করেছেন, আমি সেদিকে যাব না। আমার কেবল খাই-খাই স্বভাব, আমি অতএব সে পথেই যাব। <div class="row"> <div class="col-md-12" style="padding: 30px;background: rgba(0, 0, 0, 0.26);border-radius: 4px;"> <div class="row"> <a href="/images/আমরুলি-১.jpg" data-toggle="lightbox" data-title="সপুষ্প আমরুলি" data-footer="ফুল্ল অম্ললোনী। বৈজ্ঞানিক নাম&nbsp <i>Oxalis corniculata</i>।" data-gallery="আমরুলি" class="col-sm-6" style="padding:10px;"> <img src="/images/আমরুলি-১.jpg" class="img-fluid"> </a> <a href="/images/আমরুলি-২.jpg" data-toggle="lightbox" data-title="আমরুলির পাতা" data-footer="আমরুলির পাতা। এই পাতা আর কচি ডগাটুকুই খেতে সবচেয়ে ভাল। ছোটবেলায় মুঠো-মুঠো কচি আমরুলি তুলে নিয়ে ধুলোমাটিসুদ্ধোই ছাগলের মত চিবোতাম।" data-gallery="আমরুলি" class="col-sm-6" style="padding:10px;"> <img src="/images/আমরুলি-২.jpg" class="img-fluid"> </a> </div> <div class="row"> <a href="/images/আমরুলি-৩.jpg" data-toggle="lightbox" data-title="আমরুলির ফল" data-footer="ফলগুলো দেখতে ক্ষুদ্রকায় ঢেঁড়ষের মত। তিতকুটে স্বাদ। এই ফল বেছে ফেলে না দিলে অম্বল তেতো হয়ে যাবে। ফলঅলা শাক না আনাই বরং ভাল। ওদের বংশবৃদ্ধির জন্য ক্ষমাঘেন্না করে দেয়া উচিত।" data-gallery="আমরুলি" class="col-sm-6" style="padding:10px;"> <img src="/images/আমরুলি-৩.jpg" class="img-fluid"> </a> <a href="/images/আমরুলি-৪.jpg" data-toggle="lightbox" data-title="(আবারও) আমরুলির ফল" data-footer="আবার ফল। বড়ই পাজি বস্তু। তাই দুবার করে চিনিয়ে দিলাম।" data-gallery="আমরুলি" class="col-sm-6" style="padding:10px;"> <img src="/images/আমরুলি-৪.jpg" class="img-fluid"> </a> </div> <p style="text-align:right;color: black;margin-bottom: 0;"><small>* বড় করে দেখতে হলে ছবিতে টোকা দিন</small></p> </div> </div> <br> দিনকতক মুখে রুচি নেই। আমার রুচি বড় ঘন-ঘন বিগড়োয়। তাই নিত্যনতুন খাদ্যখাবারের তালাশ করতে হয়। অবশ্য, আমি সে তালাশ থোড়াই করি, আমার জননী পাখির মায়ের মত এটা-ওটা খুঁটে-বেছে এনে খাইয়ে-দাইয়ে আমাকে বাঁচিয়ে রেখেছেন। আজ ভোরে দেখি কোত্থেকে এক মুঠো আমরুলি শাক তুলে এনেছেন। তাই দিয়ে শুকনো-শুকনো অম্বল রাঁধা হবে। শুকনো লঙ্কা পোড়া ডলে সেই অম্বল দিয়ে চারটি ভাত মেখে খেলে এক ঠ্যাং চিতেয় তোলা লোকেরও আরো দশটা বছর বাঁচতে ইচ্ছে করবে। তা, এ হেন আমরুলি শাকের জুড়িদার মাছ নেই ঘরে। ছোট চিংড়ি নিদেনপক্ষে লাগে। ভাল হয় গলদা চিংড়ির মাথার ঘিলু হলে। গায়ে জামাটা চড়িয়ে তড়িঘড়ি বেরুলাম। দেখি, যদি কপালে থাকে! বাজারে গিয়ে বুঝলাম, পুলকের আতিশয্যে একটু বেশি সকাল-সকালই বাজারে চলে এসেছি। এখনো মেছোরা সব এসে পারে নি। বাজারে এক ছোট ভাই পরামর্শ দিলো, "মোস্তর মোড়ে চলে যান ভাই, ওখানে পাবেনই।" ছুটলাম মোস্তর মোড়ে। সেখানেও ঢু ঢু। বিফল মনোরথ হয়ে বয়রা বাজারে এসে আবার ঘোরাঘুরি করছি। যদি আসে, যদি আসে! মাছের ঝাঁকা নিয়ে কেউ ঢুকলেই ছুটে যাচ্ছি। কিন্তু বিধি বাম, ইঁচের মুড়োর কোনো পাত্তা নেই। শেষে মন্দের ভালো হিসেবে আধসের (সের তো না, কেজি) ছটফটানো নদীর চিংড়ি কিনে ফেললাম। আমাদের এই রূপসা-ভৈরবের চিংড়ি। বড়ই মিষ্টি। ঠিক সেই সময়!-- এক ছোকরা ঢুকলো এক ঝাঁকা ইঁচের মুড়ো ওরফে চিংড়ি মাছের মাথা নিয়ে। রাগে আমার হাত-পা ছুঁড়ে কাঁদার মতন অবস্থা। একটু ধাতস্থ হয়ে কিনে ফেললাম তাও আধসের। তার পরের গল্প আর বলা ঠিক হবে না। শুধু এইটুকু বলি, দুনিয়াতে কিছু খাবার গাপুস-গুপুস খেয়ে শেষ করে ফেলতে ইচ্ছে করে। আর কিছু খাবার আছে, তা অনন্তকাল বাংলায় যাকে বলে 'আস্বাদন' করতে ইচ্ছে করে। আমরুলি সেই জাতের চিজ।<file_sep>/_posts/2015-05-16-কদলীপুষ্প-ও-গাছপাঁঠা.markdown --- title: কদলীপুষ্প ও গাছপাঁঠা date: 2015-05-16 00:00:00 Z tags: - রসনাবিলাস - খাদ্যপুষ্প - এঁচোড় layout: post comments: true --- হাঁসফাঁস লাগছে। বাড়িঅলার ব্যাটার বউ মোচার ঘণ্ট রেঁধে দিয়ে গিয়েছিলো। খেয়েই বুঝলাম দয়া কলার মোচা! সর্বপ্রকার মোচার মধ্যে দয়াকলার মোচাই সবচেয়ে সুস্বাদু। এর পরেই আছে কাঁঠালি কলা, ঠোঁটে কলা আর জিন কলার মোচা। তবে কাঁচকলার মোচাটা বিচ্ছিরি। তিতকুটে। আর যাই হোক শ্রীমতির রান্নার হাতটি বেড়ে। মোচাটা জমিয়েছেন ভালো। তবে স্নেহটা (মানে তেলটা) একটু বেশি পড়ে যায়, এই যা (কাঁচা বয়েস, তা তো একটু পড়তেই পারে)। তবে কালে কালে বড় শিল্পী হবেন তাতে কোনও সন্দেহ নেই। খানিকটা এঁচোড় ছিল ঘরে। চিংড়ি দিয়ে কষা হবে বলে রাখা। ও মা! এক রাতের মধ্যে দেখি পেকেটেকে হলদে হয়ে গেছে! তার কোষগুলো ফেলে দিয়ে শুধু বিচিগুলো আলু দিয়ে একটা দম মত হয়েছে। সাথে ডাঁটা দিয়ে মটরের ডাল। শেষে অম্বল। আমের। এখানেই শেষ নয়। সব কিছুর সাথে সেই মৌরলা মাছ আর চিংড়ি ডুবো তেলো পাঁপড়ের মত করে ভেজে তোলা। কামড় দিয়ে খাওয়ার জন্য। আহা! কোথায় স্বর্গ, কোথায় নরক, কে বলে তা বহুদূর? শেষে সর্বরসের নির্যাসসমৃদ্ধ সুরুয়াটুকু এক চুমুকে সাবাড় করে টলতে টলতে উঠে দাঁড়ালাম। একেই বলে 'উকুন মারা খাওয়া'‒ পেটে উকুন রেখে চাপ দিলে পটাস করে ফেটে যাবে। <file_sep>/_posts/2018-11-24-words-from-mujica.markdown --- title: মুজিকার আত্মকথন date: 2018-11-24 00:53:00 +06:00 tags: - অনুবাদ - অনুলিখন --- <a href="/uploads/jose-mujika.jpg" data-toggle="lightbox" data-gallery="Mujica" data-title="হোসে আলবার্তো 'পেপে' মুজিকা কর্ডানো"><img class="img-fluid" src="/uploads/jose-mujika.jpg" style="float:none; width: 100%; height: auto;" alt="হোসে আলবার্তো 'পেপে' মুজিকা কর্ডানো"></a><small>\[হোসে মুজিকা। উরুগুয়ের রাষ্ট্রপতি ছিলেন ২০১৫ সাল পর্যন্ত। তাঁকে বলা হয় বিশ্বের সবচেয়ে বিনম্র রাষ্ট্রপ্রধান। আবার একটা গোষ্ঠী তাঁকে বিশ্বের দরিদ্রতম রাষ্ট্রপ্রধানও বলে। ষাটের দশকে তিনি টুপামারো গেরিলা আন্দোলনে যুক্ত ছিলেন। অনেক পরে নির্বাচনের মাধ্যমে ক্ষমতায় আসেন। মুজিকা প্রকৃতিঘনিষ্ঠ সরল জীবনযাপনের পক্ষে। সাম্য ও সমতার পক্ষে। এই লেখাটি মূলত 'হিউম্যান দ্যা মুভি' নামক একটা প্রামাণ্যচিত্রে মুজিকার কিছু বক্তব্যের অনুলিখন। তিনি খুব সহজ ভাষায় তাঁর জীবনদর্শনটি বলে গেছেন এখানে।\]<small> আমি হোসে মুজিকা। জীবনের শুরুর দিনগুলোতে আমি মাঠে কাজ করেছি কৃষক হিসেবে, রুটিরুজির জন্য। তারপর আমি নিজেকে উৎসর্গ করেছি দিনবদলের সংগ্রামে, আমার সমাজের মানুষের জীবন উন্নত করার জন্য। আজ আমি রাষ্ট্রপতি। এবং আগামিকাল, আর সকলের মতই পোকার স্তুপে পরিণত হবো এবং অদৃশ্য হয়ে যাবো। আমার জীবনে অনেক প্রতিবন্ধ ছিল, অনেক আঘাত; কিছু বছর কাটিয়েছি জেলে। সে যা হোক… যারা দুনিয়াটা বদলাতে চায়, এগুলো তাদের স্বাভাবিক জীবনচক্রের অংশ। আশ্চর্য হলো, আমি এখনো টিকে আছি এবং সবচেয়ে বড় কথা, আমি জীবন ভালবাসি। আমি চাই আমার জীবনের শেষ যাত্রাটি এমন হোক, যেন একটা লোক, যে কিনা কোনো পানশালায় গিয়ে সাকীকে (পানীয় পরিবেশক) বলছে, “এই দফা হোক আমার উদ্দেশ্যে।” আমি এরকম বেয়াড়া, কারণ আমার মূল্যবোধ ও জীবনচর্চা সমাজের সেইসব মানুষের প্রতিফলন যাদের সাথে থাকতে আমি সম্মান বোধ করি-- এবং আমি তাদের সাথেই থাকি। রাষ্ট্রপতি হওয়াটা কোনো বড় কথা না। আমি এ নিয়ে অনেক ভেবেছি। জীবনে আমি প্রায় দশ বছর একলা কাটিয়েছি, একটা গর্তের মধ্যে। চিন্তা করার অনেকটা সময়.. সাতটা বছর কাটিয়েছি কোনো বইপত্র ছাড়া। ফলে, আমি চিন্তা করার সময় পেয়েছি। আমি ভেবে ভেবে যা বের করেছি তার সারকথা হলো- হয় তুমি সমস্ত অহেতুক বোঁচকা-গাট্টি থেকে মুক্ত হয়ে খুব অল্পে সন্তুষ্ট হবে, কারণ তোমার সুখ তোমার মাথার মধ্যে; নয়তো তুমি কোথাও সন্তুষ্টি পাবে না। আমি দারিদ্র্যের সাফাই গাইছি না, ভব্যতার পক্ষে বলছি। যবে থেকে আমরা একটি ভোগবাদী সমাজ উদ্ভাবন করেছি, তবে থেকে অর্থনীতিটা আকারে বাড়ছে। দুঃখের বিষয় হলো, এর গুণগত বৃদ্ধিটা হচ্ছে না। আমরা আজগুবি সব চাহিদার বিরাট এক পর্বত আবিষ্কার করেছি-- দৈনিক নতুন নতুন জিনিস কেনো আর পুরোনোগুলো ফেলে দাও… এটা স্রেফ আমাদের জীবনের অপচয়! আমি যখন একটা কিছু কিনি বা তুমি যখন একটা কিছু কেনো, তখন কেবল টাকা দিয়েই তুমি তার দাম শোধ করো না, শোধ করো জীবন দিয়ে। কেননা, ওই টাকাটা তোমাকে জীবন ক্ষয় করেই আয় করতে হয়। একটা পার্থক্য বোঝা দরকার, জীবন হলো সেই জিনিস, যা টাকা হলেই কেনা যায় না। এটা কেবলই ছোট হতে থাকে। কারো জীবন ও স্বাধীনতা এইভাবে খরচা করে ফেলা খুবই দুঃখের ব্যাপার। উরুগুয়ে একটা ছোট্ট দেশ। রাষ্ট্রপতির একটা আলাদা বিমান পর্যন্ত আমাদের নেই। আসলে, তাতে আমাদের থোড়াই কেয়ার। ফ্রান্স থেকে আমরা একটা খুবই দামি হেলিকপ্টার কেনার সিদ্ধান্ত নিয়েছি, সার্জিকাল সুযোগসুবিধাসম্পন্ন একটা উদ্ধারকারী হেলিকপ্টার; প্রত্যন্ত অঞ্চলে সেবা দেয়ার জন্য। রাষ্ট্রপতির বিমানের পরিবর্তে আমরা একটা উদ্ধারকারী হেলিকপ্টার কিনতে চাই যেটাকে মধ্য-উরুগুয়েতে নিয়োগ করা হবে দুর্ঘটনায় পতিত মানুষদের উদ্ধার করার জন্য এবং জরুরী চিকিৎসাসেবা দেবার জন্য। এটা খুবই সোজা ব্যাপার। তোমার কি এ নিয়ে দ্বিধা আছে? রাষ্ট্রপতির বিমান বনাম উদ্ধারকারী হেলিকপ্টার। বিষয়গুলো এরকমই। আমার যেটা মনে হয়, ভব্যতার বিষয়টাই সবচেয়ে গুরুত্বপূর্ণ। আমি বলছি না যে আমাদের সেই গুহাবাসীদের যুগে ফেরত যেতে হবে বা খড়ের ঘরে বসবাস করা লাগবে, একদমই তা বলছি না। ভাবনাটা মোটেও সেরকম না। যেটা আমি জোর দিয়ে বলতে চাই, আমাদের অবশ্যই অদরকারি জিনিসে, ধরো বিরাট এক বিলাসবহুল বাড়ি যা দেখাশোনা করতে ছয়জন চাকরবাকর লাগে, সে সবে সম্পদ অপব্যবহার বন্ধ করতে হবে। কী হবে এসবে? কী হবে! এগুলোর কিছুই খুব দরকারি না। আমরা অনেক সহজভাবে বাঁচতে পারি। আমরা আমাদের সম্পদ সেই সবে ব্যবহার করতে পারি যা সবার দরকার। এটাই হলো গণতন্ত্রের আসল মানে, যে মানেটা রাজনীতিকরা হারিয়ে ফেলেছেন। কারণ, রাজীনীতির মানে যদি হয় রাজমুকুট, সামন্তযুগের জমিদারের মত, কর্তা যখন শিকারে যাবেন, চারপাশে ভাঁড়ের দল তখন বাঁশি বাজাবে-- ভাবনাটা যদি এমনই হয়, তাহলে এত বিদ্রোহ-বিপ্লবের কী দরকার ছিল? থাকতাম পড়ে আমরা সেই আগেকার যুগে! সমতার নাম করে তারপরে এইসব রাষ্ট্রপতির বিলাসবহুল প্রাসাদ ইত্যাদি, এগুলো ওই রাজা-জমিদারগিরিরই নতুন চেহারা। জার্মানিতে তারা আমাকে ২৫টা বিএমডব্লিউ মটরসাইকেল দিয়ে এসকর্ট করে এক মার্সিডিস বেঞ্জে চড়িয়ে নিয়ে চলল, বর্মের বহরে সে গাড়ির দরজার ওজন তিন টন-- কী মানে আছে এসবের? (হা হা হা এটা একটা গল্প মাত্র)। আমি একটা নরমসরম মানুষ, যা সামনে আসে নিতে পারি, মানিয়ে নিতে পারি, কিন্তু তবুও… আমি যেরকম ভাবি, আমাকে সেটা বলতেই হবে। আদত সমস্যাটা সম্পদের না, সমস্যাটা রাজনীতির। সরকারগুলো পরের নির্বাচনে জেতা নিয়ে ব্যস্ত থাকে, কে মাতব্বর হবে তাই নিয়ে ব্যস্ত থাকে। আমরা ক্ষমতার জন্য লড়াই করি... (নীরবতা) কিন্তু ভুলে যাই মানুষ আর পৃথিবীর সমস্যাগুলো। সমস্যাটা পরিবেশের না! সমস্যাটা রাজনীতির। আমরা সভ্যতার এমন একটা পর্যায়ে এসে পৌঁছেছি, এখন আমাদের একটা বিশ্বব্যাপী ঐক্য দরকার। আর আমরা সেটা থেকেই মুখ ফিরিয়ে আছি। আমাদের প্রদর্শনবাদ আমাদের অন্ধ করে ফেলেছে, প্রতিপত্তির পিপাসা আমাদের অন্ধ করে ফেলেছে, বিশেষ করে শক্তিমান দেশগুলোকে। তাদের অবশ্যই একটা উদাহরণ তৈরি করতে হবে। এটা খুবই লজ্জার যে কিয়োটো প্রোটোকলের ২৫ বছর পরেও আমরা কেবল তার প্রাথমিক মাপকাঠি নিয়েই ব্যস্ত আছি। এটা খুবই লজ্জার! মানুষ হয়তো একমাত্র প্রাণী যারা নিজেদের ধ্বংস করে ফেলতে সক্ষম। এই উভয়সংকটই এখন আমাদের সামনে। আমার কেবল একটাই আশা, আমি যেন ভুল হই। মানুষের চরিত্র এমনভাবে তৈরি যে মানুষ আরাম-আয়েশের জীবনের চেয়ে দুর্দশার জীবন থেকেই ভাল শিক্ষা নিতে পারে। এর মানে এই না যে আমি একটা দুঃখদুর্দশার জীবন সন্ধান করা পরামর্শ দিচ্ছি, বা সেরকম কোনোকিছু, কিন্তু আমি মানুষকে যেটা বোঝাতে চাই: তুমি সবসময় আবার উঠে দাঁড়াতে পার। জীবন যে কোনো সময় আবার শূন্য থেকে শুরু হতে পারে। একবার, কিম্বা হাজারবার, যতদিন তুমি বেঁচে থাকবে। সেটাই জীবনের সবচেয়ে বড় শিক্ষা। অন্যকথায়, ততক্ষণ পর্যন্ত তুমি হারতে পারো না, যতক্ষণ পর্যন্ত না তুমি তোমার লড়াই ছেড়ে দিচ্ছ। তুমি লড়াই ছাড়ছো মানে তুমি তোমার স্বপ্নও ছুঁড়ে ফেলে দিচ্ছ। লড়াই, স্বপ্ন, পড়ে যাওয়া, বাস্তবতাকে মোকাবেলা করা-- এটাই আমাদের অস্তিত্বকে, যে জীবন আমরা যাপন করি তাকে অর্থবহ করে তোলে। সারাক্ষণ অতীত ক্ষতের তোয়াজ করে জীবন চলতে পারে না। একই বৃত্তে ঘুরে ঘুরে জীবন চলতে পারে না। জীবনে যে দুঃখ পেয়েছি, তা কোনোদিনই সবটুকু উপশম হবে না। সেটা কেউ ফিরিয়ে নিতে পারবে না। তোমাকে শিখতে হবে নিজের দুঃখ-ক্ষত পোঁটলা বেঁধে সামনে এগিয়ে যেতে হয় কীভাবে। আমি যদি সারাটা সময় নিজের ক্ষত নিয়ে আহা-উহুই করতে থাকি, তাহলে তো আমার আর এগোনো হবে না। আমি জীবনটাকে দেখি একটা রাস্তার মতন, যেমন করে সেটা সামনে পড়ে আছে, তেমনই। কেবল আগামিকালটাই আসল কথা। আমাকে সবাই বলে, সাবধান করে, একটা পুরোনো প্রবাদ ব’লে-- ‘তুমি নিশ্চয়ই অতীতকে মনে রাখবে, নয়তো তুমি একই ভুল বারবার করবে।’ আরে ভাই, আমি মানুষকে জানি! মানুষ হলো সেই প্রাণী, যা একই পাথরে চৌদ্দবার ঠোক্কর খায়। প্রত্যেক প্রজন্ম তার নিজের অভিজ্ঞতা থেকে শেখে, মোটেই তারা আগেকার প্রজন্মের অভিজ্ঞতার কাছে ফেরত যায় না। আমি মানবতাকে কোনো একটা আদর্শের ছাঁচে ফেলতে নারাজ। একজন আরেকজনের অভিজ্ঞতা থেকে কীইবা শিখতে পারে? আমরা প্রত্যেকে যে অভিজ্ঞতার মধ্য দিয়ে যাই, আমরা তা থেকেই শিখি। \(হেসে\) এই হলো জীবন নিয়ে আমার ভাবনা। আমি কোনোরকম কোনো প্রতিশোধ চাই না।<file_sep>/_posts/2015-12-05-joyojatra.markdown --- title: জয়যাত্রা date: 2015-12-05 06:00:00 +06:00 tags: - তিক্তকথা comments: true layout: post --- গণতন্ত্র!!! গণতন্ত্রের আগে চাই প্রবৃদ্ধি। উন্নয়ন। দেশের মানুষকে আরো পরিশ্রমী ও কষ্টসহিষ্ণু হতে হবে। তৈরি পোষাক শিল্পে কিছু দুষ্কৃতি মাঝে মাঝে ঝামেলা করে। এদের দমন করতে হবে। তা না হলে বিশ্বে দেশের ভাবমূর্তি খারাপ হয়ে যাবে। শ্রমিকরা কষ্ট করছেন সে কথা সত্যি। কিন্তু তাদের কষ্ট বৃথা নয়। তারা উন্নয়নে ভূমিকা রাখছেন। তারা আমাদের গর্ব। তাদের জন্য বিশ্বব্যাপী আমাদের ভাবমূর্তি উজ্জ্বল হচ্ছে। নিজেদের একটু কষ্টভোগের চেয়ে দেশের ভাবমূর্তি অবশ্যই দামী। প্রতিবারের মত এবারও ধানের বাম্পার ফলন হয়েছে। কৃষক অবশ্য ধানের দাম ভাল পান নি, বাজারেও চালের দাম চড়াই আছে; কিন্তু তাতে কী! দেশ খাদ্যে স্বয়ংসম্পূর্ণ। কিছু ইনডিয়ান চাল আমদানি হয়েছে... আহা, দেশের ব্যবসায়ীদের স্বার্থটাও তো দেখতে হবে! সবচেয়ে বড় কথা, আমরা চাল রপ্তানি করছি! খুবই গর্বের বিষয়! চাল এখন শুধু আমাদের খাদ্যশষ্য মাত্র নয়, তা এখন রীতিমত অর্থকরী ফসল। দুষ্কৃতিদের কথায় কান দেবেন না। কৃষকরা আমাদের অন্নদাতা, ভগবান। তারা দেশের জন্য প্রয়োজনে প্রাণ বিসর্জন দিতে পারেন। সেইজন্যেই কবি বলেছেন, "সব সাধকের বড় সাধক আমার দেশের চাষা।" আহা! কী ভাষা! খাসা! দেশে এখনো বিদ্যুতের চরম ঘাটতি। পরমাণু শক্তিচালিত আধুনিক বিদ্যুৎকেন্দ্র দেশে তৈরি হবে। কী আনন্দের কথা। 'পারমাণবিক' শব্দটার মধ্যেই একটা থ্রিল আছে! একধরনের ঝুঁকিও আছে, কিন্তু উন্নয়নের খাতিরে সে ঝুঁকি জনগণকে মেনে নিতে হবে। সুন্দরবনের উপকণ্ঠে কয়লাভিত্তিক বিশাল বিদ্যুৎকেন্দ্র হবে। দুষ্কৃতিরা পরিবেশ রক্ষার অজুহাতে তা বন্ধ করার ষড়যন্ত্র করছে। আরে, দেশে উন্নয়ন না হলে সুন্দরবন ধুয়ে পানি খাবে পাবলিক? দেশ দুদ্দাড় বেগে এগিয়ে চলেছে ডিজিটাল বাংলাদেশের দিকে। তথ্য-প্রযুক্তির ব্যবহারে পূর্ণ নিয়ন্ত্রণ প্রতিষ্ঠায় সরকার বদ্ধপরিকর। কোনো দুষ্কৃতিই সরকারের চোখ ফাঁকি দিয়ে কিছুই করতে পারবে না। হুঁ হুঁ একটা প্রেমপত্রও লিখতে পারবে না। একেই বলে, "দেখিয়াছ ঘুঘু, দেখনাই তার ফাঁদ!" উন্নয়নের বিরুদ্ধে সকল কণ্ঠ, সকল ষড়যন্ত্র দৃঢ়বলে রোধ করা হবে। উন্নয়নের মহাশকট অপ্রতিরোধ্য গতিতে এগিয়ে যাবে। ক্ষুধা, দারিদ্র্য, অশিক্ষা কোনোকিছুই তার গতি রোধ করতে পারবে না। জয় হোক উন্নয়নের। <file_sep>/_posts/2015-05-06-ডুমুর.markdown --- title: ডুমুর date: 2015-05-06 00:00:00 Z tags: - রসনাবিলাস layout: post comments: true --- কদিন ধরেই মনটা আনচান করছিল। এ গরমকালটা বড্ড বেরসিক। মাছ তো খাওয়া যাবে না। বোশেখ মাস। এখন মাছ খেলে সারাবছর খাবো কী! তরিতরকারিও সুলভ নয়। পেটে চরা পড়ে যাবার কায়দা। জিহ্বা আড়ষ্ট হয়ে আসে। মুখের কথায় মিষ্টতা যায় কমে। এহেন নাজুক অবস্থায় যার জন্য পেট চুঁই চুুঁই করছিল, সে বস্তু আবার সেরদরে বাজারে মেলে না। ক্বচিৎ-কদাচিৎ মেলে। সেদিন স্নেহপ্রতিম স্যাঙাৎ রনির বাড়ি গিয়ে চোখ আটকে গেল সে জিনিসের দিকে। রনি একগাল হেসে বললো, “পৌঁছে যাবে।” কাল সকালে দেখি বাড়ি বয়ে এসে দিয়ে গেছে আমার ভাইটি। ডুমুর। বাঙাল মুলুকে দুই ধরণের ডুমুর আমার চেনা। একটি হলো জগডুমুর। জগ এসেছে যজ্ঞ থেকে। যজ্ঞকর্মে এ গাছের ডাল লাগে। তাই এরকম নাম। এ ডুমুরগুলো আকারে বেশ বড় বড় হয়। খেতেও মন্দ নয়। তবে সবাই খায় না। আর হলো সাধারণ পাতি ডুমুর। এটিই এদেশে বহুল প্রচলিত ও জনপ্রিয়। খুবই সুস্বাদু ও উপাদেয় বস্তু। ডালের সাথে চাক চাক করে ডুবো তেলে ভাজা ডুমুরের মত জিনিস খুব কমই আছে। আজকে রান্না হয়েছিল মাঝারি আকারের চিংড়ি সহযোগে। এ বিরস বৈশাখে বহুদিন পর রসনা তৃপ্ত হলো খানিকটা। উদরও। <file_sep>/_posts/2014-09-10-মান-মানে-কচু.markdown --- title: মান মানে কচু…. date: 2014-09-10 00:00:00 Z tags: - রসনাবিলাস - কচুতত্ত্ব layout: post comments: true --- বরাবরই কচু জাতীয় খাদ্য-খাবার আমার খুব প্রিয়। ওল, মানকচু, দুধ-মানকচু, মুখিকচু, ঘটকচু, পানিকচু, গুড়িকচু (শাক), বিষকচু, কচুর বই (লতি), কচুর ফুল, ওলের ডাঁটা‒ কোনকিছুতেই আপত্তি নেই। কচুর কন্দ অর্থাৎ শর্করাবহুল মূলের মত সুস্বাদু খাবার দুনিয়াতে খুব কমই আছে। তার সাথে অবশ্য মাছ লাগবে জুতসই। বড় শোল, শিং, বাইন, তারা বাইন, মিষ্টি পানির ট্যাংরা, ইলিশ, পার্শে, চাকা চিংড়ি, হরিণে চিংড়ি‒ এগুলোর একটা হলেই চলবে। আর লাগবে ঝাঁঝালো কাঁচাঝাল ও উৎকৃষ্ট একখণ্ড চইঝাল। যাবতীয় কচুশাকে মাছের মাথা‒ ভালো হয় ইলিশের মাথা হলে; অথবা কুঁচো চিংড়ি অথবা খলসে-চুঁচড়ো অথবা চান্দা-চুঁচড়ো অথবা টাকি মাছ লাগবে। কচুর ফুল নারকেল কোরা আর চিংড়ি মাছ দিয়ে ভাজি করলে সেদিন আর অন্য কিছু দিয়ে ভাত খাওয়া আমার পক্ষে প্রায় অসম্ভব হয়ে পড়ে। মানকচু ও মানকচুর কচি পাতা দুটোরই ভর্তা অতি সু্স্বাদু। মানকচুর আরও একটি পদ আমাদের গ্রামের দিকে প্রচলিত। মানকচুর শেষের দিককার অংশ সাধারণত অপেক্ষাকৃত কম সেদ্ধ হয়। সেই অংশটুকু ফেলে না দিয়ে শুকিয়ে গুঁড়ো করে রাখা হয়। তাই দিয়ে যেকোনো মাছ সহযোগে রান্না ঘ্যাঁট অতি অপূর্ব বস্তু। ভর্তা খাওয়ার আরও দুটি অসাধারণ উপকরণ হলো ঘাটকোল ও বিষকচুর মাঝখানের কচি, মোড়ানো পাতা। ঘাটকোল চিংড়ি বা ক্ষুদে কাঁকড়া দিয়ে ভর্তা করলেই বেশি ভালো লাগে। বিষকচুর পাতা খেতে হয় কাঁচা- সর্ষে, প্রচুর কাঁচাঝাল ও নারকেল দিয়ে বেঁটে। আজ আমার মা ওল রান্না করেছিলেন চাকা চিংড়ি দিয়ে। বলা বাহুল্য কব্জি ডুবিয়ে খেয়েছি। খুব কাছের দু-একজনকে গরীবখানায় ওলের সালুন দিয়ে চাট্টি ভাত খেতে ডেকেছিলাম। দুঃখের বিষয় তারা কেউ আসেননি। তারা কী বস্তু মিস করেছেন তার সাক্ষ্য দেবেন [আকবর ভাই](https://www.facebook.com/wriddha "আকবর ভাই")। <file_sep>/_posts/2014-05-23-প্যাটভরে-আড্ডা.markdown --- title: প্যাটভরে আড্ডা date: 2014-05-23 00:00:00 Z tags: - বকরবকর layout: post comments: true --- [মেহেদী ভাইর](https://www.facebook.com/Hasan.Mehedi "হাসান মেহেদী") ভাষায় 'প্যাটভরে আড্ডা'। সেটি আসলে কী বস্তু তার অভিজ্ঞতানির্ভর একটা বর্ণনা দিই। আড্ডা আমরা হররোজই দিয়ে থাকি। কিন্তু এ আড্ডা সবসময় জমে না। অনেক তিথি-নক্ষত্র-স্থান-কাল-পাত্র একত্র হলে তবেই এ আড্ডা জমে। সোজা কথায়, গ্যালন গ্যালন চা আর কার্টুন কার্টুন সিগারেটে উদর ও ফুসফুস উভয়ই যখন পূর্ণ হয় (এবং যখন ভাত, তরিতরকারী ইত্যাদি পুষ্টিকর খাবারের খিদের বারোটা বেজে যায়), তখন তাকে বলে 'প্যাটভরে আড্ডা'। থুক্কু, একটা জিনিস বাদ পড়েছে। শুধু উদর ও ফুসফুসই নয়, মস্তিস্কও পূর্ণ হতে হতে প্রায় অকার্যকর অবস্থায় চলে যায়। উদাহরণ দিয়ে বলি। এইরকম এক রোঁদ আড্ডা আজ জমেছিল আমাদের চায়ের ঠেকে। পূর্ণকালীন সদস্য মোটে তিনজন। আড্ডার মোট দাম কুল্লে আশি টাকা। কী আলাপ হয় নি এ আড্ডায়! লাল চা দিয়ে শুরু। এমন লাল চা দো-জাহানে আর কোথায় পাওয়া যেতে পারে তা নিয়ে একদফা আলোচনা হলো। সেই সূত্রে এলো দার্জিলিং। আমার ইচ্ছে ছিল দার্জিলিং হয়ে শিলিগুড়ি ঢুকে ভারতবিভাগ নিয়ে গতদিনের মুলতুবি আলোচনাটা শেষ করা। কিন্তু সেটা কীভাবে যেন শান্তিনিকেতনে চলে গেলো। [মিঠু ভাই](https://www.facebook.com/KOBITAFANGAS "খৈয়াম মণ্ডল") (শান্তিনিকেতনী পিস) এর জন্য দায়ী। শান্তিনিকেতন থেকে মুজতবা আলী। তারপর আড্ডা আর পিছন ফিরে তাকায় নি। বহু বাঘ-সিংহ-রাজা-উজির বধ করা হলো। সক্রেটিস থেকে রবীন্দ্রনাথ, বহু এলেমদার মহা মহা ওস্তাদকে প্লানচেটে নামানো হলো বারকতক। ফুকো-দেরিদা-চমস্কির চতুর্দশ পুরুষ উদ্ধার হলো। ম্যায়, খুলনা শহরের কোন ব্যক্তির (পুং) সাথে কোন ব্যাক্তির (স্ত্রী) সম্পর্ক আদতে কীরকম তা নিয়ে নানা অজানা রোমহর্ষক তথ্য পরিবেশিত হলো। এইপ্রকারে পেট, ফুসফুস ও মস্তিষ্ক বহুবিধ অম্ল, ক্ষারক ও অপিচ বস্তুতে পরিপূর্ণ হওয়ার পর দেখা গেলো গতদিনের জের সহ এই প্যাটভরা আড্ডার মূল্য সাকুল্যে আশি টাকা! আড্ডা যুগ যুগ জিও! <file_sep>/_posts/2016-07-25-jibon-jokhon-shukaye-jay.markdown --- title: জীবন যখন শুকায়ে যায়... date: 2016-07-25 06:00:00 +06:00 tags: - রসনাবিলাস - শাকতত্ত্ব - অম্বল comments: true fimage: "/images/তেলাকুচ.JPG" layout: post --- <a href="/images/তেলাকুচ.JPG" data-toggle="lightbox" data-title="তেলাকুচ&nbsp <i>Coccinia grandis</i>"><img class="img-fluid" src="/images/তেলাকুচ.JPG" alt="তেলাকুচ Coccinia grandis"/></a>দুপুরবেলায় খেয়েদেয়ে একটা পাতলা ঝিম্ মত এসেছে। ঝিমের মধ্যে একচোখ বুজে আরেক চোখ আদ্ধেক বুজে ভাবছিলাম... "কী দুনিয়া, কী হয়ে গেল! মানবজাতির ভবিষ্যৎটাই বা কী? এত যুদ্ধ, এত রক্তপাত, এত হানাহানি!" ভাবছিলাম, "কেন বেঁচে আছি! মরে গেলেই বা ক্ষতি কী!" কিন্তু মরার কথা ভাবতেই পেটের মধ্যে কেমন পাক দিয়ে উঠল। সদ্য খাওয়া তেলাকুচের লতা আর পার্শে মাছ যেন একযোগে মিছিল শুরু করে দিল! "মানি না, মানব না!" এই হলো জ্বালা! মরা দূরস্থান, মরার কথা ভাবতে গেলেই আমার পেট কুঁই কুঁই করে ওঠে। আহা! এত বিচিত্র খাদ্যসম্ভার ত্যাগ করে ঠুস করে মরে যেতে হবে ভাবলেই ডাক ছেড়ে কাঁদতে ইচ্ছে করে। স্বর্গ বলুন, নরক বলুন, পদ্মার অববাবহিকায় জন্ম নেয়া এই অজস্র শাকলতা আর স্বাদুপানি ও লোনাপানির সঙ্গমে জন্ম নেয়া এই বিচিত্র মৎসকূল ছেড়ে ফুটুস করে মরেটরে যাওয়া একদমই কাজের কথা না। তেলাকুচ বস্তুটা অদ্ভূত। ঠিক তিতে না। কিন্তু একটা আঘ্রাণ আছে দারুণ। কচি ডাঁটাগুলো মুখে পুরে যতক্ষণ খুশি চিবোনো যায়। বড়ই আরাম। শুনেছি কী সব নাকি ঔষধি গুণাগুণ আছে, ডায়াবেটিস-ফায়াবেটিস নাকি সারে-টারে। তা হোক গে। আমার ও নিয়ে আগ্রহ নেই। খেতে ভাল, সেটাই আসল কথা। আমিষ বা নিরামিষ, সবরকমেই ভাল লাগে। নিরামিষ রাঁধলে কতকটা সুক্ত রাঁধার কায়দায় রাঁধতে হয়। আর মাছ হলে তো কথাই নেই! একটু মাখোমাখো ঝোল হবে। তোফা! আজকে মা সেই বস্তু রেঁধেছিলেন। তেলাকুচে শাক, কাঁচকলা, আলু আর পার্শে মাছের ঝোল। তার সাথে কেওড়ার অম্বল। বাদাবনের ফল। বেজায় টক। কিন্তু অম্বলটি বড় ভাল। সর্ষে ফোড়ন দিয়ে জলটক। খেয়ে অব্দি কেমন নেশা নেশা লাগছে। এই আধাচোখও আর খুলে রাখতে পারছি না। যাই আরেকটু ঝিমিয়ে নিই... <file_sep>/_posts/2015-05-17-নটেশাক.markdown --- title: নটে শাক date: 2015-05-17 00:00:00 Z tags: - রসনাবিলাস - শাকতত্ত্ব layout: post comments: true --- আমার কথাটি ফুরোলো, নটে গাছটি মুড়োলো। সব গল্পের শেষে ওই এককথা। মাকে একদিন গল্পের শেষে জিগ্যেস করলাম, "নটে গাছ কী গো মা?" মা হেসে বললো, "কাল দেখাব।" পরদিন দেখি কোত্থেকে যেন একঝুড়ি শাকপাতা খুঁটে এনেছে। তার থেকে একটা তুলে বললো, "এ হলো নটেশাক।" আজো পষ্ট মনে আছে, সেই নটেশাক ভেজে এক চামচ ঘি দিয়ে মেখে ভাত খাইয়ে দিয়েছিল মা। সে সোয়াদ আমি এখনো ভুলতে পারি না। এরপর নটেশাক আরো অজস্রবার খেয়েছি। কিন্তু সেই অমৃততুল্য স্বাদ আজ আবার পেলাম। নটেশাক ভাজি আর এক চামচ আচারের তেল। গুটি আমের আচার। কী মধুর, কী মমতাময় মোলায়েম সে আস্বাদ! তাকে জিহ্বা দিয়ে গ্রহণ করা চলে না, গ্রহণ করতে হয় হৃদয় দিয়ে। অন্ত্রের পাচক রসে তা জীর্ণ হয় না, তাকে জীর্ণ করতে হয় অন্তরের জারক রসে। তার মূল্য কেবল পুষ্টিতে নয়, তার আসল মূল্য তুষ্টিতে। <file_sep>/404.html --- title: মগ্ন(৪০৪) permalink: "/404.html" layout: page --- <p>এখানে দেখার কিছু নাই। কেবলই চিন্তামগ্নতার আবর্জনা! <a href="{{ site.url }}">চিন্তার পৃষ্ঠতলে</a> যাও। <file_sep>/_posts/2016-02-23-মোদের-গরব-মোদের-আশা‌.markdown --- title: মোদের গরব মোদের আশা date: 2016-02-23 00:00:00 Z tags: - তিক্তকথা layout: post comments: true --- আমার দেশ নিয়ে একধরণের গর্ব আমার আছে। আমার দেশটি সুন্দর। অন্তত, সেইরকম ভাবতে আমি অভ্যস্ত। শৈশব থেকে দেশের বর্ণনায় নানা প্রাকৃতিক সৌন্দর্যের কথা বলা হয়েছে। আমি তার কতক দেখেছি, কতক কল্পনা করে নিয়েছি। সুন্দরের সান্নিধ্যে একরকম গর্ববোধ হয়, যেমন গর্ববোধ হয় সুন্দর বন্ধু বা বন্ধুনীটি পাশে থাকলে। আমার দেশের ইতিহাস আমাকে গর্বিত করে। সে ইতিহাস সংগ্রামের। যখন বাংলাদেশ নামে কোনো দেশের কথা কেউ কল্পনাও করেনি, সেই সুদূর অতীত থেকে এই ভূখণ্ডের মানুষের লড়াই আমাকে মুগ্ধ করে। আমি সবচেয়ে মুগ্ধ হই আমার ভাষায়। অসীম শক্তিধর সংজননশীল একটি ভাষা। এ ভাষা একদিন বিশ্বজয় করবে তাতে আমার কোনো সন্দেহ নেই। আমার ভাষার জন্য আমি গর্ববোধ করি। আমি গর্ব করি এই ভাষায় রচিত সাহিত্যের জন্য। এই ভাষার কবিরা পৃথিবীর শ্রেষ্ঠ কবিদের কাতারে। এতজন শ্রেষ্ঠ কবি একটি ভাষায় না থাকলেও চলে। একটি ভাষার কবিতায় একজন রবীন্দ্রনাথ আর একজন জীবনানন্দই যথেষ্ঠ। আমি গর্ব করি বাংলার গান নিয়ে। গর্ব কবি জয়নুল আর সুলতানকে নিয়ে। গর্ব করি জগদীশ বসু আর প্রফুল্লচন্দ্রকে নিয়ে। গর্ব করি তেভাগার শহীদদের নিয়ে। গর্ব করি রফিক-সালাম-বরকতকে নিয়ে। গর্ব করি মোস্তফা-বাবুল-ওয়াজিউল্লাহকে নিয়ে। গর্ব করি আসাদকে নিয়ে, তিরিশ লাখ শহীদকে নিয়ে। গর্ব করি মতিউল-কাদেরকে নিয়ে। গর্ব করি নূর হোসেনকে নিয়ে, জাফর-জয়নাল-দীপালি-কাঞ্চনকে নিয়ে। আমার গর্বের শেষ নেই এই দেশ নিয়ে। তবু, মাঝে মাঝে একটা শীতল স্রোত আমার মেরুদণ্ডের মজ্জার ভিতর দিয়ে প্রবাহিত হয়। আমি ভীত, সন্ত্রস্ত ও অসহায় বোধ করি। একদল বাঙালি সেটেলার শূকরবৎস দাঁত উঁচিয়ে পাক হানাদারের মত ছুটে যাচ্ছে অরণ্য ও পাহাড় ভেদ করে। হত্যা করছে, আগুন লাগাচ্ছে, লুটপাট করছে। আমারই মত কোনো বাঙালি পিতার বীর্যে কোনো বাঙালি মায়ের গর্ভে তাদের জন্ম। তারা আমারই ভাই, বন্ধু, স্বজন। তারা আমার লজ্জা। আমার এত যে গর্ব, তার সমস্ত দিয়ে এই লজ্জা আমি ঢাকতে পারব তো?! <file_sep>/_posts/2017-11-09-ণত্ব-ষত্ব-বত্ব.markdown --- title: ণত্ব ষত্ব বত্ব date: 2017-11-09 06:00:00 +06:00 tags: - ভাষা - ব্যাকরণ - উচ্চারণ layout: post comments: true --- অধুনা বাঙলা ভাষার বৈয়াকরণরা আমাদের সাংঘাতিক কয়েকটি ভুল তথ্য দিয়েছেন এতকাল। আমি ভাষা বিষয়ে বিষয়ীও না, অধিকারীও না। কিন্তু, ভাষাটা যেহেতু আমার, এবং যেহেতু আমি সেটা ব্যবহার করি, সেহেতু এর ব্যবহারিক অসঙ্গতি আমার চোখে বিলক্ষণ পড়ে। বাঙলাভাষী হিসেবে সে সব নিয়ে যদি কথা বলি, নিশ্চয়ই মহাজনদের আপত্তি করার কারণ নেই। পয়লা, ন-এর কথায় আসি। বাঙলা ভাষায় তিনটি ন আছে। তালব্য ন বা 'ঞ', মূর্ধন্য ন বা 'ণ' ও দন্ত ন বা 'ন'। হিসেবটা আসলে খুবই সোজা। তালব্য বর্ণের সাথে তালব্য ন , মূর্ধন্য বর্ণের সাথে মূর্ধন্য ন ও দন্ত্য বর্ণের সাথে দন্ত্য ন বসবে। একইভাবে, তিনটি স আছে, যাদের বলে শিস ধ্বনি। তারাও ওইরকম যথাক্রমে বসে। কেন বসে? কারণটা খুবই সোজা, ওইরকম বসা ছাড়া তাদের আর উপায় নেই। সে কথায় আসছি একটু পরে। নতুন মহাজনেরা বলেন যে মূর্ধন্য ণ-এর ও মূর্ধন্য ষ-এর উচ্চারণ নাকি বাঙলা ভাষা থেকে লুপ্ত। এটি সর্বৈব ভুল। কথাটি চোখ বুজে এতকাল বিশ্বাস করেছি বলে ধরতে পারি নি। একদিন হঠাৎই পরিষ্কার হয়ে গেল। মূর্ধন্য ধ্বনি হলো সেইগুলো, যেগুলো মূর্ধা বা পশ্চাৎদন্তমূলে জিহ্বা উল্টে স্পর্শ করে উচ্চারণ করতে হয়। যথা- ট, ঠ, ড, ঢ, ণ, ষ প্রভৃতি। নিয়মটা হলো মূর্ধন্য বর্ণের সাথে সঙ্গত কারণেই মূর্ধন্য ণ বা ষ উচ্চারিত হবে। ফারাকটা এখনি আপনি টের পাবেন। উচ্চারণ করুন, দন্ত এবং দন্ড। দেখুন, দন্ত শব্দে ন উচ্চারণের সময় জিভ কোথায় থাকে আর দণ্ড শব্দে ণ উচ্চারণের সময় জিভ কোথায় থাকে। জিভ না উল্টিয়ে আপনি কোনোভাবেই দণ্ড বলতে পারবেন না, তা 'দন্দ' হয়ে যাবে। এবার দন্ত উচ্চারণ করতে গিয়ে দন্ পর্যন্ত বলে থামুন, ন-এর উচ্চারণ ধরে রাখুন। মগজে নোট নিন। আবার, দণ্ড উচ্চারণ করতে গিয়ে দণ্ পর্যন্ত বলে থামুন। মগজে নোট নিন। শ্রুতির পার্থক্যটাও ধরতে পারছেন কী? খুবই সহজ ব্যাপার। এবারে, একইভাবে অস্ত ও অষ্ট শব্দ দুটি উচ্চারণ করুন। ভাল করে খেয়াল করুন। উচ্চারণের স্থান আলাদা, ধ্বনির ফারাকটাও বুঝতে পারবেন। আপনি তবু যদি জোর করে অষ্ট শব্দটি অস্ট হিসেবে উচ্চারণ করতে যান, তবে ট আর ট থাকবে না, ট ও ত-এর মাঝামাঝি চলে যাবে। আদিতে ণ-এর উচ্চারণ ছিল খানিকটা ড়ঁ-এর মত। যদি বিষ্ণু শব্দটি ষ-এর যথাযথ উচ্চারণ বজায় রেখে করতে যান, তবে ণ-এর শুদ্ধ রূপটি পাবেন। কিন্তু তেমন উচ্চারণ আমরা আজকাল করি না, তার দরকারও নেই। এখন আমরা বলি- বিশ্ঞু। ণ ও ষ এর উচ্চারণ তার আদি অবস্থা থেকে সরেছে বটে, কিন্তু একেবারে বিলুপ্ত মোটেও হয়নি। এমনকি, বিদেশি কোনো ভাষাতেও আপনি তালব্য বা দন্ত্য বর্ণের সাথে মূর্ধন্য ণ যুক্ত করে উচ্চারণ করতে পারবেন না। বিশ্বাস না হয় Fund শব্দটি উচ্চারণ করে দেখুন, জিভ ওল্টায় কিনা! >ৱ—ইহা একোনত্রিংশ ব্যঞ্জনবর্ণ এবং শেষ অন্তঃস্থ বর্ণ। [ ব-কার উচ্চারণ করিতে হইলে অধরোষ্ঠের আভ্যন্তর ও বাহ্য ভাগদ্বয় দ্বারা উত্তরদন্তাগ্র, অর্থাৎ ঊর্দ্ধ্বদন্তপঙ্‌ক্তির অগ্রভাগ স্পর্শ করিতে হয়, অতএব ব-কারের উচ্চারণে অধরোষ্ঠের আভ্যন্তর ও বাহ্য ভাগদ্বয় করণ এবং উত্তরদন্তাগ্র স্থান ( তৈ ২.৪৩ )। 'ৱকারস্য দন্তোষ্ঠম্' পা ১.১.৯, সি। দ্র 'বর্গীয় ব১, য১। ] >—বঙ্গীয় শব্দকোষ, হরিচরণ বন্দ্যোপাধ্যায়। আমার আরো একটি আপত্তি হলো অন্তস্থ ব বর্ণের বিলুপ্তি নিয়ে। এই বর্ণটি আমরা ছোটবেলায় আদর্শলিপিতে পড়েছি। য, র, ল এর পরে এটি থাকত। পরে বড় ক্লাসে উঠে জানলাম, এর উচ্চারণ বাঙলাভাষায় আর নেই। তাই এটিকে তুলে দেয়া হয়েছে বাঙলা বর্ণমালা থেকে। কিন্তু পরে আরেকটি বিষয় খেয়াল করে দেখতেই এ বর্ণটির অভাব অনুভব করলাম। ইংরেজি, ফারসি ইত্যাদি থেকে বাঙলায় যদি প্রতিবর্ণীকরণ করতে হয় তখন এ বর্ণটির দরকার আছে বলেই মনে হয়েছে আমার। ইংরেজিতে W-এর প্রকৃত উচ্চারণ আসলে অন্তস্থ ব-এর মতই। উপরের সারির দাঁত ও নিচের ঠোঁট মিলিয়ে করতে হয়। যেমন, wall এর আসল উচ্চারণ হলো ৱোয়াল, ওয়াল নয়। তেমনি, 'ৱকৎ'ও ওয়াক্ত নয়। এরকম আরো অনেক উদাহরণ দেয়া যেতে পারে। আসলে, বিদেশি অনেক ভাষাতেই ওষ্ঠ্য বর্ণগুলোর গুষ্টিসুদ্ধো একটা দন্তোষ্ঠ্য রূপ আছে। বাঙলাভাষা যে কেবল একটি সংজননশীল ভাষা, তা-ই তো নয়, এ ভাষা জাতপাতের বিচার করে দোস্তি করে না। যার কাছে যা পায়, বাবুই পাখির মত নিজের ঘরের মধ্যে এনে গোঁজে। এটা এর বিরাট শক্তিময়তা। আমরা অনেককিছু আমাদের করে নিতে গিয়ে বদলে নিয়েছি অনেককিছু। যে সব বদল হয়েছে মুখে মুখে। স্টেশন ইষ্টিশন হয়েছে, স্কুল ইশকুল হয়েছে। বড় মিষ্টি শোনায় শব্দগুলো। কিন্তু, কোনো শব্দ যদি চায় তার মূল রূপটি নিয়েই আমার ভাষার মধ্যে বসবাস করবে, তার সেই দাবিও সঙ্গত মনে করি। অন্তস্থ ব-এর কল্যাণে সেই দাবির খানিকটা পূরণ হওয়া খুবই সম্ভব ছিল। যে বর্ণটি আমি অন্তস্থ ব লিখতে ব্যবহার করেছি, সেটি ছাড়াও আজকের বর্গীয় ব-এর যে চিহ্ন, তাও অন্তস্থ ব লিখতেই ব্যবহার করা হতো। বর্গীয় ব লেখা হতো পেটকাটা ৰ দিয়ে। এখন পুনরায় বর্গীয় ব এর জন্য পেটকাটা ৰ এর প্রচলন খুবই ঝক্কির। তবে পণ্ডিত ও মহাজনেরা পরামর্শ করে অন্তস্থ ব এর চিহ্ন হিসেবে এটি ব্যবহারের বিধান দিতেই পারেন। কেননা, বর্ণটির যে ব্যবহারিক উপযোগ আছে, তা তো পষ্ট দেখাই যাচ্ছে। যদি উচ্চারণ বিলুপ্ত হওয়াই অন্তস্থ ৱ বর্ণটির বিলুপ্তির কারণ হয়, তবে সেই উচ্চারণের যুক্তিতেই তা আবার বাঙলা বর্ণমালায় ফেরত আসা উচিৎ।<file_sep>/_posts/2015-07-14-রেন্টু-ভাই.markdown --- title: রেন্টু ভাই date: 2015-07-14 00:00:00 Z tags: - স্মরণ layout: post comments: true --- আজ সকাল থেকে একটা লোকের মুখ থেকে থেকে মনে পড়ছে। নামজাদা কেউ নয়। তিনি একজন কবি ছিলেন। এই শহরের এক ঘিঞ্জি এলাকার তস্য গলিতে তাঁর জীবন কেটেছে। হতচ্ছাড়া স্মৃতি আজ তাকেই কেন খুঁড়ে বের করলো কে জানে! আসলে তাঁর লেখা কবিতার একটা লাইন ঝট করে চলে আসল মাথার মধ্যে। তারপর স্মৃতির ম্যাগনেটিক টেপ সাঁই সাঁই করে রিওয়াইন্ড করে একটা জায়গা থেকে আবার চলতে শুরু করল। সালটা ২০০৭। আমি তখন বইমেলার সাথে সদ্য যুক্ত হয়েছি। সাত, আট, নয় তিনটে বছর ফেব্রুয়ারি এলে বইমেলাই ধ্যানজ্ঞান। অনেকের কথাই মনে পড়ে, সক্কলের কথা আপাতত মুলতুবি থাক, অন্যত্র বলা যাবে। রাত বারোটার আগে বাড়ি ফেরা হতো না একদিনও। সারাদিন মেলায় অর্ধভুক্ত-অভুক্ত থেকে খাটাখাটনি আর গেলাস গেলাস চা। আর দিনভর পেটভরে আড্ডা দিয়ে একপেট এসিড নিয়ে মধ্যরাতে বাড়ি ফেরা। সেই ফেরার কয়েকজন সঙ্গী ছিল। কবি মশিরুজ্জামান, বন্ধু সুলতান মাহমুদ রতন, বন্ধু রাসেল মাহমুদ, শ্রাবণ ভাই আর রেন্টু ভাই— মীর আব্দুল জব্বার রেন্টু। এরা আর সকলেই কবি গোত্রের, আমিই একমাত্র অকবি। এদের সকলেই সবদিন থাকতেন না। আমি, মশিরুজ্জামান আর রেন্টু ভাই প্রতিদিনই একসাথে ফেরা হতো। মধ্যরাতে কখনো ফেরার পথে আরো একদফা আড্ডা হতো। মশিরুজ্জামানকে বাড়ি পৌঁছে দিতে আমরা বাকি দুজন হেঁটে যেতাম তাঁর সাথে, আবার আমাদের এগিয়ে দেয়ার ছুতোয় তিনিও ফের উল্টোদিকে হাঁটতেন। তখনই এই রেন্টু ভাইর সাথে অন্তরঙ্গতা বাড়তে থাকে। সারাদিনের কবি মানুষটির ভিতর থেকে আরো একটি মানুষ বেরিয়ে আসত তখন। তার সংসার আছে, সন্তান আছে, সে সংসারে চূড়ান্ত অনটন আছে— মানুষটি ধীরে ধীরে একেবারে নিজের মানুষ হয়ে গেল কখন, ঠিক ঠাহর করতে পারি নি। সেই মধ্যরাতে তাঁর দীর্ঘশ্বাস কানে ধরা পড়তো। নিজেরই একটা কবিতার লাইন বারবার করে বলতেন— আমি পড়ে আছি খুউব দক্ষিণে একা। সেই মানুষটি, সেই কাছের মানুষটি হঠাৎ একদিন দুম করে ট্রেনের মধ্যে হার্ট এটাকে মরে পড়ে থাকল। আর এমনই অধম আমি, সে দিনটিও আজ স্মরণ করতে পারি না। কিন্তু আজ সকালে, কবিতার এই লাইনটি মনে পড়ে, তারে সাথে তাঁর মুখটি মনে পড়ে থেকে থেকে চোখ ছলছল করে উঠছে। একটি পান খাওয়া বকবকে আড্ডাবাজ মুখ মনের মধ্যে জীবন্ত হয়ে উঠছে। কিছু ছেঁড়াখোঁড়া মানুষ, সহজ কিন্তু প্রাণবন্ত তারা আমার আজকের দিনের দৈন্যকে আরো প্রকট করে তুলছে। চারপাশে তাকালে আজ বুঝতে পারি একটি একটি করে মানুষ তাদের জীবনের পসরা গুটিয়ে নিচ্ছে। আমি ক্রমশ এই দক্ষিণে আরো একা হয়ে পড়ছি। যাহোক এই কবি আব্দুল জব্বার রেন্টু, আমাদের রেন্টু ভাই, তাকে কবি বলে খুব একটা মান্যিগণ্যি কোনোদিন করিনি, কিন্তু তিনি আমার বন্ধু ছিলেন, সুজন ছিলে, আমাকে ভালবাসতেন। যে কবিতাটির জন্য আজ সারাদিন আমার এ দুর্ভোগ, সেটি তুলে দিলাম। বন্ধু রতনকে ধন্যবাদ কবিতাটির ছবি তুলে পাঠানোর জন্য (আবারও ভাবি, কী নির্দয় অকৃতজ্ঞ আমি! তাঁর একখানি বই ভালবেসে দিয়েছিলেন আমাকে, হারিয়ে ফেলেছি।) _আমি প'ড়ে আছি খুউব দক্ষিণে একা_ _কোথাও কোনো শব্দ নেই,_ _অথচ কোত্থেকে একঝাঁক বরফ হঠাৎ উড়ে এসে_ _জুড়ে বসে—_ _হয়ে যায় লৌকিক নিসর্গ নান্দিক কবিতা।_ _যেমন সলোমান তাঁর সম্রাজ্ঞী শেবাসহ_ _দরবার সিংহাসন কুরছি নিয়ে উড়ে যান_ _উড়ুক্কু যানে,_ _তেমনি আমার ভেতরে ডোরবেলে কে যেন চাপ দেয়-_ _কে ডাকে এই মধ্যযামে?_ _শরতে সাঁইজির স্পষ্ট আন্ধার ফুঁড়ে_ _ছুটে যায় দ্রুত মনোরেল নগর বিহঙ্গমা;_ _শুধু আমি পড়ে আছি খুউব দক্ষিণে একা_ _নগরের উল্টোপথে আঠারোবেঁকির চর হতে_ _ধবধবে-শাদা-বক শব্দগুলো ডিগবাজি খেয়ে নেমে আসে_ _কবিতার সমগ্র জলজমিনে,_ _এই শরতে বাইজির শাদা-শাদা রূপারাতে_ _হে শরৎনারী, এই অন্ধকার রাতে_ _তোমার পীনোন্নত ব্রা এবং নিতম্ব ছুঁয়ে ছুঁয়ে_ _ভেসে যাচ্ছে কোথায় নিজল শাদা মেঘ প্রেম—_ _কোন সে ডেরায় পরকীয়া সোহেলীর পথে?_ _আর আমি শুধু পড়ে আছি খুউব দক্ষিণে একা_ _একা।_ <file_sep>/js/search.js var options = { // include: ["matches"], shouldSort: true, threshold: 0.6, location: 0, tokenize: true, matchAllTokens: true, distance: 50, maxPatternLength: 50, minMatchCharLength: 1, keys: [ "title", "content", "tags" ] }; var fuse; function processData (data) { fuse = new Fuse(data, options); } (function() { var API = "/search_data.json"; $.getJSON(API) .done(processData); })(); $('#search-box').on('input', function(e) { e.preventDefault(); var result = fuse.search($('#search-box').val()); $("#search-results").empty(); result.map(function (item) { $("#search-results").append("<div class=\"result-item\"><a class=\"result-item-title\" href=\"" + item.url + "\">" + item.title + "</a></div>"); }); // result.map(function (obj) { // var titlestring = obj.item.title; // obj.matches.map(function (match) { // if (match.key == "title") { // } // }); // $("#search-results").append("<div class=\"result-item\"><a class=\"result-item-title\" href=\"" + item.url + "\">" + item.title + "</a></div>"); // }); }); $('#search').submit(function(e) { e.preventDefault(); }); <file_sep>/_posts/2017-10-09-sei-chotttt-bhbghure.markdown --- title: সেই ছোট্ট ভবঘুরে date: 2017-10-09 01:20:00 +06:00 tags: - ফিলিম - চ্যাপলিন fimage: "/uploads/Limelight-poster.jpg" --- <p><a href="/uploads/Limelight-poster.jpg" data-toggle="lightbox" data-gallery="Char<NAME>" data-title="Limelight Poster"><img class="thumbnail img-fluid" src="/uploads/Limelight-poster.jpg" style="float:left;" alt="Limelight Poster"></a>ওস্তাদ যেভাবে লিখেছেন, তেমন লেখা তো আর লিখতে পারব না! আমার ওস্তাদও মজেছিলেন তার রসে। সে কথা যেরকম সরসে বয়ান করেছেন, তেমনটি আর কেউ পারবে বলে আমি বিশ্বাস করি না। তাঁর বিদেহী পদযুগলে হাজারখানেক সেলাম ঠুকে আমি একটুখানি লেখার দুঃসাহস করি। ও হ্যাঁ, আমার ওস্তাদের নাম সৈয়দ মুজতবা আলী (কানে হাত)।</p> ছবির নাম 'লাইমলাইট'। কাহিনী সবিস্তারে বলা ফিলিমরসিকদের রীতিবিরুদ্ধ কাজ (তেমন খ্যাপাটে দর্শক হলে তেড়ে মারতে আসে)। তবে, এ ছবিখানা আমার মতন নাদান আহাম্মুক ছাড়া রসিক লোক সবাই দেখে ফেলেছেন বলেই সন্দ করি। আমার এই উচ্ছাস দেখে মুখ টিপে বা হো হো করে হাসলেও আশ্চর্য হব না। কিন্তু সত্য কথা এই যে, ছবিখানা আমায় দেগেছে ভালরকমেই। বহু-বহু সিনেমা আমি দেখি নি। তাই দুনিয়ার বহু-বহু কলাকারের কাজ আমার অজানা। তবে এই ছোটখাট মানুষটিকে ভালবাসি বড়। রবীন্দ্রনাথের গানে আছে, "জীবন যখন শুকায়ে যায়, করুণাধারায় এসো"। এই ট্রাম্প কমেডির অবতারটি দুনিয়ায় এসেছিলেন হাসিকান্নার বিমিশ্র ধারা হয়ে। হাসতে হাসতে পেটে খিল ধরে যাবার মধ্যেও চোখটা ঝপ করে জলে ঝাপসা হয়ে আসে। <a href="/uploads/025-limelight-theredlist.jpg" data-toggle="lightbox" data-gallery="Charlie Chaplin" data-title="A Scene"><img src="/uploads/025-limelight-theredlist.jpg" alt="A Scene" width="100%" height="auto" class="img-fluid"></a> প্রতুল মুখোপাধ্যায়ের গানটিও সকলেরই শোনা আছে বলে সন্দ হয়। চ্যাপলিনকে নিয়ে অমন গান আমি দ্বিতীয়টি শুনি নি (আবারও কানে হাত দিয়ে স্বীকার করি, গানও আমি দু-চারখানার বেশি শুনি নি)।<br> > সেই ছোট্ট দুটো পা > ঘুরছে দুনিয়া > ছোট্ট দুটো চোখে স্বপ্নের দূরবীন > কাছে যেই আসি > মুখে ফোটে হাসি > তবু কোথায় যেন বাজে > করুণ ভায়োলিন ... এই গানে এক জায়গায় আছে 'লাভ লাভ লাভ লাভ লাভ লাভ লাভ লাভ লাভ লাভ'। এই লাভ-এর রেলগাড়িটা আসলে ওই ছবিরই একটা গানের মধ্যে আচ্ছে। সাংঘাতিক সুন্দর একটা গান। যারা কিনা দিনান্তে একবার সুইসাইড করার কথা ভাবেন, তারা দয়া করে এই গানটি একবার শুনবেন। একটা দিন অন্তত বেশি বাঁচতে ইচ্ছে হবে, আমার মুর্শিদের কসম! <a href="/uploads/Limelight-Claire-Bloom-and-Charlie-Chaplin.jpg" data-toggle="lightbox" data-gallery="Charlie Chaplin" data-title="Claire Bloom and Charlie Chaplin"><img src="/uploads/Limelight-Claire-Bloom-and-Charlie-Chaplin.jpg" alt="Claire Bloom and Charlie Chaplin" width="100%" height="auto" class="img-fluid"></a> একজন বিগতযশা ট্রাম্প কমেডিয়ান আর এক হতাশ ব্যালেরিনার কাহিনী 'লাইমলাইট'। ভালবাসার গল্প। জীবনের গল্প। নিরাশা নিরন্ধ্র আন্ধারে জীবনকে ভালবেসে বাঁচার গল্প।<br> > ভালবাসা নাও চার্লস চ্যাপলিন... > ভালবাসা ছড়াও চার্লস চ্যাপলিন > পৃথিবীর বুকে উষর মরুতে ফুল ফোটাও > চার্লস চ্যাপলিন<file_sep>/_posts/2017-10-11-dioscorea-alata.markdown --- title: মেটে আলু date: 2017-10-11 16:20:00 +06:00 tags: - রসনাবিলাস - কন্দতত্ত্ব fimage: "/images/আলুর-বিচি.jpg" comments: true layout: post --- বাঙাল মুলুকে গোল আলুর ইতিহাস খুব বেশিদিনের না। ওলন্দাজরা এনেছিলো গোল আলু। এই তো সেদিন, বিজ্ঞানী জগদীশ বোস রবীন্দ্রনাথকে বললেন যে একটা নতুন তরকারি চাষ করেছেন, খেতে নাকি খুবই ভাল। তারপর রবীন্দ্রনাথও আলু করলেন (সূত্র- প্রথম আলো, সুনীল গঙ্গোপাধ্যায়)। তার আগ অব্দি আলু মানে মেটে আলু। মেটে আলু আমাদের খাঁটি দিশি আলু। এশিয়ার ক্রান্তীয় অঞ্চলে এর উদ্ভব। ক্রান্তীয় অঞ্চল মানে যে সব অঞ্চল দিয়ে কর্কটক্রান্তি (২৩.৫° উত্তর অক্ষরেখা) বা মকরক্রান্তি (২৩.৫° দক্ষিণ অক্ষরেখা) চলে গেছে। আমাদের দেশের ঠিক বুকের উপর দিয়ে গেছে কর্কটক্রান্তি। সে হিসেবে… ধুত্তোরি ছাই! আসল কথা আগে বলে নিই। পেটভরে খেলে মাথা ঠিক থাকে না। ফালতু বকবকানিতে পেয়ে বসে। <div class="row"> <div class="container"> <div class="col-md-12" style="padding: 30px;background: rgba(0, 0, 0, 0.26);border-radius: 4px;"> <div class="col-sm-6" style="float: left;"> <a href="/images/আলু-গাছ.jpg" data-toggle="lightbox" data-title="আলু গাছ" data-footer="<i>Dioscorea alata" data-gallery="মেটে আলু"> <img src="/images/আলু-গাছ.jpg" class="img-fluid" style="padding:10px;"> </a> </div> <div class="col-sm-6" style="float: right;"> <a href="/images/আলুর-বিচি.jpg" data-toggle="lightbox" data-title="আলুর বিচি" data-footer="এটা গাছে ঝুলে থাকে। পুড়িয়ে খেতাম ছোটবেলায়।" data-gallery="মেটে আলু"> <img src="/images/আলুর-বিচি.jpg" class="img-fluid" style="padding:10px;"> </a> <a href="/images/মেটে-আলু.jpg" data-toggle="lightbox" data-title="মেটে আলু" data-gallery="মেটে আলু"> <img src="/images/মেটে-আলু.jpg" class="img-fluid" style="padding:10px;"> </a> </div> <p style="text-align:right;color: black; padding: 10px 30px 10px auto;"><small>&#9733; বড় করে দেখতে হলে ছবিতে টোকা দিন</small></p> </div> </div> </div> আসল কথা হলো, মেটে আলু। মানে, মেটে আলুর ঝোল। মানে, ইলিশ মাছ দিয়ে মেটে আলুর ঝোল। (কেউ মনে করবেন না, আমি এখন ইলিশ মাছ কিনেছি। পয়লা অক্টোবর থেকে ইলিশ ধরা বন্ধ আছে। এ তার আগে কেনা ইলিশ। হুঁ হুঁ, আর যাই করি, মাছের বেলায় আমি আইন ভাঙি না।) আলুটা ছিল মাদাম তুসোর মূর্তির মোমের মত সাদা, মখমলের মত মোলায়েম। তার স্বাদ পুরোপুরি প্রকাশ করা মত ভাষা পৃথিবীতে জন্ম হয় নি। কবি হলে হয়তো তা কোনো এক প্রকারে বলে ফেলতে পারতাম (কবিরা এত কিছু নিয়ে লেখে, কিন্তু শাক-পাতা-আলু-কচু-মাছ নিয়ে কেন লেখে না, খোদা মালুম! এর চেয়ে বড়ো সরেশ বস্তু পৃথিবীতে আর কী আছে! হ্যাঁ, একজনই লিখেছিলেন। সুকুমার রায়। তাঁর খুরে খুরে প্রণাম। আহা! 'খাই খাই করো কেন, এসো বোসো আহারে।' কী উদার আহ্বান!)। কিন্তু, পেটে এটম বোমা ফাটালেও দু লাইন পদ্য বেরোবে না। অতএব, গদ্যেই যত বকবকানি। আবার কথায় কথায় বেপথু হচ্ছি। এই ইলিশ মাছ আর মেটে আলু আর একটু চইঝাল। রামপ্রসাদের সুরের মত সুরুয়া। মুখে দিলে মনের মধ্যে বেজে ওঠে, “মন তুমি কৃষিকাজ জানো না। এমন মানবজমিন রইলো পতিত, আবাদ করলে ফলতো সোনা…"। আহা, ভিটেমাটি নেই, থাকলে কিছু না হোক মেটে আলু আবাদ করে মানবজীবন সার্থক করতাম। সোনা ফলিয়ে কী হবে! সোনা কী খাওয়া যায়? (যে সোনা খাওয়া যায়, সেই সোনার ধানের আবাদীরাও আজ ধনেপ্রাণে মরোমরো। সে গল্প আজ না, অন্যদিন।) আমি বাংলাদেশের খোদ কৃষকের বংশধর। যে কৃষক বারংবার মন্বন্তরের কালে বনবাঁদাড় ঘেঁটে আলু-কচু-শুষনি শাক তুলে এনে খেয়েছে। তাই এইসকল লতা-গুল্ম-কন্দের প্রতি প্রীতি মনে হয় আমার জেনেটিক মেমোরিতে সঞ্চিত আছে। আমাদের বাড়িতে (মানে একদা যেখানে ভিটেমাটি ছিল) দেখেছি মেটে আলু করতে। একটা বড় গাছের পাশে গর্ত খুঁড়ে ছাই-মাটি দিয়ে ভর্তি করে মেটে আলু রুয়ে দেয়া হত। কতরকম বাহারি আলু। কোনটা ধপধপে সাদা, কোনোটা লালচে বেগুনি। কোনোটায় একটু গাল কুটকুট করে। একটা আলু ছিল, তার নাম 'হরিণ শিঙে' মনে হয়। তার কন্দ এদিক ওদিক ছড়িয়ে যায় বহুদুর পর্যন্ত। গোটা আলুটা খুঁড়ে তোলা খুবই মুশকিল হয়। আরেকটা আলুর নাম 'আলতা পাতি'। এর খোসার নিচেটা আলতার মত লাল। আরেকটা আলুর নাম 'বেনার ঝাড়'। আরো কত পদের আলু ছিল! নাম ভুলে গেছি। একবার ঠাকুর্দা একটা আলু তুলতে গিয়ে রীতিমত নাজেহাল হয়েছিলেন। গোটাটা খুঁড়ে বের করা যায় নি, এমনি বিচিত্র পথে মাটির নিচে তার বিস্তার ঘটেছিল। যতটুকু তোলা হয়েছিল, তার ওজন এক মণের বেশি। আলুর গাছে, মানে লতায় ছোটো ছোট আলু ধরে। আমরা বলতাম 'আলুর বিচি'। এই বিচির তরকারি খাওয়া হতো না। এখন কেউ কেউ খায় শুনেছি। 'আলুর বিচি' শীতের 'বিহানে' আগুন পোহানোর সময় নাড়ার আগুনে পুড়িয়ে খেতাম। আহা শৈশব!<a href="/images/Dioscorea_alata8c.jpg" data-toggle="lightbox" data-gallery="মেটে আলু" data-title="মেটে আলু" data-footer="ঠাকুর্দার তোলা আলুটা কতকটা এইরকম ছিল"><img class="thumbnail img-fluid" src="/images/Dioscorea_alata8c.jpg" style="float:right !important;" alt="মেটে আলু"> ইংরেজিতে এই আলুর সাধারন নাম Yam। বিজ্ঞানীরা ডাকেন <i>Dioscorea alata</i> নামে। দক্ষিণ এশিয়া এর জন্মভূমি। কিন্তু, তাইওয়ান, জাপান, চীন, আফ্রিকা, লাতিন আমেরিকাসহ বহু জায়গায় এই আলু খুবই জনপ্রিয়। নানা দেশে কেক, পেস্ট্রি, আইসক্রীম, কুকি ইত্যাদি বাহারি খাবার হয় এই আলু দিয়ে। ফিলিপাইনে একে বলে উবে (Ube)। বেগুনি উবে থেকে তারা বানায় উবে হালেইয়া নামে এক মিষ্টি। হালুয়ার মতই কতকটা। আর বানায় হালো-হালো (Halo-Halo) নামের এক পদের আইসক্রীম জাতীয় চিজ। গুর্জরদেশীয়দের 'উন্ধিয়ু'র অত্যাবশ্যকীয় উপাদান এই মেটে আলু। আমাদের বাঁদাড়ের জংলা আলুর এত কদর কে জানতো! <div class="row"> <div class="col-md-12" style="padding: 30px;background: rgba(0, 0, 0, 0.26);border-radius: 4px;"> <div class="row"> <a href="/images/Ubecupcakes.jpg" data-toggle="lightbox" data-title="মেটে আলুর কাপকেক" data-gallery="মেটে আলু" class="col-sm-6" style="padding:10px;"> <img src="/images/Ubecupcakes.jpg" class="img-fluid"> </a> <a href="/images/ube-haleya.jpg" data-toggle="lightbox" data-title="উবে হালেইয়া" data-footer="বাঙলায় মেটে আলুর হালুয়া বলা যেতে পারে" data-gallery="মেটে আলু" class="col-sm-6" style="padding:10px;"> <img src="/images/ube-haleya.jpg" class="img-fluid"> </a> </div> <div class="row"> <a href="/images/halo-halo.jpg" data-toggle="lightbox" data-title="হালো-হালো" data-footer="আইসক্রীম জাতীয়। আমাদের মেলায় যে 'ঘষা বরফ' পাওয়া যায়, খানিকটা সেইরকম জিনিস।" data-gallery="মেটে আলু" class="col-sm-6" style="padding:10px;"> <img src="/images/halo-halo.jpg" class="img-fluid"> </a> <a href="/images/Undhiyu.jpg" data-toggle="lightbox" data-title="উন্ধিয়ু" data-footer="গুর্জরদেশীয় পদ। শব্দটা এসেছে 'উন্ধু' থেকে। মানে 'উল্টো'। মাটির নিচে একটা উল্টো পাত্রের উপর দিক থেকে তাপ দিয়ে এই বস্তু রান্না করা হয়।" data-gallery="মেটে আলু" class="col-sm-6" style="padding:10px;"> <img src="/images/Undhiyu.jpg" class="img-fluid"> </a> </div> <p style="text-align:right;color: black;margin-bottom: 0;"><small>&#9733; বড় করে দেখতে হলে ছবিতে টোকা দিন</small></p> </div> </div> তা, যে যাই বলুক, আমার এই ইলিশ মাছের সুরুয়াই জবরদস্ত। আর সব তো খাই নি, না খেয়ে ভালমন্দ কেম্নে বলি? এই ঝাঁঝালো ঝোলের গন্ধে যে সুখ, আইসক্রীম-পেস্ট্রিতে কি আর তা পাওয়া যাবে! নাহ্! খাওয়াটা একটু বেশি আঁটো হয়ে গেছে। ঠিকমত হজম হওয়ার জন্য পাতলা একটা ঝিম হওয়া দরকার। বাংলায় যাকে বলে 'ভাতঘুম'।<file_sep>/_posts/2015-04-16-jole-jonmay-jaha.markdown --- title: জলে জন্মায় যাহা date: 2015-04-16 06:00:00 +06:00 tags: - রসনাবিলাস - কচুতত্ত্ব comments: true layout: post --- জীবনে কিছু দায় আছে যা এড়ানো যায় না। আর কিছু আনন্দ আছে যার লোভ ছাড়তে পারি না। সেই জন্যেই বেঁচে থাকি। কালকে বাড়ি ফেরার পথে দেখি মোড়ের মাথায় তরকারির দোকানে দশাসই পানিকচু সব সাজিয়ে রেখেছে। আমাকে যারা চেনেন, তারা জানেন, কচুর প্রতি আমার কিঞ্চিৎ বিশেষ দূর্বলতা আছে। কচুগুলোর যে সাইজ, তা আমার পরিবারের জন্য বাহুল্য। কুল্লে তিনজন মানুষ; তিনজনের খাবার রীতি তিনরকম। অতএব, মাঝারি সাইজের একটা কচু নিয়ে বাড়ি ফিরলাম। সেই কচুর কন্দ আজ সকালে বেগুনের মত চাক-চাক করে পেঁয়াজ দিয়ে ভাজা হয়েছে। আক্ষরিক অর্থেই মাখন যাকে বলে। ভাতের সাথে মিলেমিশে একাকার। ভাত মেখে মুখে দিতেই মুখের মধ্যে যে আরামটা তৈরি হলো তার সাথে কেবল কোমল গান্ধারেরই তুলনা চলে। পণ্ডিতজনেরা মুখ গম্ভীর করে বলেন, মানুষ খাওয়ার জন্য বাঁচে না। আমি বলি, আমি বাঁচার জন্য খাই তো বটেই, খাওয়ার আনন্দেও বেঁচে থাকি। যা হোক, শাকটা এখনো রান্না হয় নি। কাল হবে। রসিকজনের নিমন্ত্রণ রইলো।
0fa8cae7bb5201e36f13eaaa2ceec3470d3dea4f
[ "Markdown", "JavaScript", "HTML" ]
31
Markdown
utsargo/utsargo.github.io
bfd23e5213e37e4dd46d25e6fc499229d9cd08e7
b8ca67c82b0a7b0dba29b4be436e10d7f0007d51
refs/heads/main
<file_sep>import { AccountService } from './../../@app-core/http/account/account.service'; import { SpeechRecognition } from '@ionic-native/speech-recognition/ngx'; import { Component, OnInit, ViewChild, Output, EventEmitter } from '@angular/core'; import { AlertController, Platform } from '@ionic/angular'; @Component({ selector: 'app-support', templateUrl: './support.page.html', styleUrls: ['./support.page.scss'], }) export class SupportPage implements OnInit { @ViewChild('searchBar') searchBar: any; @Output() output = new EventEmitter<string>(); input = ''; hiddenSearchBar = true; supports: any; constructor( private PlatForm: Platform, private speechRecognition: SpeechRecognition, private accountService: AccountService, private alertController: AlertController, ) { } headerCustom = { title: 'Trợ Giúp' }; ngOnInit() { this.accountService.showSupports().subscribe((data) => { this.supports = data.supports; }) } toggleHideSearchBar(value) { this.hiddenSearchBar = value; if (!value) { this.searchBar.setFocus(); } } startVoice() { this.PlatForm.ready().then(() => { this.speechRecognition.requestPermission().then( async () => { await this.startVoiceRecord(); this.searchBar.setFocus(); } ) }) return; } startVoiceRecord() { this.speechRecognition.startListening().subscribe((matches: Array<string>) => { this.input = matches[0]; }) } changeInput(value) { this.output.emit(value); } async openSupport(support) { const alert = await this.alertController.create({ header: support.answer, mode: 'ios', buttons: [ { text: 'Đồng ý', handler: () => { } } ] }); await alert.present(); } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { IonInfiniteScroll, ModalController } from '@ionic/angular'; import { IPageRequest, OrderService } from 'src/app/@app-core/http'; import { LoadingService } from 'src/app/@app-core/utils'; import { ModalDetailOrderPage } from 'src/app/@modular/modal-detail-order/modal-detail-order.page'; @Component({ selector: 'app-notification', templateUrl: './notification.page.html', styleUrls: ['./notification.page.scss'], }) export class NotificationPage implements OnInit { @ViewChild('infiniteScroll') infiniteScroll: IonInfiniteScroll; headerCustom = { title: 'Thông báo' }; orders = []; lastedData: any; requestOrder: IPageRequest = { page: 1, per_page: 100, } constructor(private orderService: OrderService, private modalController: ModalController, private loadingService: LoadingService ) { } ngOnInit() { } ionViewWillEnter() { this.getDataNotifications(); } getDataNotifications(func?) { this.orderService.getAll(this.requestOrder).subscribe(data => { // this.orders = this.orders.concat(data.orders); for(let i = 11; i >= 1; i--) { this.orders.push({ id: i, status: 'chua xem', created_at: 29-i + '-04-2021' }) } this.orders.length; func && func(); this.requestOrder.page++; // if (this.orders.length >= data.meta.pagination.total_objects) { // this.infiniteScroll.disabled = true; this.orders.sort((a, b) => { var a_time = new Date(a.created_at); var b_time = new Date(b.created_at); return b_time.getTime() - a_time.getTime() //}) }) }) } loadMoreData(event) { this.getDataNotifications(() => { event.target.complete(); }) } async openOrderDetailModal(notify) { this.loadingService.present(); const modal = await this.modalController.create({ component: ModalDetailOrderPage, cssClass: 'event-detail-modal', swipeToClose: true, componentProps: { id: notify.id } }); modal.present(); modal.onWillDismiss().then(() => { this.reset(); }) } reset() { this.orders = []; this.requestOrder.page = 1; this.getDataNotifications(); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { AlertController, ModalController } from '@ionic/angular'; import { DonateService, OrderService } from '../@app-core/http'; import { LoadingService, ToastService } from '../@app-core/utils'; import { PaymentupComponent } from '../@modular/paymentup/paymentup.component'; import { InAppBrowser } from '@ionic-native/in-app-browser/ngx'; @Component({ selector: 'app-paymentmethods', templateUrl: './paymentmethods.page.html', styleUrls: ['./paymentmethods.page.scss'], }) export class PaymentmethodsPage implements OnInit { dataParam: any; payment; headerCustom = { title: 'Phương thức thanh toán', background: '#fff' } constructor( private route: ActivatedRoute, private router: Router, public modalController: ModalController, private alert: AlertController, private orderService: OrderService, private loading: LoadingService, private iab: InAppBrowser, private donateService: DonateService, private toart: ToastService, ) { } ngOnInit() { let url = window.location.href; if (url.includes('?')) { this.route.queryParams.subscribe(params => { this.dataParam = JSON.parse(params['data']); }) } } async openModal() { const modal = await this.modalController.create({ component: PaymentupComponent, swipeToClose: true, cssClass: 'modal__payment' }); await modal.present(); } async presentAlertMoMo(header: string, text: string) { const alert = await this.alert.create({ mode: 'ios', header: header, message: text, buttons: [ { text: 'Hủy', role: 'cancel', cssClass: 'secondary', handler: () => { } }, { text: 'Tiếp tục', handler: () => { const browser = this.iab.create(this.payment.pay_url, '_system', 'location=yes'); } } ] }); await alert.present(); } goMomo() { if (this.dataParam.type_page == 'order') { const orderParam = { order_payment: { "app_link": "no link", "order_id": this.dataParam.order_id, } } this.loading.present(); this.orderService.paymentOrder_Momo(orderParam).subscribe((data) => { this.openMomoPopUp(); }, () => { this.loading.dismiss(); this.toart.presentSuccess('Hãy thử lại sau') }) } else if(this.dataParam.type_page == 'pray') { this.dataParam.pray_log["app_link"] ="no link"; this.loading.present(); this.dataParam.pray_log.payment_type = 'momo'; this.donateService.prayByMoMo(this.dataParam).subscribe((data) => { this.payment = data; this.openMomoPopUp(); }, () => { this.loading.dismiss(); this.toart.presentSuccess('Hãy thử lại sau'); }) } else if(this.dataParam.type_page == 'donate'){ this.dataParam.donation["app_link"] ="no link"; this.loading.present(); this.dataParam.donation.payment_type = 'momo'; this.donateService.donateByMoMo(this.dataParam).subscribe((data) => { this.payment = data; this.openMomoPopUp(); }, () => { this.loading.dismiss(); this.toart.presentSuccess('Hãy thử lại sau'); }) } } openMomoPopUp() { this.loading.dismiss(); this.presentAlertMoMo('Thông báo', 'Bắt đầu thanh toán qua momo'); } } <file_sep>import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class PageNotiService { private data: BehaviorSubject<IDataNoti> = new BehaviorSubject<IDataNoti>({ title: '', des: '', routerLink: '' }); constructor() { } public get dataStatusNoti(): Observable<IDataNoti> { return this.data.asObservable(); } public setdataStatusNoti(value: IDataNoti) { this.data.next(value); } } export interface IDataNoti { title: string; des: string; routerLink: string; } export interface IDataSlide { title: string; image: string; label: string; routerLink: string; }<file_sep>import { ToastService } from 'src/app/@app-core/utils'; import { Injectable } from "@angular/core"; import { Network } from "@ionic-native/network"; import { AlertController, Platform } from "@ionic/angular"; import { BehaviorSubject } from "rxjs"; @Injectable() export class NetworkService { public connected: BehaviorSubject<boolean> = new BehaviorSubject(true); private subscribedToNetworkStatus: boolean = false; private network = Network; constructor( private toastService: ToastService, private platform: Platform, private alertController: AlertController,) { } isConnected: any; setSubscriptions() { if (this.isConnected == 'disconnected') { this.networkConfirm(); } if (!this.subscribedToNetworkStatus && this.platform.is('cordova')) { this.subscribedToNetworkStatus = true; this.network.onChange().subscribe((val) => { this.isConnected = val.toString(); this.showAlert(); }); this.network.onDisconnect().subscribe(() => { this.connected.next(false); }); } } showAlert() { if (this.isConnected == 'connected') { // this.toastService.presentSuccess('Đã kết nối!'); } } async networkConfirm() { const alert = await this.alertController.create({ cssClass: 'my-custom-class', header: 'Vui lòng kiểm tra lại kết nối mạng!', mode: 'ios', buttons: [ { text: 'Thử lại', handler: () => { location.reload(); } } ] }); await alert.present(); } }<file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { ModalController, AlertController } from '@ionic/angular'; import { OrderService } from 'src/app/@app-core/http'; import { DateTimeService, LoadingService } from 'src/app/@app-core/utils'; import { IDataNoti, PageNotiService } from 'src/app/@modular/page-noti/page-noti.service'; @Component({ selector: 'app-checkout', templateUrl: './checkout.page.html', styleUrls: ['./checkout.page.scss'], }) export class CheckoutPage implements OnInit { headerCustom = { title: 'Kiểm tra đơn hàng' }; cart = []; address = ''; shipCost = 5000; paymentMethod; phone; order_id: any; constructor( public dateTimeService: DateTimeService, private route: ActivatedRoute, private orderService: OrderService, private modalCtrl: ModalController, private pageNotiService: PageNotiService, private router: Router, private alertController: AlertController, private loadingService: LoadingService ) { } ngOnInit() { this.getCart(); this.phone = localStorage.getItem('phone_temp'); this.route.queryParams.subscribe(params => { this.paymentMethod = JSON.parse(params['data']).paymentMethod; }).unsubscribe(); } getCart() { this.cart = JSON.parse(localStorage.getItem('cart')) || []; this.address = localStorage.getItem('address'); } calPrice(item) { return item.amount * item.price; } calTotalPrice() { return this.cart.reduce((acc, item) => acc + this.calPrice(item), 0); } ionViewWillLeave() { this.modalCtrl.dismiss(); } confirm() { this.loadingService.present(); const req = { order: { lat: localStorage.getItem('lat'), lng: localStorage.getItem('lng'), note: localStorage.getItem('note'), full_address: this.address, parish_id: localStorage.getItem('tempParishId'), phone_number_receiver: localStorage.getItem('phone_temp'), order_details_attributes: this.cart.map(item => ({ product_id: item.id, amount: item.amount })) } } if (this.paymentMethod.id == 0) { this.orderService.create(req).subscribe((data: any) => { this.order_id = data.order.id; this.paymentByCash(); this.loadingService.dismiss(); }) } else { this.orderService.create(req).subscribe( (data: any) => { this.order_id = data.order.id; this.alertSuccess(); this.modalCtrl.dismiss(); this.loadingService.dismiss(); }, () => { this.loadingService.dismiss(); } ) } localStorage.removeItem('lat'); localStorage.removeItem('lng'); localStorage.removeItem('cart'); localStorage.removeItem('phone_temp'); localStorage.removeItem('note'); } paymentByCash() { var orderByCash = { order_payment: { "order_id": this.order_id } } const datapasing: IDataNoti = { title: 'THÀNH CÔNG!', des: 'Đơn hàng đặt thành công!', routerLink: '/main/chabad' } this.orderService.paymentOrder_Cash(orderByCash).subscribe((data) => { this.pageNotiService.setdataStatusNoti(datapasing); this.router.navigateByUrl('/page-noti'); }) } async alertSuccess() { const alert = await this.alertController.create({ cssClass: 'my-custom-class', header: 'Tiếp tục thanh toán', backdropDismiss: false, mode: 'ios', buttons: [ { text: 'Đóng', cssClass: 'secondary', handler: () => { this.router.navigate(['/main']) } }, { text: 'Tiếp tục', handler: () => { const data = { order_id: this.order_id, type_page: 'order', token: '', } this.continute(data); } } ] }); await alert.present(); } continute(data) { this.router.navigate(['paymentmethods'], { queryParams: { data: JSON.stringify(data) } }) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { ModalController } from '@ionic/angular'; import { AuthService, IPageRequest } from '../@app-core/http'; import { DioceseService } from '../@app-core/http/diocese'; import { ParishesService } from '../@app-core/http/parishes'; import { IPageParishes } from '../@app-core/http/parishes/parishes.DTO'; import { LoadingService } from '../@app-core/utils'; import { ModalDonateComponent } from '../@modular/modal-donate/modal-donate.component'; @Component({ selector: 'app-dioceses', templateUrl: './dioceses.page.html', styleUrls: ['./dioceses.page.scss'], }) export class DiocesesPage implements OnInit { headerCustom = { title: 'Chọn giáo phận' }; dataDiocese: any = []; canDiocese = true; id; type_page; pageResult: IPageRequest = { page: 1, per_page: 1000, } data; notFound = false; constructor( private modalCtrl: ModalController, private diocesesService: DioceseService, private route: ActivatedRoute, private loadingService: LoadingService ) { } ngOnInit() { this.loadingService.present(); let url = window.location.href; if (url.includes('?')) { this.route.queryParams.subscribe(params => { this.data = JSON.parse(params['data']); this.type_page = this.data.type_page; }); } this.getAll(); } getAll() { this.notFound = false; this.diocesesService.getAll(this.pageResult).subscribe((data: any) => { this.notFound = true; this.loadingService.dismiss() this.dataDiocese = data.dioceses; this.pageResult.total_objects = data.meta.pagination.total_objects || 1; }); } search(value: string) { if (typeof value != 'string') { return; } else if (!value) { delete this.pageResult.search; } else { this.pageResult.search = value; } this.pageResult.page = 1; this.dataDiocese = []; this.getAll(); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { ChooseQuestionPageRoutingModule } from './choose-question-routing.module'; import { ChooseQuestionPage } from './choose-question.page'; import { HeaderModule } from 'src/app/@modular/header/header.module'; import { ChooseQuestionDetailComponent } from './choose-question-detail/choose-question-detail.component'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, ChooseQuestionPageRoutingModule, HeaderModule ], declarations: [ChooseQuestionPage, ChooseQuestionDetailComponent] }) export class ChooseQuestionPageModule { } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { APICONFIG } from '..'; import { map, catchError } from 'rxjs/operators'; import { ModalController } from '@ionic/angular'; import { ToastController } from '@ionic/angular'; import { IPageRequest } from '../global'; import { requestQuery } from '../../utils'; @Injectable() export class OrderService { constructor( private http: HttpClient, private toastController: ToastController ) { } public create(req) { return this.http.post(`${APICONFIG.ORDER.CREATE}`, req).pipe( map((result) => { return result; }), catchError((errorRes: any) => { if(errorRes.error.messages[0]) { this.presentToast(errorRes.error.messages[0]); } else { this.presentToast('Bạn vui lòng kiểm tra lại.') } throw errorRes.error; }) ) } public getAll(request: IPageRequest) { return this.http.get(`${APICONFIG.ORDER.GET_ALL}?${(requestQuery(request))}`).pipe( map((result: any) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } public getDetail(id) { return this.http.get(`${APICONFIG.ORDER.GET_DETAIL(id)}`).pipe( map((result: any) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } public paymentOrder_Visa(request) { return this.http.post(`${APICONFIG.ORDER.PAYMENT_ORDER_VISA}`,request).pipe( map((result: any) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } public paymentOrder_Momo(request) { return this.http.post(`${APICONFIG.ORDER.PAYMENT_ORDER_MOMO}`,request).pipe( map((result: any) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } public paymentOrder_Cash(request) { return this.http.post(`${APICONFIG.ORDER.PAYMENT_ORDER_CASH}`,request).pipe( map((result: any) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } public delete(id: number) { return this.http.delete(`${APICONFIG.ORDER.DELETE(id)}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; })); } async presentToast(mes) { const toast = await this.toastController.create({ mode: 'ios', message: mes, duration: 2000, color: 'warning' }); toast.present(); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { IDataNoti, PageNotiService } from './page-noti.service'; @Component({ selector: 'app-page-noti', templateUrl: './page-noti.component.html', styleUrls: ['./page-noti.component.scss'], }) export class PageNotiComponent implements OnInit { public title = ""; public des = ""; public routerLink = '' constructor( private pageNotiService: PageNotiService, private router: Router ) { } ngOnInit() { this.pageNotiService.dataStatusNoti.subscribe((data: IDataNoti) => { this.title = data.title; this.routerLink = data.routerLink; this.des = data.des; setTimeout(() => { this.router.navigateByUrl(this.routerLink); }, 2000); }) } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { CatechismClassPageRoutingModule } from './catechism-class-routing.module'; import { CatechismClassPage } from './catechism-class.page'; import { HeaderModule } from 'src/app/@modular/header/header.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, CatechismClassPageRoutingModule, HeaderModule ], declarations: [ CatechismClassPage, ] }) export class CatechismClassPageModule {} <file_sep>import { NgModule } from '@angular/core'; import { PreloadAllModules, RouterModule, Routes } from '@angular/router'; import { AuthGuard } from './@app-core/auth-guard.service'; import { } from './changepassword/changepassword.module' const routes: Routes = [ { path: 'auth-manager', loadChildren: () => import('./auth-manager/auth-manager.module').then(m => m.AuthManagerPageModule) }, { path: 'main', loadChildren: () => import('./main/main.module').then(m => m.MainPageModule), canActivate: [AuthGuard], }, { path: 'donate', loadChildren: () => import('./donate/donate.module').then(m => m.DonatePageModule), canActivate: [AuthGuard], }, { path: 'payment', loadChildren: () => import('./payment/payment.module').then(m => m.PaymentPageModule), canActivate: [AuthGuard], }, { path: 'paymentmethods', loadChildren: () => import('./paymentmethods/paymentmethods.module').then(m => m.PaymentmethodsPageModule), canActivate: [AuthGuard], }, { path: 'pray', loadChildren: () => import('./pray/pray.module').then(m => m.PrayPageModule), canActivate: [AuthGuard], }, { path: 'page-noti', loadChildren: () => import('./@modular/page-noti/page-noti-routing.module').then(m => m.PageNotiRoutingModule), canActivate: [AuthGuard], }, { path: 'changepassword', loadChildren: () => import('./changepassword/changepassword.module').then(m => m.ChangepasswordPageModule), canActivate: [AuthGuard], }, { path: 'account', loadChildren: () => import('./account/account.module').then(m => m.AccountPageModule), canActivate: [AuthGuard], }, { path: 'account-setting', loadChildren: () => import('./account-setting/account-setting.module').then(m => m.AccountSettingPageModule), canActivate: [AuthGuard], }, { path: 'slide', loadChildren: () => import('./@modular/slide/slide.module').then(m => m.SlideModule), canActivate: [AuthGuard], }, { path: 'modal-detail-order', loadChildren: () => import('./@modular/modal-detail-order/modal-detail-order.module').then(m => m.ModalDetailOrderPageModule), canActivate: [AuthGuard], }, { path: 'dioceses', loadChildren: () => import('./dioceses/dioceses.module').then(m => m.DiocesesPageModule), canActivate: [AuthGuard], }, { path: 'news', loadChildren: () => import('./@modular/news/news.module').then(m => m.NewsPageModule), canActivate: [AuthGuard], }, { path: 'information', loadChildren: () => import('./@modular/information/information.module').then(m => m.InformationPageModule), canActivate: [AuthGuard], }, { path: 'news-detail', loadChildren: () => import('./@modular/news-detail/news-detail.module').then(m => m.NewsDetailPageModule), canActivate: [AuthGuard], }, { path: 'parishes', loadChildren: () => import('./parishes/parishes.module').then(m => m.ParishesPageModule), canActivate: [AuthGuard], }, { path: 'map', loadChildren: () => import('./@modular/map/map.module').then(m => m.MapPageModule), canActivate: [AuthGuard], }, { path: 'statistic', loadChildren: () => import('./statistic/statistic.module').then(m => m.StatisticPageModule), canActivate: [AuthGuard], }, { path: 'questionares', loadChildren: () => import('./questionares/questionares.module').then(m => m.QuestionaresPageModule), canActivate: [AuthGuard], }, { path: 'community', loadChildren: () => import('./community/community.module').then(m => m.CommunityPageModule), canActivate: [AuthGuard], }, { path: 'calendar', loadChildren: () => import('./calendar/calendar.module').then( m => m.CalendarPageModule), canActivate: [AuthGuard], }, { path: 'store', loadChildren: () => import('./store/store.module').then( m => m.StorePageModule), canActivate: [AuthGuard], }, { path: 'calendar-detail', loadChildren: () => import('./@modular/calendar-detail/calendar-detail.module').then( m => m.CalendarDetailPageModule), canActivate: [AuthGuard], }, { path: 'tabbar-manager', loadChildren: () => import('./tabbar-manager/tabbar-manager.module').then(m => m.TabbarManagerPageModule), canActivate: [AuthGuard] }, { path: '', redirectTo: '/tabbar-manager/main', pathMatch: 'full' }, { path: '**', redirectTo: 'tabbar-manager/main' }, // { // path: 'popup-registe', // loadChildren: () => import('./@modular/popup-registe/popup-registe.module').then( m => m.PopupRegistePageModule) // }, ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }) ], exports: [RouterModule] }) export class AppRoutingModule { }<file_sep>import { Component, OnInit, Input, NgModule } from '@angular/core'; import { ModalController } from '@ionic/angular'; import { OrderService } from 'src/app/@app-core/http'; import { DateTimeService, LoadingService } from 'src/app/@app-core/utils'; import { AlertController } from '@ionic/angular'; @Component({ selector: 'app-modal-detail-order', templateUrl: './modal-detail-order.page.html', styleUrls: ['./modal-detail-order.page.scss'], }) export class ModalDetailOrderPage implements OnInit { @Input() id; setOrderItemId() { localStorage.setItem('orderItemId', this.id); } order = { id: 0, status: '', note: '', full_address: '', phone_number_receiver: '', created_at: '', order_details: [] } loadedData = false; isCanceled = ''; fakeImg = 'https://res.cloudinary.com/baodang359/image/upload/v1616123967/kito-music/MDC319_avatar_bqms50.jpg'; constructor( private orderService: OrderService, private dateTimeService: DateTimeService, public modalController: ModalController, private loadingService: LoadingService, private alertController: AlertController, ) { } ngOnInit() { this.loadingService.present(); this.getData(this.id); } getDayString() { if (this.order.created_at == '') { return ' '; } return this.dateTimeService.DAYS[new Date(this.order.created_at).getDay()].toUpperCase(); } getData(id) { this.orderService.getDetail(id).subscribe(data => { this.order = data.order; this.loadedData = true; if (data.order.status == 'pending') { this.isCanceled = 'Hủy đơn hàng'; } else if (data.order.status == 'failed') { this.isCanceled = 'Đã hủy đơn hàng'; } else if (data.order.status == 'done') { this.isCanceled = 'Đã xác nhận'; } this.loadingService.dismiss(); }) } async reallyWantCancelOrder(id) { const alert = await this.alertController.create({ cssClass: 'my-custom-class', header: 'Xác nhận!', message: 'Bạn chắc chắn muốn <strong>hủy</strong> đơn hàng này?', mode: 'ios', backdropDismiss: true, buttons: [ { text: 'Quay lại', role: 'cancel', cssClass: 'secondary', }, { text: 'Đồng ý', handler: () => { this.cancelOrder(id); } } ] }); await alert.present(); } cancelOrder(id) { this.loadingService.present(); this.order.status = 'failed'; this.orderService.delete(id).subscribe(data => { this.modalController.dismiss(); this.loadingService.dismiss(); this.isCanceled = 'Đã hủy đơn hàng'; }) } calTotalPrice() { return this.order.order_details.reduce((acc, cur) => acc + cur.amount * cur.total_price, 0) } calTotalAmount() { return this.order.order_details.reduce((acc, cur) => acc + cur.amount, 0); } } <file_sep>import { Router } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { ModalController } from '@ionic/angular'; @Component({ selector: 'app-complete-question', templateUrl: './complete-question.page.html', styleUrls: ['./complete-question.page.scss'], }) export class CompleteQuestionPage implements OnInit { score = 0; imgUrl = ''; title = ''; win = new Audio(); lose = new Audio(); questionsLength = 0; buttons = [ { name: 'Chơi tiếp', routerLink: 'questionares', }, { name: 'Thoát', routerLink: 'main/catechism-class' } ] constructor( private modalCtrl: ModalController, private route:Router) { } ngOnInit() { this.loadAudios(); this.init(); } ionViewWillLeave() { localStorage.removeItem('score'); localStorage.removeItem('questionsLength'); this.pauseAudios(); } init() { this.questionsLength = parseInt(localStorage.getItem('questionsLength')); localStorage.removeItem('questionType'); localStorage.removeItem('questionTypeName'); this.score = parseInt(localStorage.getItem('score')); this.lose.play(); if ( this.score == this.questionsLength) { this.imgUrl = '../../assets/img/questionares/success.svg'; this.title = 'HOÀN THÀNH XUẤT SẮC !'; this.win.play(); this.lose.pause(); } else { this.imgUrl = '../../assets/img/questionares/try-more.svg' this.title = 'HÃY CỐ GẮNG HƠN !'; } } loadAudios() { this.win.src = "https://res.cloudinary.com/baodang359/video/upload/v1615538814/kito-music/win_pnfljg.mp3"; this.win.load(); this.lose.src = "https://res.cloudinary.com/baodang359/video/upload/v1615538814/kito-music/lose_hpvlu2.mp3"; this.lose.load(); } pauseAudios() { this.win.pause(); this.lose.pause(); } async closeCompleteQuestion(value) { this.route.navigateByUrl(value); await this.modalCtrl.dismiss(); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AlertController } from '@ionic/angular'; import { AccountService } from 'src/app/@app-core/http'; import { CameraService, LoadingService, ToastService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-change-avatar', templateUrl: './change-avatar.page.html', styleUrls: ['./change-avatar.page.scss'], }) export class ChangeAvatarPage implements OnInit { headerCustom = { title: 'Đổi ảnh đại diện' }; activedAvatar; listAvatar = []; constructor( private accoutnService: AccountService, private alertCtrl: AlertController, private cameraService: CameraService, private toastService: ToastService, public loadingService: LoadingService, private router: Router ) { } ngOnInit() { this.getData(); } activeAvatar(item) { this.activedAvatar = item; } checkActivedItem(item) { return this.activedAvatar && item === this.activedAvatar; } getData() { this.accoutnService.getArrayAvatar().subscribe((data) => { this.listAvatar = data.data; }); } async avatarSetting() { let alertAvatarSetting = await this.alertCtrl.create({ message: 'Cài đặt ảnh đại diện', mode: 'ios', buttons: [ { text: 'Chọn từ thư viện', handler: () => { this.cameraService.getAvatarUpload(this.activedAvatar); this.router.navigateByUrl('account'); } }, { text: 'Chụp ảnh mới', handler: () => { this.cameraService.getAvatarTake(this.activedAvatar); this.router.navigateByUrl('account'); } }, { text: 'Đóng', role: 'destructive', }, ] }); await alertAvatarSetting.present(); } updateAvatar() { this.loadingService.present() localStorage.setItem('avatar', this.activedAvatar) this.accoutnService.updateAvatar({ "thumb_image": { "url": this.activedAvatar } }).subscribe(data => { }) this.loadingService.dismiss(); this.accoutnService.getAccounts().subscribe(); this.toastService.presentSuccess('Cập nhật ảnh thành công !'); this.accoutnService.updateAvatar(this.activedAvatar); this.router.navigateByUrl('account'); } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { TonggiaophanPage } from './tonggiaophan.page'; const routes: Routes = [ { path: '', component: TonggiaophanPage }, { path: 'parish-news', loadChildren: () => import('./parish-news/parish-news.module').then(m => m.ParishNewsPageModule) }, { path: 'archdiocese-detail', loadChildren: () => import('./archdiocese-detail/archdiocese-detail.module').then( m => m.ArchdioceseDetailPageModule) }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class TonggiaophanPageRoutingModule { } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { IonContent, IonSlides } from '@ionic/angular'; import { CourseService } from 'src/app/@app-core/http/course'; import { IPageCourse } from 'src/app/@app-core/http/course/course.DTO'; @Component({ selector: 'app-catechism', templateUrl: './catechism.page.html', styleUrls: ['./catechism.page.scss'], }) export class CatechismPage implements OnInit { @ViewChild('slides', { static: false }) slides: IonSlides; @ViewChild(IonContent) ionContent: IonContent; headerCustom = { title: 'Giáo lý Hồng Ân' }; menuItems = []; currentMenuItemId = null; slideOptions = { initialSlide: 0, autoHeight: true }; pageResult: IPageCourse = { course_group_id: null }; constructor( private coursesService: CourseService ) { } ngOnInit() { this.getData(); } getData() { this.coursesService.getGroup().subscribe((data: any) => { this.menuItems = data.course_groups; this.currentMenuItemId = this.menuItems[0].id; this.menuItems.forEach(menuItem => { this.pageResult.course_group_id = menuItem.id; menuItem.list = []; this.coursesService.getAll(this.pageResult).subscribe(d => { menuItem.list = d.courses; }) }) }) } scrollToTop(value) { this.ionContent.scrollToTop(value); } changeSegment(menuItem) { this.slides.lockSwipes(false).then(() => { this.slides.slideTo(this.menuItems.indexOf(menuItem)).then(() => { this.changeSlide(menuItem.id); this.slides.lockSwipes(true); }); }) } changeSlide(id) { this.currentMenuItemId = id; } disableSwipe() { this.slides.lockSwipes(true); } formatTime(date) { date = new Date(date); var hours = date.getHours(); var minutes = date.getMinutes(); hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + 'h' + ':' + minutes return strTime } } <file_sep>import { from } from 'rxjs'; export * from './auth'; export * from './account'; export * from './events' export * from './global'; export * from './@http-config'; export * from './history'; export * from './donate'; export * from './order'; export * from './diocese'; export * from './vatican'; export * from './pope'; export * from './parishes'; export * from './diocese-news'; export * from './bishop'; export * from './store'; export * from './questionares'; export * from './doctrine_classes'; export * from './course' export * from './calendar' export * from './hymn-music' export * from './post' <file_sep>import { Injectable } from '@angular/core'; import { Platform } from '@ionic/angular'; import { SocialSharing } from '@ionic-native/social-sharing/ngx'; @Injectable() export class SocialSharingService { constructor( public PlatForm: Platform, public socialSharing: SocialSharing, ) { } share() { this.socialSharing.shareWithOptions({ chooserTitle: 'Chia sẻ ứng dụng', url: 'https://play.google.com/store/apps/details?id=com.conggiaovn.patitek' }).then((data) => { console.log(data) }).catch((err) => { }) } }<file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { TonggiaophanPageRoutingModule } from './tonggiaophan-routing.module'; import { TonggiaophanPage } from './tonggiaophan.page'; import { HeaderModule } from 'src/app/@modular/header/header.module'; import { SearchBarNavModule } from 'src/app/@modular/search-bar-nav/search-bar-nav.module'; import { MainItemModule } from 'src/app/@modular/main-item/main-item.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, TonggiaophanPageRoutingModule, HeaderModule, SearchBarNavModule, MainItemModule ], declarations: [TonggiaophanPage] }) export class TonggiaophanPageModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { API_URL, AuthService } from 'src/app/@app-core/http'; import { LoadingService } from 'src/app/@app-core/utils'; import { Inject } from '@angular/core'; @Component({ selector: 'app-verification', templateUrl: './verification.page.html', styleUrls: ['./verification.page.scss'], }) export class VerificationPage implements OnInit { wrongCode = false; inputCode: FormGroup; error_messages = { 'code1': [ { type: 'required', message: 'Password is required.' }, ], 'code2': [ { type: 'required', message: 'Password is required.' }, ], 'code3': [ { type: 'required', message: 'Password is required.' }, ], 'code4': [ { type: 'required', message: 'Password is required.' }, ], 'code5': [ { type: 'required', message: 'Password is required.' }, ], 'code6': [ { type: 'required', message: 'Password is required.' }, ], } httpOptions: any; constructor( @Inject(API_URL) private apiUrl: string, public formBuilder: FormBuilder, private router: Router, private authService: AuthService, private loadingService: LoadingService ) { this.inputCode = this.formBuilder.group({ code1: ['',[Validators.required]], code2: ['',[Validators.required]], code3: ['',[Validators.required]], code4: ['',[Validators.required]], code5: ['',[Validators.required]], code6: ['',[Validators.required]] },); } ngOnInit() { } resendCode() { this.router.navigateByUrl('auth-manager/forgot-password'); } keytab($event,prevInput, fieldInput, nextInput) { if(this.inputCode.value[fieldInput] !== null && this.inputCode.value[fieldInput] !== '' && this.inputCode.value[fieldInput].toString().length > 1) { const strSplit = this.inputCode.value[fieldInput].toString(); this.inputCode.controls[fieldInput].setValue(strSplit[0]); this.inputCode.controls[nextInput].setValue(strSplit[1]); document.getElementById(nextInput).focus() } if(this.inputCode.value[fieldInput] !== null && this.inputCode.value[fieldInput] !== '' && this.inputCode.value[fieldInput].toString().length === 1) { document.getElementById(nextInput).focus() } if (this.inputCode.value[fieldInput] === null || this.inputCode.value[fieldInput] === '') { document.getElementById(prevInput).focus() } } confirmCode() { var c1 = this.inputCode.get('code1').value; var c2 = this.inputCode.get('code2').value; var c3 = this.inputCode.get('code3').value; var c4 = this.inputCode.get('code4').value; var c5 = this.inputCode.get('code5').value; var c6 = this.inputCode.get('code6').value; var inputstring = (`${c1}${c2}${c3}${c4}${c5}${c6}`).toString(); this.loadingService.present(); this.authService.checkcodePassword({code: inputstring}).subscribe((data:any)=> { this.loadingService.dismiss(); this.router.navigateByUrl("/auth-manager/new-password"); }, (error: any)=> { this.inputCode.reset(); this.wrongCode = true; throw error }) } } <file_sep>import { ComponentFixture, TestBed, async } from '@angular/core/testing'; import { IonicModule } from '@ionic/angular'; import { HymnMusicPage } from './hymn-music.page'; describe('HymnMusicPage', () => { let component: HymnMusicPage; let fixture: ComponentFixture<HymnMusicPage>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ HymnMusicPage ], imports: [IonicModule.forRoot()] }).compileComponents(); fixture = TestBed.createComponent(HymnMusicPage); component = fixture.componentInstance; fixture.detectChanges(); })); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-tabbar-manager', templateUrl: './tabbar-manager.page.html', styleUrls: ['./tabbar-manager.page.scss'], }) export class TabbarManagerPage implements OnInit { footerList = [ { id: 0, active: true, title: 'Trang chủ', tab: 'main', imgSrc: 'assets/icon/tab/main.svg', }, { id: 1, active: false, tab: 'social', imgSrc: 'assets/icon/tab/social.svg', title: 'Cộng đồng' }, { id: 2, active: false, tab: 'personal', imgSrc: 'assets/icon/tab/personal.svg', title: 'Cá nhân' }, ] constructor() { } ionTabsDidChange() { } setCurrentTab(item) { this.footerList.forEach(element => { element.active = false; }); item.active = true; } ngOnInit() { } } <file_sep>import { Injectable } from '@angular/core'; import { LoadingController } from '@ionic/angular'; @Injectable() export class LoadingService { isLoading = false; constructor( public loadingController: LoadingController ) { } async present() { this.isLoading = true; return await this.loadingController.create({ message: '<ion-img src="/assets/icon/icon-loading.svg" alt="loading..." style="width: 10vh; height: 10vh"></ion-img>', mode: 'ios', cssClass: 'scale-down-center', showBackdrop: true, keyboardClose: true, spinner: null }).then(a => { a.present().then(() => { if (!this.isLoading) { a.dismiss(); } }) }); } async dismiss() { this.isLoading = false; let topLoader = await this.loadingController.getTop(); while (topLoader) { if (!(await topLoader.dismiss())) { break; } topLoader = await this.loadingController.getTop(); } } } <file_sep>import { IPageRequest } from "../global"; export interface IPageParishes extends IPageRequest{ diocese_id?; parish_id?; }<file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { map, catchError } from 'rxjs/operators'; import { APICONFIG } from '..'; @Injectable({ providedIn: 'root' }) export class PostService { constructor( private http: HttpClient ) { } public getAllPosts(){ return this.http.get<any>(`${APICONFIG.POST.GET_ALL}`).pipe( map((result) =>{ return result; }), catchError((error) =>{ throw error; }) ) } public getPostID(id){ return this.http.get<any>(`${APICONFIG.POST.GET_ID, id}`).pipe( map((result) =>{ return result; }), catchError((error) =>{ throw error; }) ) } public addLike(id: number){ return this.http.post(`${APICONFIG.POST.LIKE(id)}`, null).pipe( map((result) =>{ return result; }), catchError((error) =>{ throw error; }) ) } public dislike(id: number){ return this.http.post(`${APICONFIG.POST.DIS_LIKE(id)}`, null).pipe( map((result) =>{ return result; }), catchError((error) =>{ throw error; }) ) } public addComment(id, content, imgurl){ const params = { content: content, photos_attributes: imgurl, }; return this.http.post(`${APICONFIG.POST.COMMENT(id)}`, params).pipe( map((result) =>{ return result; }), catchError((error) =>{ throw error; }) ) } public repplycomment(id, content, imgurl, commentID){ const params={ content: content, photos_attributes: imgurl, comment_id: commentID }; return this.http.post(`${APICONFIG.POST.COMMENT(id)}`, params).pipe( map((result) =>{ return result; }), catchError((error) =>{ throw error; }) ) } public showAllComment(id){ return this.http.get(`${APICONFIG.POST.SHOW_MORE_COMMENTS(id)}`).pipe( map((result) =>{ return result; }), catchError((error) =>{ throw error; }) ); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { PaymentmethodsPageRoutingModule } from './paymentmethods-routing.module'; import { PaymentmethodsPage } from './paymentmethods.page'; import { InAppBrowser } from '@ionic-native/in-app-browser/ngx'; import { HeaderComponent } from '../@modular/header/header.component'; import { HeaderModule } from '../@modular/header/header.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, HeaderModule, PaymentmethodsPageRoutingModule ], providers: [ InAppBrowser ], declarations: [PaymentmethodsPage], }) export class PaymentmethodsPageModule {} <file_sep>import { InjectionToken } from '@angular/core'; import { environment } from 'src/environments/environment.prod'; export const API_URL = new InjectionToken<string>('apiUrl'); export const APICONFIG = { BASEPOINT: environment.apiUrl, AUTH: { LOGIN: '/app/auth/login', SIGNUP: `/app/auth/signup`, TYPE_OF_USER: `/app/auth/users/profile`, RESET_PASSWORD_EMAIL: `/app/reset_password/send_code`, CHECK_CODE_RESET: `/app/reset_password/check_code`, RESET_PASSWORD: `/app/app_users/change_password`, RESET_PASSWORD_NEW: `/app/reset_password/reset_password`, COUNTRY_CODE: `/app/country_codes`, UPDATE_AVATAR: `/app/app_users/update_avatar` }, ACCOUNT: { PROFILE_USER: `/app/app_users/profile`, UPDATE_PROFILE: `/app/app_users/update_profile`, UPDATE_PASS: `/app/users/update_password`, GETDETAIL: (id) => `/app/users/${id}`, EDIT: (id) => `/app/users/${id}`, DELETE: (id) => `/app/users/${id}`, UPDATE_PREMIUM: (id) => `/app/users/request_upgrade`, CONTACT_ADMIN: `/app/interact_email/submit`, SUPPORT: `/app/supports` }, DIOCESE: { GET: `/app/dioceses`, GET_DETAIL: id => `/app/dioceses/${id}` }, PARISHES: { GET_ALL_WITH_DIOCESE_ID: `/app/parishes`, GETNEWS: `/app/parish_news`, GET_ALL: `app/parishes/all_parishes`, GET_DETAIL: id => `/app/parishes/${id}` }, EVENTS: { GET: `/app/events`, GET_DETAIL: (id) => `/app/events/${id}`, }, CALENDARS: { GET_BY_MONTH: `/app/calendars/month`, GET_BY_WEEK: `/app/calendars/week`, GET_BY_DAY: `/app/calendars/day`, }, DONATES: { DONATE_VISA: `/app/donation_logs/visa_master`, DONATE_MOMO: `/app/donation_logs/momo` }, PRAY: { PRAY_VISA: `/app/pray_logs/visa_master`, PRAY_MOMO: `/app/pray_logs/momo` }, HISTORY: { GET_SERVICES: `/app/attention_logs/service_history`, GET_EVENTS: `/app/attention_logs/event_history` }, ORDER: { GET_ALL: `/app/orders`, GET_DETAIL: (id) => `/app/orders/${id}`, CREATE: `/app/orders`, DELETE: (id) => `/app/orders/${id}`, PAYMENT_ORDER_VISA: `/app/order_payments/visa_master`, PAYMENT_ORDER_MOMO: `/app/order_payments/momo`, PAYMENT_ORDER_CASH: `/app/order_payments/cash`, }, VATICAN: { GET: `/app/vatican_news`, GET_CATE: `/app/vatican_news/categories`, GET_DETAIL: id => `/app/vatican_news/${id}` }, POPE: { GET: `/app/pope_infos`, GET_DETAIL: id => `/app/pope_infos/${id}` }, BISHOP: { GET: `/app/bishop_infos`, GET_DETAIL: id => `/app/bishop_infos/${id}` }, DIOCESE_NEWS: { GET: `/app/diocese_news`, GET_DETAIL: id => `/app/diocese_news/${id}` }, DOCTRINE_CLASSES: { GET: `/app/doctrine_classes/marriage`, GET_DETAIL: id => `/app/doctrine_classes/marriage/${id}`, REGISTER: `/app/doctrine_classes/register`, UNREGISTER: `/app/doctrine_classes/unregister`, }, CATECKISM: { GET: `/app/doctrine_classes/catechism`, GET_DETAIL: id => `/app/doctrine_classes/catechism/${id}` }, STORE: { GET_ALL_CATEGORIES: `/app/categories`, GET_ALL_PRODUCTS: `/app/products`, GET_DETAIL_PRODUCT: id => `/app/products/${id}` }, QUESTIONARES: { GET_TOPIC: `/app/questions/topics`, GET_LEVEL: `/app/questions/levels`, GET_QUES_TOPIC: topic => `/app/questions/by_topic?topic=${topic}`, GET_QUES_LEVEL: level => `/app/questions/by_level?level=${level}`, CHECK_ANSWER: answerKey => `/${answerKey}`, UPDATE_SCORE: `/app/games/score`, RANKING: `/app/games/rankings`, }, COURSE: { GET_COURSE_GROUP: `/app/course_groups`, GET_COURSE_ID: `/app/courses` }, MUSIC: { GET_ALL: `/app/songs`, GET_DETAIL: id => `/app/songs/${id}`, GET_ALL_FAVORITE: `/app/songs/favourite_songs`, FAVORITE: `/app/songs/favourite`, UNFAVORITE: `/app/songs/unfavourite`, }, IMAGE_PROFILE: { GET_ALL: `/app/app_users/default_avatar` }, VIDEO: { GET_ALL: `/app/lecture_videos`, GET_BIBEL_SONG: `/app/bible_songs`, GET_BIBLE_SONG_DETAIL: id => `/app/bible_songs/${id}`, }, ATTENTION_LOG: { GET: date => `/app/attention_logs?cal_date=${date}`, CREATE: `/app/attention_logs` }, DEVICES: { REGISTER: `/app/register_device` }, POST: { GET_ALL: `/app/posts`, GET_ID: (id) => `/app/posts/${id}`, LIKE: (id) => `/app/posts/${id}/add_like`, DIS_LIKE: (id) => `/app/posts/${id}/delete_like`, COMMENT: (id) => `/app/posts/${id}/add_comment`, SHOW_MORE_COMMENTS: (id) => `/app/posts/${id}/show_more_comment` } }; <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { MyParishPageRoutingModule } from './my-parish-routing.module'; import { MyParishPage } from './my-parish.page'; import { HeaderModule } from 'src/app/@modular/header/header.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, HeaderModule, MyParishPageRoutingModule ], declarations: [MyParishPage] }) export class MyParishPageModule {} <file_sep>import { Observable, throwError } from 'rxjs'; import { Injectable, Inject } from '@angular/core'; import { HttpRequest, HttpErrorResponse, HttpInterceptor } from '@angular/common/http'; import { HttpHandler } from '@angular/common/http'; import { HttpEvent } from '@angular/common/http'; import { catchError } from 'rxjs/operators'; import { Router } from '@angular/router'; import { API_URL } from './http/@http-config'; import { LoadingService } from './utils'; @Injectable() export class IntercepterService implements HttpInterceptor { constructor( @Inject(API_URL) private apiUrl: string, private router: Router, private loading: LoadingService ) {} count : number = 0; intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { var request = req.clone({ url: this.prepareUrl(req.url) }); if(localStorage.getItem('Authorization') !== null){ request = req.clone({ url: this.prepareUrl(req.url), headers: req.headers.set('Authorization', localStorage.getItem('Authorization') || '').set('Accept', 'multipart/form-data'), }); } return next.handle(request) .pipe( catchError((res) => { if (res instanceof HttpErrorResponse) { if (res.status === 401) { // this.count++; this.router.navigateByUrl('/auth-manager/login', { queryParams: { returnUrl: window.location.pathname } }); localStorage.clear(); } // if(this.count == 3) { // this.count = 0; // this.router.navigateByUrl('/auth/login', { queryParams: { returnUrl: window.location.pathname } }); // localStorage.clear(); // } return throwError(res); } })); } private isAbsoluteUrl(url: string): boolean { const absolutePattern = /^https?:\/\//i; return absolutePattern.test(url); } private prepareUrl(url: string): string { url = this.isAbsoluteUrl(url) ? url : this.apiUrl + url; return url.replace(/([^:]\/)\/+/g, '$1'); } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { PrayerTimePage } from './prayer-time.page'; const routes: Routes = [ { path: '', component: PrayerTimePage }, { path: 'prayer-detail', loadChildren: () => import('./prayer-detail/prayer-detail.module').then( m => m.PrayerDetailPageModule) }, { path: 'select-diocese', loadChildren: () => import('./select-diocese/select-diocese.module').then( m => m.SelectDiocesePageModule) }, { path: 'select-parish', loadChildren: () => import('./select-parish/select-parish.module').then( m => m.SelectParishPageModule) } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class PrayerTimePageRoutingModule {} <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { DioceseService, ParishesService } from 'src/app/@app-core/http'; import { LoadingService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-setting', templateUrl: './setting.page.html', styleUrls: ['./setting.page.scss'], }) export class SettingPage implements OnInit { headerCustom = { title: 'Cài đặt' }; items = []; countApi = 0; constructor( private router: Router, private dioceseService: DioceseService, private parishService: ParishesService, private loadingService: LoadingService ) { } ngOnInit() { this.loadingService.present(); this.initData(); } ionViewWillEnter() { this.getData(); } getData() { const languageName = JSON.parse(localStorage.getItem('language'))?.name; if (languageName) { this.items[0].name = languageName; } else { localStorage.setItem('language', JSON.stringify({ name: "Tiếng Việt", id: 0 })); this.items[0].name = 'Tiếng Việt'; } this.dioceseService.getDetail(localStorage.getItem('diocese_id')).subscribe( data => { this.items[1].name = data.diocese.name; this.countApi++; if (this.countApi >= 2) { this.loadingService.dismiss(); } }, () => { this.loadingService.dismiss(); }) this.parishService.getDetail(localStorage.getItem('parish_id')).subscribe( data => { this.items[2].name = data.parish.name; this.countApi++; if (this.countApi >= 2) { this.loadingService.dismiss(); } }, () => { this.loadingService.dismiss(); }) } initData() { this.items = [ { type: 'language', title: "Ngôn ngữ", icon: "assets/img/setting/language.svg", // name: JSON.parse(localStorage.getItem('language')).name, routerLink: '/account-setting/setting/setting-languages' }, { id: localStorage.getItem('diocese_id'), type: 'diocese', title: "Giáo phận", icon: "assets/img/setting/archdiocese.svg", name: null, routerLink: '/account-setting/setting' }, { id: localStorage.getItem('parish_id'), type: 'parish', title: "Giáo xứ", icon: "assets/img/setting/parish.svg", name: null, routerLink: '/account-setting/setting' }, ]; } goToDetail(item) { if (item.type == 'language') { this.router.navigateByUrl(item.routerLink); } else { let data = { type: item.type, dioceseId: item.type == 'parish' ? this.items[1].id : null } this.router.navigate(['account-setting/setting/select-diocese'], { queryParams: { data: JSON.stringify(data) } }) } } } <file_sep>import { SocialSharingService } from './@app-core/utils/social-sharing.service'; import { NetworkService } from './@app-core/utils/network.service'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouteReuseStrategy } from '@angular/router'; import { IonicModule, IonicRouteStrategy } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CoreModule } from './@app-core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AuthGuard } from './@app-core/auth-guard.service'; import { Camera } from '@ionic-native/camera/ngx'; import { SlideService } from './@modular/slide/slide.service'; import { Stripe } from '@ionic-native/stripe/ngx'; import { enableProdMode } from '@angular/core'; import { SpeechRecognition } from '@ionic-native/speech-recognition/ngx' import { AudioManagement } from '@ionic-native/audio-management/ngx'; import { AudioManagerService, CameraService, GeolocationService, OneSignalService, SpeechRecognitionService } from './@app-core/utils'; import { OneSignal } from '@ionic-native/onesignal/ngx'; import { Geolocation } from '@ionic-native/geolocation/ngx'; import { NativeGeocoder, NativeGeocoderOptions, NativeGeocoderResult } from '@ionic-native/native-geocoder/ngx'; import { NativePageTransitions } from '@ionic-native/native-page-transitions/ngx'; import { CommonModule } from '@angular/common'; import { SocialSharing } from '@ionic-native/social-sharing/ngx'; import { PhotoLibrary } from '@ionic-native/photo-library/ngx'; // import { ImagePicker } from '@ionic-native/image-picker/ngx'; // import { IonicSwipeAllModule } from 'ionic-swipe-all'; @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [ BrowserModule, CommonModule, IonicModule.forRoot(), AppRoutingModule, CoreModule.forRoot(), // StoreModule.forRoot({}), FormsModule, ReactiveFormsModule, ], providers: [ StatusBar, SlideService, Stripe, SplashScreen, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }, AuthGuard, Camera, CameraService, SpeechRecognition, SpeechRecognitionService, AudioManagement, AudioManagerService, OneSignal, OneSignalService, Geolocation, GeolocationService, NativeGeocoder, NativePageTransitions, NetworkService, SocialSharing, SocialSharingService, PhotoLibrary, // ImagePicker ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { map, catchError } from 'rxjs/operators'; import { APICONFIG } from '..'; import { requestQuery } from '../../utils'; import { IPageVatican } from './vatican.DTO'; @Injectable() export class VaticanService { constructor(private http: HttpClient) { } public getAll(request: IPageVatican) { return this.http.get<any>(`${APICONFIG.VATICAN.GET}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ); } public getCategory() { return this.http.get<any>(`${APICONFIG.VATICAN.GET_CATE}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ); } public getDetail(id) { return this.http.get<any>(`${APICONFIG.VATICAN.GET_DETAIL(id)}`).pipe( map(result => { return result; }), catchError(errorRes => { throw errorRes.error; }) ); } } <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { ModalController } from '@ionic/angular'; @Component({ selector: 'app-comfiller', templateUrl: './comfiller.component.html', styleUrls: ['./comfiller.component.scss'], }) export class ComfillerComponent implements OnInit { listFiller = [ { id: "all", name: "<NAME>", icon: "assets/img/music/allmusic.svg" }, { id: "name", name: "<NAME>", icon: "assets/img/music/song.svg" }, { id: "artist", name: "<NAME>", icon: "assets/img/music/artist.svg" }, { id: "song_type", name: "Thể loại", icon: "assets/img/music/category.svg" } ] listSort = [{ id: "asc", name: "Tên (A-Z)", icon: "assets/img/music/az.svg" }, { id: "desc", name: "Tên (Z-A)", icon: "assets/img/music/za.svg" }, ] activeFiller; activeSort; @Input() fillerItem; @Input() sortItem; constructor( private modalCtrl: ModalController ) { } ngOnInit() { this.activeFiller = this.fillerItem; this.activeSort = this.sortItem; } selectFiller(item) { this.activeFiller = item.id; this.modalCtrl.dismiss({ filler: this.activeFiller }); } selectSort(item) { this.activeSort = item.id; this.modalCtrl.dismiss({ sort: this.activeSort }); } } <file_sep>export * from './bishop.service';<file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ModalController } from '@ionic/angular'; import { CalendarService, EventsService } from '../@app-core/http'; import { LoadingService } from '../@app-core/utils'; import { CalendarDetailPage } from '../@modular/calendar-detail/calendar-detail.page'; @Component({ selector: 'app-calendar', templateUrl: './calendar.page.html', styleUrls: ['./calendar.page.scss'], }) export class CalendarPage implements OnInit { headerCustom = { title: 'Lịch Công Giáo' }; DATES = [ 'Th2', 'Th3', 'Th4', 'Th5', 'Th6', 'Th7', 'CN', ] DATE_ENG = [ 'Sun', 'Mon', 'Tue', 'Web', 'Thu', 'Fri', 'Sat', ] calendarMonth = [] masses = [] date currentMonth nameMonth currentYear paramCalendar paramMonth constructor( private calendarService: CalendarService, private loadingService: LoadingService, private router: Router ) { } ngOnInit() { this.date = new Date() this.currentMonth = this.date.getMonth() this.currentYear = this.date.getFullYear() this.nameMonth = this.currentMonth + 1 this.paramMonth = this.currentMonth + 1 this.paramMonth = (parseInt(this.paramMonth)) < 10 ? `0${this.paramMonth}` : this.paramMonth this.getEventByMonth() } prevMonth() { this.calendarMonth = [] this.masses = [] if (this.currentMonth == 0) { this.currentMonth = 11 this.nameMonth = 12 this.paramMonth = this.nameMonth this.currentYear = this.currentYear - 1 } else { this.nameMonth = this.nameMonth - 1 this.currentMonth = this.currentMonth - 1 this.paramMonth = this.nameMonth } this.paramMonth = (parseInt(this.paramMonth)) < 10 ? `0${this.paramMonth}` : this.paramMonth this.getEventByMonth() } nextMonth() { this.calendarMonth = [] this.masses = [] if (this.currentMonth == 11) { this.currentMonth = 0 this.nameMonth = 1 this.paramMonth = 1 this.currentYear = this.currentYear + 1 } else { this.nameMonth = this.nameMonth + 1 this.currentMonth = this.currentMonth + 1 this.paramMonth = this.currentMonth + 1 } this.paramMonth = (parseInt(this.paramMonth)) < 10 ? `0${this.paramMonth}` : this.paramMonth this.getEventByMonth() } getEventByMonth() { this.loadingService.present() this.paramCalendar = { cal_date: `${this.currentYear}` + '-' + `${this.paramMonth}` + '-' + '01' } this.calendarService.getByMonth(this.paramCalendar).subscribe(data => { this.loadingService.dismiss() this.calendarMonth = data.calendars this.masses = data.masses this.calendarMonth.forEach(i => { i.date = new Date(i.date) i.lunar_date = new Date(i.lunar_date) }) this.masses.forEach(i => { i.date = new Date(i.date) i.lunar_date = new Date(i.lunar_date) }) }) } async presentModal(item) { this.router.navigate(['/calendar-detail'],{ queryParams: { data: JSON.stringify(item) }} ) } } <file_sep>import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class SlideService { private data: BehaviorSubject<IDataNoti> = new BehaviorSubject<IDataNoti>({ title: '', label:'', image: '', routerLink: '' }) constructor() { } public get datafrom(): Observable<IDataNoti> { return this.data.asObservable(); } public setdataSlide(value: IDataNoti) { this.data.next(value); } } export interface IDataNoti { image: any; title: string; label: string, routerLink: string; }<file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { APICONFIG } from '../@http-config'; import { catchError, map } from 'rxjs/operators'; import { LoadingService } from 'src/app/@app-core/utils'; @Injectable() export class AccountService { constructor( private http: HttpClient, public loadingServie: LoadingService ) { } public getAccounts() { return this.http.get(`${APICONFIG.ACCOUNT.PROFILE_USER}`).pipe( map((result: any) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } public updateProfile(data) { const req = { app_user: data } return this.http.put(`${APICONFIG.ACCOUNT.UPDATE_PROFILE}`, req).pipe( map((result:any) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } public updatePassword(pass) { return this.http.put(`${APICONFIG.ACCOUNT.UPDATE_PASS}`, pass).pipe( map((result) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } public getAccountDetail(id: string) { return this.http.get<any>(`${APICONFIG.ACCOUNT.GETDETAIL(id)}`).pipe( map((result) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } public editAccount(id: string, modifer: any) { return this.http.put<any>(`${APICONFIG.ACCOUNT.EDIT(id)}`, modifer).pipe( map((result) => { // this.toastr.success(SUCCESS.EDIT, STATUS.SUCCESS); return result; }), catchError((errorRes) => { throw errorRes.error; })); } // XOA MOT NHAN VIEN public DeleteAccount(id: string) { return this.http.delete(`${APICONFIG.ACCOUNT.DELETE(id)}`).pipe( map((result) => { // this.toastr.success(SUCCESS.DELETE, STATUS.SUCCESS); return result; }), catchError((errorRes: any) => { throw errorRes.error; })); } public ContactAdmin(req) { return this.http.post(`${APICONFIG.ACCOUNT.CONTACT_ADMIN}`, req).pipe( map((result)=> { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ) } public upgradePremium(req) { return this.http.post(`${APICONFIG.ACCOUNT.UPDATE_PREMIUM}`, req).pipe( map((result) => { return result }), catchError((errorRes: any) => { throw errorRes.error; }) ) } public uploadPhoto(req) { return this.http.post('http://image-service.patitek.com/api/v1/images/upload', req).pipe( map((result) => { return result }), catchError((errorRes: any) => { throw errorRes.error; }) ) } public updateAvatar(req) { return this.http.put(`${APICONFIG.AUTH.UPDATE_AVATAR}`, req).pipe( map((result) => { return result }), catchError((errorRes: any) => { throw errorRes.error; }), ) } public getArrayAvatar(){ return this.http.get(`${APICONFIG.IMAGE_PROFILE.GET_ALL}`).pipe( map((result: any) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } public showSupports() { return this.http.get(`${APICONFIG.ACCOUNT.SUPPORT}`).pipe( map((result: any) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-auth-manager', templateUrl: './auth-manager.page.html', styleUrls: ['./auth-manager.page.scss'], }) export class AuthManagerPage implements OnInit { constructor() { } ngOnInit() { const tabs = document.querySelectorAll('ion-tab-bar'); Object.keys(tabs).map((key) => { tabs[key].style.display = 'none'; }); } } <file_sep>import { NetworkService } from './utils/network.service'; import { Router } from '@angular/router'; import { LoadingService } from './utils/loading.service'; import { ErrorHandler, Injectable, Injector, Inject } from '@angular/core'; import { ToastService } from './utils'; import { AlertController } from '@ionic/angular'; @Injectable() export class GlobalErrorHandler implements ErrorHandler { constructor( @Inject(Injector) private readonly injector: Injector, private loadingService: LoadingService, private toarstSerivce: ToastService, private router: Router, private alertController: AlertController, private netWorkService: NetworkService ) { } handleError(error) { console.log(error); this.loadingService.dismiss(); if (error.message) { console.error(error.message); } if (error.message === 'Uncaught (in promise): overlay does not exist' || error.message === 'Uncaught (in promise): plugin_not_installed') { return } else if (error.message === 'Signature has expired' || error.message === 'Signature verification raised') { this.validateConfirm(); return } // else else if (error.message != null) { this.toarstSerivce.presentFail(error.message); } this.netWorkService.setSubscriptions(); } async validateConfirm() { const alert = await this.alertController.create({ cssClass: 'my-custom-class', header: 'Phiên đã hết hạn, vui lòng đăng nhập lại', backdropDismiss: false, mode: 'ios', buttons: [ { text: 'Đồng ý', handler: () => { this.router.navigate(['/auth-manager/login']); localStorage.clear(); location.reload(); } } ] }); await alert.present(); } } <file_sep>import { LoadingService } from 'src/app/@app-core/utils'; import { HymnMusicService } from './../../@app-core/http/hymn-music/hymn-music.service'; import { Component, OnInit, ViewChild } from '@angular/core'; import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; import { NavController, IonInfiniteScroll, IonContent } from '@ionic/angular'; import { IPageRequest } from 'src/app/@app-core/http'; import { Router } from '@angular/router'; @Component({ selector: 'app-hymn-video', templateUrl: './hymn-video.page.html', styleUrls: ['./hymn-video.page.scss'], }) export class HymnVideoPage implements OnInit { @ViewChild('infiniteScrollVideos') infinityScroll: IonInfiniteScroll; @ViewChild(IonContent) ionContent: IonContent; headerCustom = { title: 'Video bài giảng & Sách tiếng nói' }; trustedVideoUrlArray: SafeResourceUrl[] = []; pageRequestVideos: IPageRequest = { page: 1, per_page: 4, } pageRequestMusic: IPageRequest = { page: 1, per_page: 4, } videos = []; music = []; segmentValue = 'video'; notFound = false; constructor( public navCtrl: NavController, private domSanitizer: DomSanitizer, private hymnVideoService: HymnMusicService, private LoadingService: LoadingService, private router: Router ) { } ngOnInit() { this.LoadingService.present(); this.getVideos(); this.getBiBlesSong(); } getVideos(func?) { this.notFound = false; this.hymnVideoService.getAllLectureVideo(this.pageRequestVideos).subscribe(data => { this.notFound = true; this.videos = this.videos.concat(data.lecture_videos) this.pageRequestVideos.page++; func && func(); if (this.videos.length >= data.meta.pagination.total_objects) { this.infinityScroll.disabled = true; } this.videos.forEach((e) => { e.trustLink = this.domSanitizer.bypassSecurityTrustResourceUrl(e.url.replace('watch?v=', 'embed/')) }) setTimeout(() => { this.LoadingService.dismiss(); }, 1500) }) } getBiBlesSong(func?) { this.notFound = false; this.hymnVideoService.getAllBibleSong(this.pageRequestMusic).subscribe((data) => { data.bible_songs.forEach(element => { this.music.push(element) }); this.pageRequestMusic.page++ func && func(); if (this.videos.length >= data.meta.pagination.total_objects) { this.infinityScroll.disabled = true; } setTimeout(() => { this.LoadingService.dismiss(); }, 1500) }) } loadMoreVideos(event) { this.getVideos(() => { event.target.complete(); }); } loadMoreMusic(event) { this.getBiBlesSong(() => { event.target.complete(); }) } search(value: string) { if (typeof value != 'string') { return; } else if (!value) { delete this.pageRequestVideos.search; } else { this.pageRequestVideos.search = value; } this.pageRequestVideos.page = 1; this.videos = []; this.trustedVideoUrlArray = []; this.getVideos(); this.infinityScroll.disabled = false; } changedSegment(event) { this.segmentValue = event.target.value; } gotoBibleSongDetail(id) { this.router.navigate(['main/hymn-video/BibleSongdetail/' + id]); } } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { catchError, map } from 'rxjs/operators'; import { APICONFIG, IPageRequest } from '..'; import { requestQuery } from '../../utils'; import { IPageCourse } from './course.DTO'; @Injectable() export class CourseService { constructor(private http: HttpClient) { } public getAll(request: IPageCourse) { return this.http.get<any>(`${APICONFIG.COURSE.GET_COURSE_ID}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ); } public getGroup() { return this.http.get<any>(`${APICONFIG.COURSE.GET_COURSE_GROUP}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ); } public getDetail(id) { return this.http.get<any>(`${APICONFIG.DIOCESE.GET_DETAIL(id)}`).pipe( map(result => { return result; }), catchError(errorRes => { throw errorRes.error; }) ); } } <file_sep>import { Component, OnInit, Output } from '@angular/core'; import { DioceseService } from 'src/app/@app-core/http/diocese'; import { IPageRequest } from 'src/app/@app-core/http/global/global.DTO'; import { LoadingService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-tonggiaophan', templateUrl: './tonggiaophan.page.html', styleUrls: ['./tonggiaophan.page.scss'], }) export class TonggiaophanPage implements OnInit { headerCustom = { title: '(Tổng) Giáo phận' }; pageRequest: IPageRequest = { search: '', } dioceses = []; holySee = { diocese_type: "vatican", name: "<NAME>", thumb_image: { url: "assets/img/tonggiaophan/vatican.jpg" } } output; notFound = false; constructor( private diocesesService: DioceseService, private loading: LoadingService ) { } ngOnInit() { this.loading.present(); this.getAllDiocese(); } getAllDiocese() { this.notFound = false; this.diocesesService.getAll(this.pageRequest).subscribe(data => { this.notFound = true; this.loading.dismiss(); data.dioceses.forEach(diocese => { let hasNull = false; for (let i in diocese) { if (diocese[i] =="location"&& diocese[i] === null) { hasNull = true; return; } } !hasNull && this.dioceses.push(diocese); }) }) } search(value: string) { if (typeof value != 'string') { return; } else if (!value) { delete this.pageRequest.search; } else { this.pageRequest.search = value; } this.reset(); this.getAllDiocese(); } reset() { this.dioceses = []; this.pageRequest.page = 1; } } <file_sep>export * from './auth.service'; export * from './auth.DTO'; <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MainSlideRoutingModule } from './main-slide-routing.module'; import { MainSlideComponent } from './main-slide.component'; import { IonicModule } from '@ionic/angular'; @NgModule({ declarations: [MainSlideComponent], imports: [ CommonModule, MainSlideRoutingModule, IonicModule ], exports: [ MainSlideComponent ] }) export class MainSlideModule { } <file_sep>import { NetworkService } from './../../@app-core/utils/network.service'; import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService, IPageRequest, PATTERN } from 'src/app/@app-core/http'; import { ToastController } from '@ionic/angular'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { ToastService } from 'src/app/@app-core/utils'; import { DioceseService } from 'src/app/@app-core/http/diocese'; import { ParishesService } from 'src/app/@app-core/http/parishes'; import { IPageParishes } from 'src/app/@app-core/http/parishes/parishes.DTO'; @Component({ selector: 'app-login', templateUrl: './login.page.html', styleUrls: ['./login.page.scss'], }) export class LoginPage implements OnInit { public type = 'password'; public showpass = false; public name = 'eye-outline'; public status = 'login'; country_codes: any; segmentValue = 'login'; matchPassword = false; formLogin: FormGroup; formSignUp: FormGroup; showSpinner = false; validationLoginMessages = { phone_number: [ { type: 'required', message: 'Hãy nhập số điện thoại' }, ], password: [ { type: '<PASSWORD>', message: '<PASSWORD>' } ], } validationSignUpMessages = { full_name: [ { type: 'required', message: 'Hãy nhập tên' }, { type: 'pattern', message: 'Tên không thể chứa ký tự đặc biệt' }, ], email: [ { type: 'required', message: 'Hãy nhập email' }, { type: 'pattern', message: 'Email không hợp lệ' }, ], phone_number: [ { type: 'required', message: 'Hãy nhập số điện thoại' }, { type: 'pattern', message: 'Số điện thoại không hợp lệ' }, ], age: [ { type: 'required', message: 'Hãy nhập tuổi' } ], country_code: [ { type: 'required', message: 'Hãy nhập mã quốc gia' }, ], province: [ { type: 'required', message: 'Hãy nhập tỉnh' }, ], district: [ { type: 'required', message: 'Hãy nhập quận' }, ], full_address: [ { type: 'required', message: 'Hãy nhập địa chỉ' }, ], password: [ { type: 'required', message: '<PASSWORD>' }, { type: 'minLength', message: 'Mật khẩu phải dài tối thiểu 6 ký tự' }, ], } countries: any; listDioceses: any; listParishes: any; id_diocese = 1; tagret; code; constructor( private router: Router, private authService: AuthService, public toastController: ToastController, private formBuilder: FormBuilder, private toastService: ToastService, private diocese: DioceseService, private parishes: ParishesService, private networkService: NetworkService ) { } pageRequestDioceses: IPageRequest = { page: 1, per_page: 100, } pageRequestParishes: IPageParishes = { diocese_id: this.id_diocese, page: 1, per_page: 100, } ngOnInit() { localStorage.setItem('isRepeat', 'true'); this.networkService.setSubscriptions(); this.authService.countryCode().subscribe((data: any) => { this.country_codes = data.country_codes; this.code = data.country_codes[0].phone_code; }) this.diocese.getAll(this.pageRequestDioceses).subscribe(data => { this.listDioceses = data.dioceses; this.tagret = this.listDioceses[0].name }), this.parishes.getAllWithDioceseId(this.pageRequestParishes).subscribe(data => { this.listParishes = data.parishes; }) this.initForm(); // this.oneSignal.startOneSignal(); // this.oneSignal.setUpOneSignal(); } onSelectChange(event) { this.pageRequestParishes.diocese_id = this.formSignUp.get('dioceses').value; this.parishes.getAllWithDioceseId(this.pageRequestParishes).subscribe(data => { this.listParishes = data.parishes; }) } initForm() { this.formLogin = this.formBuilder.group({ phone_number: new FormControl('', Validators.required), password: new FormControl('', Validators.required) }) this.formSignUp = this.formBuilder.group({ full_name: new FormControl('', Validators.compose([ Validators.required, // Validators.pattern(PATTERN.NAME) ])), sex: new FormControl('male'), email: new FormControl('', Validators.compose([ Validators.required, Validators.pattern(PATTERN.EMAIL) ])), phone_number: new FormControl('', Validators.compose([ Validators.required, Validators.pattern(PATTERN.PHONE_NUMBER_VIETNAM) ])), age: new FormControl('', Validators.compose([ Validators.required ])), dioceses: new FormControl('', Validators.compose([ Validators.required ])), parish_id: new FormControl('', Validators.compose([ Validators.required ])), country_code: new FormControl(''), // province: new FormControl('Ho Chi Minh'), // district: new FormControl('Thu Duc'), full_address: new FormControl('', Validators.required), password: new FormControl('', Validators.compose([ Validators.required, Validators.minLength(6) ])), confirmed_password: new FormControl('') }) } changedSegment(event) { this.segmentValue = event.target.value; } canSubmitLogin() { return this.formLogin.valid; } canSubmitSignUp() { return this.formSignUp.valid; } async submitLogin() { this.showSpinner = true; if (!this.canSubmitLogin()) { this.showSpinner = false; this.markFormGroupTouched(this.formLogin); } else { let dataFormLogin = this.formLogin.value; dataFormLogin.phone_number = dataFormLogin.phone_number.length == 10 ? dataFormLogin.phone_number.substring(1, 10) : dataFormLogin.phone_number; dataFormLogin.phone_number = `+84${dataFormLogin.phone_number}`; let dataSubmit = { "phone_number": dataFormLogin.phone_number, "password": <PASSWORD> } this.authService.login(dataSubmit).subscribe( () => { this.showSpinner = false; this.router.navigate(['main/chabad']); }, (error: any) => { this.showSpinner = false; throw error } ); } } submitSignUp() { this.showSpinner = true; if (!this.canSubmitSignUp()) { this.toastService.presentSuccess('Kiểm tra lại các trường'); this.showSpinner = false; this.markFormGroupTouched(this.formSignUp); } else if (!this.checkMatchConfirmedPassword()) { this.showSpinner = false; this.toastService.presentSuccess('Mật khẩu không trùng khớp'); } else { let data = this.formSignUp.value; if (data.phone_number.search("0") == 0) { data.phone_number = data.phone_number.substring(1); } // if (data.phone_number.search("+84") == 0) { // data.phone_number = '+84' + data.phone_number; // } let submitData = { "full_name": data.full_name, "sex": data.sex, "birthday": data.age, "full_address": data.full_address, "phone_number": '+84' + data.phone_number, "email": data.email, "password": <PASSWORD>, "password_confirmation": <PASSWORD>, "parish_id": data.parish_id } this.authService.signup(submitData).subscribe( () => { }, (error: any) => { this.showSpinner = false; throw error; } ); } } showPass() { this.showpass = !this.showpass; if (this.showpass) { this.type = 'text'; this.name = 'eye-off-outline' } else { this.type = 'password'; this.name = 'eye-outline' } } clickForgotPassword() { this.router.navigate(['auth-manager/forgot-password']); } checkMatchConfirmedPassword() { return this.formSignUp.get('password').value == this.formSignUp.get('confirmed_password').value; } private markFormGroupTouched(formGroup: FormGroup) { (<any>Object).values(formGroup.controls).forEach(control => { control.markAsTouched(); if (control.controls) { this.markFormGroupTouched(control); } }); } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { TabbarManagerPage } from './tabbar-manager.page'; const routes: Routes = [ { path: '', component: TabbarManagerPage, children: [ { path: 'main', children:[ { path: '', loadChildren: ()=> import('../main/main.module').then(m=>m.MainPageModule), } ] }, { path: 'social', children:[ { path: '', loadChildren: ()=> import('../community/community.module').then(m=>m.CommunityPageModule), } ] }, { path: 'personal', children:[ { path: '', loadChildren: ()=> import('../account-setting/account-setting.module').then(m=>m.AccountSettingPageModule), } ] }, ] } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class TabbarManagerPageRoutingModule {} <file_sep>import { QuestionaresService } from 'src/app/@app-core/http'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-rank', templateUrl: './rank.page.html', styleUrls: ['./rank.page.scss'], }) export class RankPage implements OnInit { headerCustom = { title: 'BẢNG XẾP HẠNG', background: 'transparent', color: '#fff' }; ranking: any = []; constructor( private QuestionaresService: QuestionaresService ) { } ngOnInit() { this.getRanking(); } getRanking() { this.QuestionaresService.getRanking().subscribe((data) => { this.ranking = data.app_users.slice(0, 10); let i = 1; for (let ranker of this.ranking) { ranker.index = i; if (ranker.thumb_image == null || ranker.thumb_image.url == null) { ranker.thumb_image = {}; ranker.thumb_image.url = 'https://i.imgur.com/edwXSJa.png'; } i++; } }) } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { SelectParishPage } from './select-parish.page'; const routes: Routes = [ { path: '', component: SelectParishPage } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class SelectParishPageRoutingModule {} <file_sep>import { IPageRequest } from "../global"; export interface IPope extends IPageRequest{ parish_id?; }<file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { map, catchError } from 'rxjs/operators'; import { requestQuery } from '../../utils'; import { APICONFIG } from '../@http-config'; import { IPageRequest } from '../global'; @Injectable({ providedIn: 'root' }) export class DonateService { constructor( private http: HttpClient) { } public donateByVisa(req) { return this.http.post(`${APICONFIG.DONATES.DONATE_VISA}`, req).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; })); } public donateByMoMo(req) { return this.http.post(`${APICONFIG.DONATES.DONATE_MOMO}`, req).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; })); } public prayByVisa(req) { return this.http.post(`${APICONFIG.PRAY.PRAY_VISA}`, req).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; })); } public prayByMoMo(req) { return this.http.post(`${APICONFIG.PRAY.PRAY_MOMO}`, req).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; })); } public registerDevice(req) { return this.http.post(`${APICONFIG.DEVICES.REGISTER}`, req).pipe( map((result) =>{ return result }), catchError((error)=>{ throw error }) ) } } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { catchError, map } from 'rxjs/operators'; import { APICONFIG, IPageRequest } from '..'; import { requestQuery } from '../../utils'; @Injectable() export class DioceseService { constructor(private http: HttpClient) { } public getAll(request: IPageRequest) { return this.http.get<any>(`${APICONFIG.DIOCESE.GET}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ); } public getDetail(id) { return this.http.get<any>(`${APICONFIG.DIOCESE.GET_DETAIL(id)}`).pipe( map(result => { return result; }), catchError(errorRes => { throw errorRes.error; }) ); } public getAttention(date: any) { return this.http.get<any>(`${APICONFIG.ATTENTION_LOG.GET(date)}`).pipe( map(result => { return result; }), catchError(errorRes => { throw errorRes.error; }) ); } public creatAttention(req: any) { return this.http.post<any>(`${APICONFIG.ATTENTION_LOG.CREATE}`, req).pipe( map((result)=> { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ) } } <file_sep>export * from './doctrine.service';<file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { catchError } from 'rxjs/operators'; import { AuthService, PATTERN } from 'src/app/@app-core/http'; import { LoadingService, ToastService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-forgot-password', templateUrl: './forgot-password.page.html', styleUrls: ['./forgot-password.page.scss'], }) export class ForgotPasswordPage implements OnInit { email: any = { email : '' } constructor( private router: Router, private toastService: ToastService, private authService: AuthService, private loadingService: LoadingService ) { } ngOnInit() { } goToVerification() { this.loadingService.present(); this.authService.forgotPassword({email: this.email.email}).subscribe((data) => { this.toastService.presentSuccess('Vui lòng kiểm tra mã OTP vừa gửi đến mail của bạn.'); this.loadingService.dismiss(); this.router.navigateByUrl('auth-manager/verification'); }) } getEmail(event) { this.email.email = event.target.value; } } <file_sep>import { Injectable } from '@angular/core'; // import { ToastrService } from 'ngx-toastr'; @Injectable() export class GlobalService { constructor( // private toastr: ToastrService, ) { } // convert base64/URLEncoded data component to a file dataURItoBlob(dataURI: any, fileName: string): File { var byteString; if (dataURI.split(',')[0].indexOf('base64') >= 0) byteString = atob(dataURI.split(',')[1]); else byteString = unescape(dataURI.split(',')[1]); // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // write the bytes of the string to a typed array var ia = new Uint8Array(byteString.length); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return new File([ia], fileName, { type: mimeString }); } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ArchdioceseDetailPage } from './archdiocese-detail.page'; const routes: Routes = [ { path: '', component: ArchdioceseDetailPage } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class ArchdioceseDetailPageRoutingModule {} <file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { DonateService, EventsService, IPageEvent, AccountService, IPageRequest, AuthService, ParishesService } from '../@app-core/http'; import { DateTimeService, ImageService, LoadingService } from '../@app-core/utils'; import { ToastController } from '@ionic/angular'; import { DioceseService } from '../@app-core/http/diocese'; @Component({ selector: 'app-pray', templateUrl: './pray.page.html', styleUrls: ['./pray.page.scss'], }) export class PrayPage implements OnInit { frmPray: FormGroup; error_messages = { 'amount': [ { type: 'require', message: 'This field must have a value for donate !' } ], } source_type: any; source_id: any; required_mess = false; name: any; message_purpose = ""; required_purpose = false; message = ""; avatar: any; img; getData:any; bishop_name; data: any; level = 'Linh'; type_page = 'pray'; headerCustom = { title: 'Xin lễ', background: '#e5e5e5' }; x: any; amount: any; setamount = 0; public myDate = new Date().toISOString(); constructor( public formBuilder: FormBuilder, private route: ActivatedRoute, private router: Router, public donateService: DonateService, public loadingService: LoadingService, public toastController: ToastController, public parishesService: ParishesService, public imageService: ImageService, private diocesesService: DioceseService, ) { this.frmPray = this.formBuilder.group({ note: new FormControl('', Validators.compose([ Validators.required, ])), day: new FormControl('', Validators.compose([ Validators.required, ])), amount: new FormControl('', []) }); } async presentToast(message) { const toast = await this.toastController.create({ message: message, duration: 1500 }); toast.present(); } ngOnInit() { this.loadingService.present(); this.name = localStorage.getItem('fullname'); } getUrl() { if (!this.img) { return `url("https://i.imgur.com/UKNky29.jpg")` } return `url(${this.img})` } ionViewWillEnter() { let url = window.location.href; if (url.includes('?')) { this.route.queryParams.subscribe(params => { this.data = JSON.parse(params['data']); this.source_id = this.data.id; }); } else { this.source_id = parseInt(localStorage.getItem('parish_id')); this.level = 'Linh'; this.source_type = 'Parish'; this.parishesService.getDetail(this.source_id).subscribe((data: any) => { this.loadingService.dismiss(); this.getData = data.parish; this.bishop_name = this.getData.priest_name; this.img = this.getData.thumb_image.url }) } if (this.data && this.data.source_type == 'Diocese') { this.source_type = this.data.source_type; this.level = 'Giám' this.loadingService.dismiss(); this.diocesesService.getDetail(this.source_id).subscribe((data: any) => { this.loadingService.dismiss(); this.getData = data.diocese; this.bishop_name = this.getData.bishop_name; this.img = this.getData.thumb_image.url; }) } else if (this.data && this.data.source_type == 'Parish') { this.source_type = this.data.source_type; this.level = 'Linh' this.parishesService.getDetail(this.source_id).subscribe((data: any) => { this.loadingService.dismiss(); this.getData = data.parish; this.bishop_name = this.getData.priest_name; this.img = this.getData.thumb_image.url }) } this.avatar = localStorage.getItem('avatar'); } callChangeDot() { let data = this.frmPray.get('amount').value; data = data.replace(/[^0-9]/gm, ''); data = data.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,') this.frmPray.controls['amount'].setValue(data); } imgNotFound(item) { !item?.thumb_image?.url && (item.thumb_image = { url: "https://i.imgur.com/UKNky29.jpg" }); } onSubmit() { this.amount = this.frmPray.get('amount').value; if (this.frmPray.get('amount').dirty || this.frmPray.get('amount').touched) { if (this.amount != undefined) { this.amount = this.amount.replace(/\,/g, '') } else { this.amount = ""; } if (this.amount.length != 0 && this.amount < 12000) { this.required_mess = true; this.message = 'Giá trị phải lớn hơn 12,000 vnd'; return; } else { this.required_mess = false; } } if (this.amount == "" || this.amount == undefined) { this.amount = this.setamount; } this.amount = parseInt(this.amount); var result = { pray_log: { "amount": this.amount, "app_link": "no link", "email": localStorage.getItem('email'), "note": this.frmPray.get('note').value, "source_type": this.source_type, "source_id": this.source_id, "pray_date": this.frmPray.get('day').value }, type_page: 'pray' } if (this.amount == 0) { result.pray_log['payment_type'] = 'visa_master'; this.donateService.prayByVisa(result.pray_log).subscribe((data) => { this.presentToast('Xin lễ thành công!'); }) } else { result.pray_log['token'] = ''; result.pray_log['payment_type'] = ''; this.router.navigate(['paymentmethods'], { queryParams: { data: JSON.stringify(result) } }) } } async goToDioceses() { const data = { type_page: this.type_page } this.router.navigate(['/dioceses'], { queryParams: { data: JSON.stringify(data) } }) } goToMap(lat, lng) { window.open('https://www.google.com/maps/dir/?api=1&destination=' + lat + ',' + lng); } }<file_sep>import { Component, OnInit } from '@angular/core'; import { VaticanService } from 'src/app/@app-core/http'; import { PopeService } from 'src/app/@app-core/http/pope'; import { IPageVatican } from 'src/app/@app-core/http/vatican/vatican.DTO'; @Component({ selector: 'app-parish-news', templateUrl: './parish-news.page.html', styleUrls: ['./parish-news.page.scss'], }) export class ParishNewsPage implements OnInit { headerCustom = { title: 'Tòa thánh Vatican' } list = [ { heading: 'Tin tức Vatican', items: [], category_id: 2, type: { general: 'news', detail: 'vatican' } }, { heading: 'Tiểu sử các Đức Giáo Hoàng', items: [], type: { general: 'story', detail: 'pope' } } ] pageRequest: IPageVatican = { page: 1, per_page: 4, category_id: 2 } pageRequestPope: IPageVatican = { page: 1, per_page: 4, // category_id: 2 } constructor( private vaticanService: VaticanService, private popeService: PopeService, // private categoryService:va ) { } ngOnInit() { this.vaticanService.getCategory().subscribe((data) => { data.vatican_news_categories.forEach(element => { if (element.name == "Vatican") { this.pageRequest.category_id = element.id; } // if (element.name == "Đức Giáo Hoàng") { // this.pageRequestPope.category_id = element.id // } }); this.getData(); }) } getVatican() { this.vaticanService.getAll(this.pageRequest).subscribe(data => { data.vatican_news.forEach(v => v.type = this.list[0].type); this.list[0].items = data.vatican_news; this.list[0].category_id = this.pageRequest.category_id }) } getPope() { this.popeService.getAll(this.pageRequestPope).subscribe(data => { data.pope_infos.forEach(v => v.type = this.list[1].type); this.list[1].items = data.pope_infos; }) } getData() { this.getVatican(); this.getPope(); } } <file_sep>import { SearchBarNavModule } from 'src/app/@modular/search-bar-nav/search-bar-nav.module'; import { HeaderModule } from './../../@modular/header/header.module'; import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { HymnVideoPageRoutingModule } from './hymn-video-routing.module'; import { HymnVideoPage } from './hymn-video.page'; import { BibleSongDetailComponent } from './bible-song-detail/bible-song-detail.component'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, HymnVideoPageRoutingModule, HeaderModule, SearchBarNavModule ], declarations: [HymnVideoPage, BibleSongDetailComponent] }) export class HymnVideoPageModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { PostService } from 'src/app/@app-core/http'; @Component({ selector: 'app-comment', templateUrl: './comment.page.html', styleUrls: ['./comment.page.scss'], }) export class CommentPage implements OnInit { headerCustom = { title: 'Bình luận' } id commentData constructor( private router: Router, private route: ActivatedRoute, private postService: PostService ) { } ngOnInit() { this.id = JSON.parse(localStorage.getItem('commentsID')) this.postService.showAllComment(this.id).subscribe((data:any)=>{ this.commentData = data.comments; this.commentData.forEach(element => { !element?.app_user?.thumb_image?.url && (element.app_user.thumb_image = { url: "assets/img/avatar.png" }); }); }); } }<file_sep>import { QuestionaresService } from './../../@app-core/http/questionares/questionares.service'; import { LoadingService } from './../../@app-core/utils/loading.service'; import { Component, OnInit } from "@angular/core"; import { Router } from "@angular/router"; import { AlertController, ModalController } from "@ionic/angular"; import { BehaviorSubject } from "rxjs"; import { ToastService } from "src/app/@app-core/utils"; import { CompleteQuestionPage } from "../complete-question/complete-question.page"; @Component({ selector: "app-question", templateUrl: "./question.page.html", styleUrls: ["./question.page.scss"], }) export class QuestionPage implements OnInit { musicType = true; questionTypeName = ''; heart = 3; score = 0; questionCounter = 0; answerValue = ""; answerKey = ""; questionsLength = 0; time: BehaviorSubject<string> = new BehaviorSubject("00:00"); timer: number; forTimer: any; questions = []; soundtrack1 = new Audio(); right = new Audio(); wrong = new Audio(); hasModal = false; rules = [ { rule: 'Người chơi chọn chủ đề hoặc cấp độ để bắt đầu trò chơi.' }, { rule: 'Mỗi lượt chơi sẽ có một số câu hỏi với 4 đáp án A, B, C, D (thời gian là 12s/1 câu). Người chơi chọn 1 trong 4 đáp án để trả lời câu hỏi.' }, { rule: 'Người chơi có 3 mạng, mỗi câu trả lời sai sẽ bị trừ 1 mạng. Đến khi hết 3 mạng sẽ kết thúc trò chơi.' }, { rule: 'Điểm sau khi kết thúc sẽ được tích lũy vào bảng xếp hạng.' } ] constructor( private alertCtrl: AlertController, private router: Router, private modalController: ModalController, private toastService: ToastService, private loadingService: LoadingService, private QuestionaresService: QuestionaresService ) { } ngOnInit() { } ionViewWillEnter() { this.loadingService.present(); this.checkQuestionType(); this.soundtrack1.play(); localStorage.setItem("score", "0"); } ionViewWillLeave() { this.stopTimer(); } async questionSetting() { let alertQuestionSetting = await this.alertCtrl.create({ message: "Lựa chọn", mode: "ios", buttons: [ { text: "Tiếp tục", }, { text: "Quay lại", handler: () => { this.router.navigate(["questionares/choose-question"]); }, }, { text: "Thoát", role: "destructive", handler: () => { this.questionQuit(); localStorage.removeItem('score'); }, }, ], }); await alertQuestionSetting.present(); } async questionQuit() { let alertQuestionSetting = await this.alertCtrl.create({ message: "Bạn có muốn thoát?", mode: "ios", buttons: [ { text: "Hủy", }, { text: "Thoát", role: "destructive", handler: () => { localStorage.removeItem("questionType"); localStorage.removeItem("questionTypeName"); this.router.navigate(["main/catechism-class"]); }, }, ], }); await alertQuestionSetting.present(); } async checkQuestionType() { if (localStorage.getItem("idTopic") == null && localStorage.getItem('idLevel') == null) { await this.loadingService.dismiss(); this.router.navigateByUrl('questionares'); return; } this.questionTypeName = localStorage.getItem('questionTypeName'); if (localStorage.getItem("idTopic")) { this.setUpQuestion('idTopic'); this.loadAudio(); return; } if (localStorage.getItem("idLevel")) { this.setUpQuestion('idLevel'); this.loadAudio(); return; } } setUpQuestion(idString) { this.QuestionaresService.getQuesTopic(JSON.parse(localStorage.getItem(idString))).subscribe((data) => { this.questions = data.questions; this.loadingService.dismiss(); this.questionsLength = data.questions.length; localStorage.setItem('questionsLength', this.questionsLength.toString()); this.startTimer(data.questions.length * 12); this.questions.push({ question: '', answer: { a: '', b: '', c: '', d: '', right_answer: '' }, thumb_image: { url: '' } }) }); localStorage.removeItem(idString) } setMusicType() { if (this.musicType == true) { this.soundtrack1.pause(); this.musicType = false; } else { this.soundtrack1.play(); this.musicType = true; } } loadAudio() { this.loadingService.present(); this.soundtrack1.src = "https://res.cloudinary.com/baodang359/video/upload/v1615538818/kito-music/soundtrack1_tgqm5n.mp3"; this.soundtrack1.load(); this.right.src = "https://res.cloudinary.com/baodang359/video/upload/v1615538813/kito-music/right_omlr5s.mp3"; this.right.load(); this.wrong.src = "https://res.cloudinary.com/baodang359/video/upload/v1615538813/kito-music/wrong_ghnyzp.mp3"; this.wrong.load(); } startTimer(duration) { this.timer = duration; this.forTimer = setInterval(() => { this.updateTimeValue(); }, 1000); } updateTimeValue() { let minutes: any = this.timer / 60; let seconds: any = this.timer % 60; minutes = String("0" + Math.floor(minutes)).slice(-2); seconds = String("0" + Math.floor(seconds)).slice(-2); const text = minutes + ":" + seconds; this.time.next(text); --this.timer; if (this.timer == 0) { this.stopTimer(); this.updateScore(); this.openCompleteQuestion(); this.toastService.presentFail("Hết giờ rồi!", 'top', 1000, 'danger'); } } stopTimer() { clearInterval(this.forTimer); this.soundtrack1.pause(); } btnActivate(e) { let answer = document.querySelectorAll(".answer"); answer.forEach((element) => { element.classList.remove("active-button"); }); e.target.classList.add("active-button"); } checkAnswerValue(item) { this.answerValue = item; } checkAnswerKey(object, value) { this.answerKey = (Object.keys(object).find((key) => object[key] === value)).toUpperCase(); } btnConfirm() { this.answerValue = ""; if (this.answerKey == this.questions[this.questionCounter].answer.right_answer) { this.score++; localStorage.setItem("score", JSON.stringify(this.score)); this.toastService.presentSuccess("Đúng rồi!", 'top', 1000, 'success'); this.right.play(); } else { this.heart--; this.toastService.presentFail("Sai rồi!", 'top', 1000, 'danger'); this.wrong.play(); } if (this.questionCounter >= this.questionsLength - 1 || this.heart < 0 || this.score == this.questionsLength) { this.heart = 0; this.updateScore(); this.openCompleteQuestion(); this.stopTimer(); this.soundtrack1.pause(); } if (this.questionCounter <= this.questionsLength) { this.questionCounter++; } } async openCompleteQuestion() { const modal = await this.modalController.create({ component: CompleteQuestionPage, cssClass: "my-custom-class", swipeToClose: false, }); await modal.present(); } toggleHasModal(bool) { this.hasModal = bool; } updateScore() { this.QuestionaresService.updateScore({ app_user: { score: this.score } }).subscribe((data) => { }) } }<file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { IonInfiniteScroll } from '@ionic/angular'; import { BishopService, IPageRequest, ParishesService, PopeService } from 'src/app/@app-core/http'; import { IPageParishes } from 'src/app/@app-core/http/parishes/parishes.DTO'; import { LoadingService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-information', templateUrl: './information.page.html', styleUrls: ['./information.page.scss'], }) export class InformationPage implements OnInit { @ViewChild('infiniteScroll') infiniteScroll: IonInfiniteScroll; headerCustom = { title: '' }; list = []; pageRequestPope: IPageRequest = { page: 1, per_page: 5 }; pageRequestParish: IPageParishes = { page: 1, per_page: 10, diocese_id: null } pageRequestBishop: IPageParishes = { page: 1, per_page: 10, diocese_id: null } dataParams = null; notFound = false; constructor( private route: ActivatedRoute, private popeService: PopeService, private router: Router, private parishService: ParishesService, private bishopService: BishopService, private loadingService: LoadingService ) { } ngOnInit() { this.loadingService.present(); this.getParams(); } getData(func?) { this.notFound = false; if (this.dataParams.id) { switch (this.dataParams.type.detail) { case 'parish': this.parishService.getAllWithDioceseId(this.pageRequestParish).subscribe(data => { this.notFound = true; this.loadingService.dismiss(); data.parishes.forEach(v => v.type = this.dataParams.type); this.list = this.list.concat(data.parishes); func && func(); this.pageRequestParish.page++; if (this.list.length >= data.meta.pagination.total_objects) { this.infiniteScroll.disabled = true; } }) break; case 'bishop': this.bishopService.getAll(this.pageRequestBishop).subscribe(data => { this.notFound = true; this.loadingService.dismiss(); data.bishop_infos.forEach(v => v.type = this.dataParams.type); this.list = this.list.concat(data.bishop_infos); func && func(); this.pageRequestBishop.page++; if (this.list.length >= data.meta.pagination.total_objects) { this.infiniteScroll.disabled = true; } }) break; } } else { switch (this.dataParams.type.detail) { case 'pope': this.popeService.getAll(this.pageRequestPope).subscribe(data => { this.notFound = true; this.loadingService.dismiss(); data.pope_infos.forEach(v => v.type = this.dataParams.type); this.list = this.list.concat(data.pope_infos); func && func(); this.pageRequestPope.page++; if (this.list.length >= data.meta.pagination.total_objects) { this.infiniteScroll.disabled = true; } }) break; } } } search(value: string) { if (typeof value != 'string') { return; } else if (!value) { delete this.pageRequestParish.search; delete this.pageRequestBishop.search; delete this.pageRequestPope.search; } else { if (this.dataParams.id == null) { this.pageRequestPope.search = value; } else if (this.dataParams.type.detail == 'parish') { this.pageRequestParish.search = value; } else if (this.dataParams.type.detail == 'bishop') { this.pageRequestBishop.search = value; } } this.reset(); this.getData(); } reset() { this.list = []; this.infiniteScroll.disabled = false; this.pageRequestPope.page = 1; this.pageRequestParish.page = 1; this.pageRequestBishop.page = 1; } getParams() { this.route.queryParams.subscribe(params => { this.dataParams = JSON.parse(params['data']); this.pageRequestBishop.diocese_id = this.dataParams.id; this.pageRequestParish.diocese_id = this.dataParams.id; switch (this.dataParams.type.general) { case 'info': this.headerCustom.title = 'Thông tin'; case 'parish': this.headerCustom.title = 'Giáo xứ'; break; case 'story': this.headerCustom.title = 'Tiểu sử'; break; } this.getData(); }).unsubscribe(); } loadMoreData(event) { this.getData(() => { event.target.complete(); }) } goToNewsDetail(item) { const data = { id: item.id, type: item.type } this.router.navigate(['/news-detail'], { queryParams: { data: JSON.stringify(data) } }) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-calendar-detail', templateUrl: './calendar-detail.page.html', styleUrls: ['./calendar-detail.page.scss'], }) export class CalendarDetailPage implements OnInit { headerCustom = { title: 'Lịch Công Giáo' }; data day dayName DATES = [ { name: 'THỨ 2', value: 1 }, { name: 'THỨ 3', value: 2 }, { name: 'THỨ 4', value: 3 }, { name: 'THỨ 5', value: 4 }, { name: 'THỨ 6', value: 5 }, { name: 'THỨ 7', value: 6 }, { name: '<NAME>', value: 0 }, ] constructor( private route: ActivatedRoute ) { } ngOnInit() { this.route.queryParams.subscribe((data: any) =>{ this.data = JSON.parse(data['data']) this.data['created_at'] = new Date (this.data['created_at']) this.data['date'] = new Date (this.data['date']) this.day = this.data['date'].getDay() console.log(this.data) this.DATES.forEach(i =>{ if(i.value == this.day) { this.dayName = i.name } }) }) } } <file_sep>import { IPageRequest } from "../global"; export interface IPageCalendar extends IPageRequest { cal_date?: string | Date; } export interface Day { valueView: string; value: any; }<file_sep>import { IPageRequest } from "../global"; export interface IPageCourse extends IPageRequest { course_group_id?:string; }<file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { ModalController } from '@ionic/angular'; import { AuthService } from 'src/app/@app-core/http'; import { LoadingService, ToastService } from 'src/app/@app-core/utils'; import { IDataNoti, PageNotiService } from '../@modular/page-noti/page-noti.service'; @Component({ selector: 'app-changepassword', templateUrl: './changepassword.page.html', styleUrls: ['./changepassword.page.scss'], }) export class ChangepasswordPage implements OnInit { formSubmit: FormGroup; check = false; message = ''; checkpn = false; messagepn = ''; count: any; constructor(private formBuilder: FormBuilder, private pageNotiService: PageNotiService, private router: Router, private loadService: LoadingService, private passwordModal: ModalController, private toastService:ToastService, private authService: AuthService) { this.formSubmit = this.formBuilder.group({ passwordcurrent: new FormControl('', Validators.required), passwordnew: new FormControl('', Validators.required), passwordconfirm: new FormControl('', Validators.required) }) } ngOnInit() { } async openModal(ev: any) { const popover = await this.passwordModal.create({ component: ChangepasswordPage, cssClass: 'modalPassword', }); return await popover.present(); } dismissModal() { this.passwordModal.dismiss(); } onSubmit() { const cp = this.formSubmit.value.passwordcurrent; const pn = this.formSubmit.value.passwordnew; const pc = this.formSubmit.value.passwordconfirm; if(cp==pn) { this.toastService.presentFail("Mật khẩu mới và mật khẩu cũ không được trùng!") return; } if (pn.length < 6) { this.checkpn = true; this.messagepn = 'Mật khẩu ít nhất 6 kí tự.' } else if (pn != pc) { this.check = true; this.checkpn = false; this.message = 'Mật khẩu không trùng khớp!' } else { this.check = false; const datapasing: IDataNoti = { title: 'SUCCESSFUL!', des: 'Change Password successful!', routerLink: '/main' } var ps = { "current_password": cp, "new_password": pn, "new_password_confirmation": pc } this.dismissModal() this.loadService.present() this.authService.resetPassword(ps).subscribe(data => { this.pageNotiService.setdataStatusNoti(datapasing); this.router.navigateByUrl('/page-noti'); this.loadService.dismiss(); }) } } async closeModalPassword() { this.passwordModal.dismiss(); } } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { map, catchError } from 'rxjs/operators'; import { IPageRequest, APICONFIG } from '..'; import { requestQuery, ToastService } from '../../utils'; import { DOCTRINE_CLASSES } from '../@http-config'; @Injectable({ providedIn: 'root' }) export class DoctrineService { constructor( private http: HttpClient, private toastService:ToastService ) { } public getAll(request: IPageRequest) { return this.http.get<any>(`${APICONFIG.DOCTRINE_CLASSES.GET}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ); } public getDetail(id) { return this.http.get<any>(`${APICONFIG.DOCTRINE_CLASSES.GET_DETAIL(id)}`).pipe( map(result => { return result; }), catchError(errorRes => { throw errorRes.error; }) ); } public getCateckism(request: IPageRequest) { return this.http.get<any>(`${APICONFIG.CATECKISM.GET}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ); } public register(payload) { return this.http.post<any>(`${APICONFIG.DOCTRINE_CLASSES.REGISTER}`, payload).pipe( map((result) => { this.toastService.presentSuccess(DOCTRINE_CLASSES.REGIEST); return result; }), catchError((errorRes) => { throw errorRes.error; })); } public unregister(payload) { return this.http.post<any>(`${APICONFIG.DOCTRINE_CLASSES.UNREGISTER}`, payload).pipe( map((result) => { this.toastService.presentSuccess(DOCTRINE_CLASSES.UNREGIEST); return result; }), catchError((errorRes) => { throw errorRes.error; })); } } <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ModalController } from '@ionic/angular'; import { AuthService } from 'src/app/@app-core/http'; import { ModalDonateComponent } from '../modal-donate/modal-donate.component'; @Component({ selector: 'app-list-dioceses', templateUrl: './list-dioceses.component.html', styleUrls: ['./list-dioceses.component.scss'], }) export class ListDiocesesComponent implements OnInit { @Input() data: any; @Input() flag_parishes_diocese: string; @Input() type_page; constructor( private modalCtrl: ModalController, public router: Router, private authService: AuthService ) { } ngOnInit() { } async goToDetail() { if(this.type_page === 'parish_news' && this.flag_parishes_diocese === 'parish') { localStorage.setItem('tempParishId', this.data.id); this.router.navigateByUrl('news'); } else if(this.type_page === 'parish_news') { const dataToParish = { id: this.data.id, type: { detail: 'parish_news', general: 'news' }, type_page: 'parish_news' } this.router.navigate(['parishes'], { queryParams: { data: JSON.stringify(dataToParish) } }) } else if (this.flag_parishes_diocese === 'diocese') { const popover = await this.modalCtrl.create({ component: ModalDonateComponent, swipeToClose: true, cssClass: 'modalDonate', componentProps: { diocese_id: this.data.id, type_page: this.type_page} }); return await popover.present(); } else if(this.flag_parishes_diocese === 'parish' && this.type_page === 'donate') { const data = { id: this.data.id, source_type: 'Parish', type_page: this.type_page, } this.router.navigate(['donate'], { queryParams: { data: JSON.stringify(data) } }) } else if(this.flag_parishes_diocese === 'parish' && this.type_page === 'pray') { const data = { id: this.data.id, source_type: 'Parish', type_page: this.type_page, } this.router.navigate(['pray'], { queryParams: { data: JSON.stringify(data) } }) } } } <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-main-slide', templateUrl: './main-slide.component.html', styleUrls: ['./main-slide.component.scss'], }) export class MainSlideComponent implements OnInit { @Input() data: any; slideOptions = { initialSlide: 0, loop: true, autoplay: { disableOnInteraction: false } }; constructor( private router: Router ) { } ngOnInit() { } seeMore() { const data = { type: this.data.type, id: this.data.category_id } switch (this.data.type.general) { case 'news': this.router.navigate(['/news'], { queryParams: { data: JSON.stringify(data) } }) break; case 'info': case 'story': this.router.navigate(['/information'], { queryParams: { data: JSON.stringify(data) } }) break; } } goToItemDetail(item) { const data = { id: item.id, type: item.type } this.router.navigate(['/news-detail'], { queryParams: { data: JSON.stringify(data) } }) } } <file_sep>import { Pipe, PipeTransform } from '@angular/core'; import { isNull, isUndefined } from 'util'; import { Day } from '../http/calendar/calendar.DTO'; @Pipe({ name: 'dayPipe' }) export class DayPipe implements PipeTransform { transform(value: any, arrWeekend: Day[]): string { if (isNull(value) || isUndefined(value) || value === '') { return 'unknown'; } else { const index = arrWeekend.findIndex(x => x.value.toString() === value.toString()); return arrWeekend[index].valueView; } } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ChooseQuestionDetailComponent } from './choose-question-detail/choose-question-detail.component'; import { ChooseQuestionPage } from './choose-question.page'; const routes: Routes = [ { path: '', component: ChooseQuestionPage }, { path: 'detail', component: ChooseQuestionDetailComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class ChooseQuestionPageRoutingModule { } <file_sep>export const SUCCESS = { GET: 'Lấy dữ liệu thành công', CREATE: 'Tạo mới thành công', EDIT: 'Chỉnh sửa thành công', DELETE: 'Xoá thành công', AUTH: { LOGOUT: 'Đăng xuất thành công', LOGIN: 'Đăng nhập thành công', }, }; export const FAIL = { LOGOUT: 'Đăng xuất thất bại', }; export const LOADING = { REGIEST: "Đang đăng ký", UNREGIEST: "Đang hủy đăng ký" } export const STATUS = { SUCCESS: 'Thành công!', FAIL: 'Lỗi, vui lòng kiểm tra lại!', WARNING: 'Cảnh báo!' }; export const ARLET = { DATE: { WRONG_FORMAT: 'Ngày không hợp lệ! Ngày hợp lệ là ngày có định dạng ngày/tháng/năm' }, USER: { PASSWORD_ENOUGH_LENGTH: '<PASSWORD>ẩ<PASSWORD> tối thiểu 6 kí tự', PASSWORD_NOT_VALID: 'Mật khẩu không khớp, vui lòng kiểm tra lại' } }; export const TOARST = { COLOR: { primary: 'primary', secondary: 'secondary', tertiary: 'tertiary', success: 'success', warning: 'warning', danger: 'danger', light: 'light', medium: 'medium', dark: 'dark' }, POSITION: { bottom: 'bottom', top: 'top' } } export const DOCTRINE_CLASSES = { REGIEST: "Đăng ký thành công", UNREGIEST: "Đã hủy đăng ký", } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { BishopService, DioceseNewsService } from 'src/app/@app-core/http'; import { DioceseService } from 'src/app/@app-core/http/diocese'; import { IPageParishes } from 'src/app/@app-core/http/parishes/parishes.DTO'; import { LoadingService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-archdiocese-detail', templateUrl: './archdiocese-detail.page.html', styleUrls: ['./archdiocese-detail.page.scss'], }) export class ArchdioceseDetailPage implements OnInit { headerCustom = { title: '' }; archdiocese = { id: '', name: '', diocese_type: 'archdiocese', thumb_image: { url: '' } } title = ''; list = [ { id: '', heading: 'Tin tức ', items: [], type: { general: 'news', detail: 'dioceseNews' } }, { id: '', heading: 'Tiểu sử các Đức Giám Mục', items: [], type: { general: 'story', detail: 'bishop' } } ] pageRequest: IPageParishes = { page: 1, per_page: 4, diocese_id: '' } constructor( private route: ActivatedRoute, private diocesesService: DioceseService, private router: Router, private dioceseNewsService: DioceseNewsService, private bishopService: BishopService, private loadingService: LoadingService ) { } ngOnInit() { this.loadingService.present(); this.getData(); } getArchdiocese(id) { this.diocesesService.getDetail(id).subscribe(data => { this.archdiocese = data.diocese; }) } getDioceseNews() { this.dioceseNewsService.getAll(this.pageRequest).subscribe(data => { data.diocese_news.forEach(d => { d.type = { general: 'news', detail: 'dioceseNews' }; }); this.list[0].items = data.diocese_news; }) } getBishops() { this.bishopService.getAll(this.pageRequest).subscribe(data => { this.loadingService.dismiss(); data.bishop_infos.forEach(d => { d.type = { general: 'story', detail: 'bishop' }; }); this.list[1].items = data.bishop_infos; }) } getData() { this.route.queryParams.subscribe(params => { const dataParams = JSON.parse(params['data']); this.title = dataParams.diocese.type == 'diocese' ? 'giáo phận' : 'tổng giáo phận'; this.list[0].heading += this.title; this.headerCustom.title = dataParams.diocese.name; this.pageRequest.diocese_id = dataParams.diocese.id; this.list.forEach(item => item.id = dataParams.diocese.id); this.getArchdiocese(dataParams.diocese.id); this.getDioceseNews(); this.getBishops(); }).unsubscribe(); } goToDiocese() { const data = { id: this.archdiocese.id, type: { general: 'info', detail: 'diocese' } } this.router.navigate(['/news-detail'], { queryParams: { data: JSON.stringify(data) } }) } goToParishes() { const data = { id: this.archdiocese.id, type: { general: 'parish', detail: 'parish' } } this.router.navigate(['/information'], { queryParams: { data: JSON.stringify(data) } }) } } <file_sep>import { Injectable } from '@angular/core'; import { Observable, BehaviorSubject } from 'rxjs'; import { AccountService, PERMISSIONS } from './http'; @Injectable() export class StorageService { private userSub: BehaviorSubject<any> = new BehaviorSubject<any>(null); constructor( private accountService: AccountService, ) { } public clear() { this.userSub.next(null); } public get infoAccount(): Observable<any> { return this.userSub.asObservable(); } public setInfoAccount() { if (localStorage.getItem('Authorization') !== null) { return this.accountService.getAccounts().subscribe((data: any) => { localStorage.setItem('phoneNumber', data.app_user.phone_number); localStorage.setItem('email', data.app_user.email); localStorage.setItem('diocese_id', data.app_user.diocese_id); localStorage.setItem('fullname', data.app_user.full_name); localStorage.setItem('parish_id', data.app_user.parish_id); localStorage.setItem('language', JSON.stringify({ name: 'Tiếng Việt', id: 0 })); this.userSub.next(data.user); }) } else { const data = { user: { fullname: "Guest", email: "<EMAIL>", role: PERMISSIONS[0].value, phone_number: "000000" } } return this.userSub.next(data.user); } } } <file_sep>import { Injectable } from '@angular/core'; import { SpeechRecognition } from '@ionic-native/speech-recognition/ngx'; import { Platform } from '@ionic/angular'; import { AuthService } from '../http'; @Injectable() export class SpeechRecognitionService { public voiceResult = ''; constructor( public speechRecognition: SpeechRecognition, public PlatForm: Platform, public authService: AuthService, ) { } checkPermission() { this.PlatForm.ready().then(() => { this.speechRecognition.requestPermission().then( () => this.startVoiceRecord()) }) } startVoiceRecord() { if (localStorage.getItem('voice')) { localStorage.removeItem('voice'); } this.speechRecognition.startListening().subscribe((matches: Array<string>) => { this.voiceResult = matches[0]; localStorage.setItem('voice', this.voiceResult) }) } }<file_sep>export * from './requestQuery'; export * from './connectivity.service'; export * from './loading.service'; export * from './date-time.service'; export * from './toast.service'; export * from './speech-recognition.service'; export * from './audio-manager.service'; export * from './onesignal.service' export * from './geolocation.service'; export * from './camera.service'; export * from './image.service'; export * from './network.service'; export * from './social-sharing.service'<file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { CatechismClassPage } from './catechism-class.page'; const routes: Routes = [ { path: '', component: CatechismClassPage }, { path: 'catechism', loadChildren: () => import('./catechism/catechism.module').then( m => m.CatechismPageModule) }, { path: 'catechism-marriage', loadChildren: () => import('./catechism-marriage/catechism-marriage.module').then( m => m.CatechismMarriagePageModule) }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class CatechismClassPageRoutingModule {} <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { QuestionaresPage } from './questionares.page'; const routes: Routes = [ { path: '', component: QuestionaresPage }, { path: 'choose-question', loadChildren: () => import('./choose-question/choose-question.module').then( m => m.ChooseQuestionPageModule) }, { path: 'question', loadChildren: () => import('./question/question.module').then( m => m.QuestionPageModule) }, { path: 'complete-question', loadChildren: () => import('./complete-question/complete-question.module').then( m => m.CompleteQuestionPageModule) }, { path: 'rule', loadChildren: () => import('./rule/rule.module').then( m => m.RulePageModule) }, { path: 'rank', loadChildren: () => import('./rank/rank.module').then( m => m.RankPageModule) } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class QuestionaresPageRoutingModule {} <file_sep>import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { CommunityPageRoutingModule } from './community-routing.module'; import { CommunityPage } from './community.page'; import { HeaderModule } from '../@modular/header/header.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, CommunityPageRoutingModule, HeaderModule, ReactiveFormsModule, ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ], declarations: [CommunityPage] }) export class CommunityPageModule {} <file_sep>import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { IonicModule } from '@ionic/angular'; import { SelectParishPage } from './select-parish.page'; describe('SelectParishPage', () => { let component: SelectParishPage; let fixture: ComponentFixture<SelectParishPage>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ SelectParishPage ], imports: [IonicModule.forRoot()] }).compileComponents(); fixture = TestBed.createComponent(SelectParishPage); component = fixture.componentInstance; fixture.detectChanges(); })); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { Injectable } from '@angular/core'; @Injectable() export class DateTimeService { public DAYS = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]; public VIETNAMESE_DAYS = [ 'CN', 'Hai', 'Ba', 'Tư', 'Năm', 'Sáu', 'Bảy', ]; public VIETNAMESE_DAYS_2 = [ 'Chủ nhật', 'Thứ hai', 'Thứ ba', 'Thứ tư', 'Thứ năm', 'Thứ sáu', 'Thứ bảy', ]; public MONTHS = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; public MONTHS_VIETNAMESE = [ 'Tháng 1', 'Tháng 2', 'Tháng 3', 'Tháng 4', 'Tháng 5', 'Tháng 6', 'Tháng 7', 'Tháng 8', 'Tháng 9', 'Tháng 10', 'Tháng 11', 'Tháng 12', ]; constructor() { } // Thursday, 03 January 2021 public getDateString(date: Date) { return `${this.DAYS[date.getDay()]}, ${date.getDate()} ${this.MONTHS[date.getMonth()]} ${date.getFullYear()}`; } // 2021-01-01 public getDateString2(date: Date) { return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`; } // Thursday, 03 January 2021 public getDateString3(date: Date) { return `${this.VIETNAMESE_DAYS_2[date.getDay()]} - ${date.getDate()}.${date.getMonth()}.${date.getFullYear()}`; } // 5:00 public getTimeString(date: Date) { const minutes = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes(); return `${date.getHours()}:${minutes}`; } public numberWithCommas(str) { let parts = str.toString().split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, "."); return parts.join(","); } public isEmptyObject(obj) { return obj && Object.keys(obj).length === 0 && obj.constructor === Object; } public daysInMonth(month, year) { return new Date(year, month, 0).getDate(); } } <file_sep>import * as _ from 'lodash'; export const requestQuery = (queries: object): string => { if (!queries) { return ''; } let result: object = JSON.parse(JSON.stringify(queries)); result = _.keys(result).map((key) => { return result[key] !== null || result[key] !== undefined ? `${key}=${result[key]}` : ''; }).filter(x => x); return _.values(result).join('&'); }; <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { BibleSongDetailComponent } from './bible-song-detail/bible-song-detail.component'; import { HymnVideoPage } from './hymn-video.page'; const routes: Routes = [ { path: '', component: HymnVideoPage }, { path: 'BibleSongdetail/:id', component: BibleSongDetailComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class HymnVideoPageRoutingModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { NavController, Platform } from '@ionic/angular'; import { LoadingService, CameraService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-popoverimage', templateUrl: './popoverimage.component.html', styleUrls: ['./popoverimage.component.scss'], }) export class PopoverimageComponent implements OnInit { constructor( private router: Router, private loadingService: LoadingService, private platform: Platform, private navController: NavController, private CameraService: CameraService ) { } avatar = ''; subscribe: any; count = 0; ngOnInit() { this.avatar = localStorage.getItem('avatar'); this.subscribe = this.platform.backButton.subscribeWithPriority(99999, () => { if (this.router.url === '/account') { this.count++; if (this.count == 1) { this.CameraService.popoverImage.dismiss(); this.count = 0; } } else { this.navController.back(); } }) } getUrl() { return `url(${this.avatar})` } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { IonInfiniteScroll } from '@ionic/angular'; import { IPageCategory, IPageProduct, StoreService } from '../@app-core/http'; @Component({ selector: 'app-store', templateUrl: './store.page.html', styleUrls: ['./store.page.scss'], }) export class StorePage implements OnInit { headerCustom = { title: 'Cửa hàng' }; pageRequestCategories: IPageCategory = { page: 1, per_page: 20, parish_id: localStorage.getItem('parish_id') } sortType = { newest: 'newest', topSeller: 'top-seller', priceDesc: 'price-desc', priceAsc: 'price-asc' } currentCategoryId = '' pageRequestProducts: IPageProduct = { page: 1, per_page: 6, category_id: this.currentCategoryId, search: '', sort: this.sortType.newest } categories = [] products = [] constructor( private storeService: StoreService ) { } @ViewChild('infiniteScroll') infinityScroll: IonInfiniteScroll; ngOnInit() { const parishId = localStorage.getItem('tempParishId'); this.getCategories(); } ionViewWillEnter() { } getCategories() { this.storeService.getAllCategories(this.pageRequestCategories).subscribe(data => { this.categories = data.categories; this.currentCategoryId = this.categories[0].id; this.categories = data.categories this.getProducts(); }) localStorage.setItem('tempParishId', this.pageRequestCategories.parish_id); } Activecategory(item) { this.currentCategoryId = item.id this.getProducts() } getProducts() { this.pageRequestProducts.category_id = this.currentCategoryId; this.storeService.getAllProducts(this.pageRequestProducts).subscribe(data => { console.log(data) this.products = data.products }) } loadMoreProducts() { } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { QuestionDataService } from '../choose-question.service'; import { Location } from "@angular/common"; @Component({ selector: 'app-choose-question-detail', templateUrl: './choose-question-detail.component.html', styleUrls: ['./choose-question-detail.component.scss'], }) export class ChooseQuestionDetailComponent implements OnInit { data; headerCustom = { title: '', background: 'transparent', color: '#fff' }; constructor( private questionService: QuestionDataService, private location: Location, private router: Router, ) { } ngOnInit() { this.questionService.currentMessage.subscribe((data) => { if (data == "") { this.router.navigateByUrl('questionares') return } this.data = data; }) } gotoQuestion() { if (this.data.level) { localStorage.setItem('idLevel', this.data.level); localStorage.removeItem("idTopic") } else { localStorage.setItem('idTopic', this.data.id); localStorage.removeItem("idLevel") } this.router.navigate(['questionares/question']); } goBack() { this.location.back() } } <file_sep>import { listLazyRoutes } from '@angular/compiler/src/aot/lazy_routes'; import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { AlertController } from '@ionic/angular'; import { DateTimeService, GeolocationService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-cart', templateUrl: './cart.page.html', styleUrls: ['./cart.page.scss'], }) export class CartPage implements OnInit { headerCustom = { title: 'Giỏ hàng' }; cart = []; shipCost = 5000; paymentMethods = [ { srcIcon: 'assets/icon/dollar.svg', name: 'Tiền mặt', id: 0 }, { srcIcon: 'assets/icon/visa.svg', name: 'VISA/MASTER', id: 1 }, { srcIcon: 'assets/icon/visa.svg', name: 'MOMO', id: 2 } ]; currentPaymentMethodId = 0; hasPaymentModal = false; paymentSelectElement: any; phone_number = null; address; phone_temp; note = null; frm: FormGroup; constructor( public dateTimeService: DateTimeService, public formBuilder: FormBuilder, private router: Router, private geolocationSerivce: GeolocationService, private alert: AlertController ) { this.frm = this.formBuilder.group({ address: new FormControl('', Validators.compose([ Validators.required, ])), phone_number: new FormControl('', Validators.compose([ Validators.required, ])), note: new FormControl('', Validators.compose([ Validators.required, ])), }); } ngOnInit() { this.getCart(); this.phone_number = localStorage.getItem('phoneNumber'); this.address = localStorage.getItem('address'); if (!localStorage.getItem('address')) { this.presentAlert('Cập nhật', 'Lấy địa chỉ của bạn!'); } } async presentAlert(header: string, text: string) { const alert = await this.alert.create({ header: header, message: text, mode: 'ios', buttons: [ { text: 'Hủy', role: 'cancel', cssClass: 'secondary', handler: () => { this.reTakeLocation(); } }, { text: 'Đồng ý', handler: () => { this.reTakeLocation(); } } ] }); await alert.present(); } check(): boolean { return !this.cart.length || this.address == null; } reTakeLocation() { this.geolocationSerivce.getCurrentLocation(); this.address = this.geolocationSerivce.customerLocation.address; localStorage.setItem('address', this.address) } ionViewDidEnter() { this.paymentSelectElement = document.querySelector('.payment-method-container'); } getCart() { this.cart = JSON.parse(localStorage.getItem('cart')) || []; } setCart() { localStorage.setItem('cart', JSON.stringify(this.cart)); } changeAddress() { document.getElementById('address').focus(); } changePhoneNumber() { document.getElementById('phone_number').focus(); } changeNote() { document.getElementById('note').focus(); } decreaseAmount(item) { if (item.amount > 1) { item.amount--; this.setCart(); } } increaseAmount(item) { if (item.amount < 999) { item.amount++; this.setCart(); } } calPrice(item) { return item.amount * item.price; } calTotalPrice() { return this.cart.reduce((acc, item) => acc + this.calPrice(item), 0); } removeItem(item) { this.cart.splice(this.cart.indexOf(item), 1); this.setCart(); } goBackToStore() { this.router.navigateByUrl('main/store'); } toggleHasPaymentModal(value) { this.hasPaymentModal = value; } onCheckClickOutsidePaymentSelect(e) { if (this.paymentSelectElement && !this.paymentSelectElement.contains(e.target)) { this.toggleHasPaymentModal(false); } } onClickPaymentModal() { event.stopPropagation(); } changePayment(paymentMethod) { this.currentPaymentMethodId = paymentMethod.id; this.toggleHasPaymentModal(false); } goToCheckout() { if (localStorage.getItem(this.address)) { localStorage.removeItem('address'); } if (localStorage.getItem(this.phone_temp)) { localStorage.removeItem('phone_temp'); } localStorage.setItem('address', this.address); localStorage.setItem('phone_temp', this.phone_number); localStorage.setItem('note', this.note); const data = { paymentMethod: this.paymentMethods[this.currentPaymentMethodId] } this.router.navigate(['main/store/cart/checkout'], { queryParams: { data: JSON.stringify(data) } }) } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; import { AlertController, IonContent, IonInfiniteScroll, ModalController } from '@ionic/angular'; import { IPageCategory, IPageProduct, StoreService } from 'src/app/@app-core/http'; import { DateTimeService, LoadingService } from 'src/app/@app-core/utils'; import { AddStoreComponent } from 'src/app/@modular/add-store/add-store.component'; @Component({ selector: 'app-store', templateUrl: './store.page.html', styleUrls: ['./store.page.scss'], }) export class StorePage implements OnInit { // @ViewChild(IonContent) ionContent: IonContent; @ViewChild('infiniteScroll') infinityScroll: IonInfiniteScroll; headerCustom = { title: 'Cửa hàng' }; list = []; cart = []; hasSetting = false; categories = []; currentCategoryId = null; notFound = false; sortType = { newest: 'newest', topSeller: 'top-seller', priceDesc: 'price-desc', priceAsc: 'price-asc' } pageRequestCategories: IPageCategory = { page: 1, per_page: 20, parish_id: localStorage.getItem('parish_id') } pageRequestProducts: IPageProduct = { page: 1, per_page: 6, category_id: this.currentCategoryId, search: '', sort: this.sortType.newest } constructor( public dateTimeService: DateTimeService, private router: Router, private modalController: ModalController, private storeService: StoreService, private alertController: AlertController, private loadingService: LoadingService ) { } ngOnInit() { this.getCategories(); } ionViewWillEnter() { this.getCart(); const parishId = localStorage.getItem('tempParishId'); if (parishId) { if (parishId !== this.pageRequestCategories.parish_id) { this.pageRequestCategories.parish_id = parishId; this.categories = []; this.reset(); this.getCategories(); } } } ionViewWillLeave() { this.resetAmount(); } getProducts() { this.notFound = false; this.pageRequestProducts.category_id = this.currentCategoryId; const tempCategoryId = this.currentCategoryId; console.log(this.pageRequestProducts) this.storeService.getAllProducts(this.pageRequestProducts).subscribe(data => { this.notFound = true; this.loadingService.dismiss(); if (tempCategoryId !== this.currentCategoryId) { return; } data.products.forEach(product => { product.unit_price = 'đ'; product.amount = 0; }) this.list = this.list.concat(data.products); this.pageRequestProducts.page++; // this.infinityScroll.disabled = false; console.log() if (this.list.length >= data.meta.pagination.total_objects) { // this.infinityScroll.disabled = true; // this.infinityScroll.complete(); }else { // this.infinityScroll.disabled = false } }) } changeCategory(category) { this.setHasSetting(false); if (this.currentCategoryId !== category.id) { this.pageRequestProducts.page = 1; this.currentCategoryId = category.id; this.infinityScroll.disabled = false this.list = []; // this.ionContent.scrollToTop(0).then(() => { this.getProducts(); //}) } } getCategories() { this.storeService.getAllCategories(this.pageRequestCategories).subscribe(data => { this.categories = data.categories; this.currentCategoryId = this.categories[0].id; this.getProducts(); }) localStorage.removeItem('cart'); this.cart = []; localStorage.setItem('tempParishId', this.pageRequestCategories.parish_id); } resetAmount() { this.list.forEach(item => item.amount = 0); } setHasSetting(bool) { this.hasSetting = bool; } toggleHasSetting() { this.hasSetting = !this.hasSetting; } getCart() { this.cart = JSON.parse(localStorage.getItem('cart')) || []; } setCart() { localStorage.setItem('cart', JSON.stringify(this.cart)); } calTotalItem() { const total = this.cart.reduce((acc, item) => acc + item.amount, 0); return total <= 99 ? total : 99; } goToCart() { this.router.navigateByUrl('main/store/cart'); } async openAddModal(item) { const modal = await this.modalController.create({ component: AddStoreComponent, cssClass: 'add-store-modal', swipeToClose: true, componentProps: { item: item } }); modal.present(); modal.onWillDismiss().then(data => { if (data.role == 'ok') { item.amount = data.data; this.getCart(); } }) } decreaseAmount(item) { if (item.amount > 0) { item.amount--; } for (let i of this.cart) { if (i.id == item.id) { i.amount = item.amount; i.amount <= 0 && this.cart.splice(this.cart.indexOf(i), 1); break; } } this.setCart(); } increaseAmount(item) { if (item.amount < 999) { item.amount++; } for (let i of this.cart) { if (i.id == item.id) { i.amount = item.amount; break; } } this.setCart(); } sort(sortType = this.sortType.newest) { this.loadingService.present(); this.setHasSetting(false); this.pageRequestProducts.sort = sortType; this.reset(); this.getProducts(); } loadMoreProducts() { console.log(1) this.getProducts(); } onScrollContent() { this.setHasSetting(false); } async alertGoToOtherStore() { const alert = await this.alertController.create({ header: 'Xem cửa hàng khác', mode: 'ios', buttons: [ { text: 'Hủy', role: 'cancel' }, { text: 'Đồng ý', handler: () => { this.router.navigateByUrl('main/store/choose-store'); } } ] }) await alert.present(); } search(value: string) { if (typeof value !== 'string') { return } if (!value) { delete this.pageRequestProducts.search; } else { this.pageRequestProducts.search = value; } this.reset(); this.getProducts(); } reset() { this.list = []; this.pageRequestProducts.page = 1; this.infinityScroll.disabled = false; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { NavController } from '@ionic/angular'; import { AccountService, DioceseService, IPageRequest, ParishesService } from 'src/app/@app-core/http'; import { IPageParishes } from 'src/app/@app-core/http/parishes/parishes.DTO'; import { LoadingService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-select-diocese', templateUrl: './select-diocese.page.html', styleUrls: ['./select-diocese.page.scss'], }) export class SelectDiocesePage implements OnInit { headerCustom = { title: '' }; list = []; pageRequestDiocese: IPageRequest = { page: 1, per_page: 10 } pageRequestParish: IPageParishes = { page: 1, per_page: 10, diocese_id: null } type = null; constructor( private route: ActivatedRoute, private navController: NavController, private dioceseService: DioceseService, private parishService: ParishesService, private loadingService: LoadingService, private accountService: AccountService ) { } ngOnInit() { this.route.queryParams.subscribe(params => { const dataParams = JSON.parse(params['data']); this.type = dataParams.type; switch (this.type) { case 'diocese': this.headerCustom.title = 'Chọn giáo phận'; this.getDioceses(); break; case 'parish': this.headerCustom.title = 'Chọn giáo xứ'; this.getParishes(localStorage.getItem('diocese_id')); break; } }) } getDioceses() { this.dioceseService.getAll(this.pageRequestDiocese).subscribe(data => { this.list = data.dioceses; localStorage.setItem('diocese_id', data.dioceses[0].id) }) } getParishes(id) { this.pageRequestParish.diocese_id = id; this.parishService.getAllWithDioceseId(this.pageRequestParish).subscribe(data => { this.list = data.parishes; }) } setItem(item, type) { localStorage.setItem(type, JSON.stringify(item.id)); } goBack() { this.navController.back(); } choose(item) { switch (this.type) { case 'diocese': const prevDioceseId = JSON.parse(localStorage.getItem('diocese_id')); if (prevDioceseId !== item.id) { this.loadingService.present(); this.accountService.updateProfile({ diocese_id: item.id }).subscribe(() => { this.parishService.getAllWithDioceseId({ page: 1, per_page: 1, diocese_id: item.id }).subscribe( data => { const parish = data.parishes[0]; if (parish) { this.accountService.updateProfile({ parish_id: parish.id }).subscribe( () => { this.setItem(item, 'diocese_id'); this.setItem(parish, 'parish_id'); this.loadingService.dismiss(); this.goBack(); }, (err) => { this.loadingService.dismiss(); } ) } }, () => { this.loadingService.dismiss(); this.goBack(); } ), () => { this.loadingService.dismiss(); } }) } else { this.goBack(); } break; case 'parish': const prevParishId = JSON.parse(localStorage.getItem('parish_id')); if (prevParishId !== item.id) { this.loadingService.present(); this.accountService.updateProfile({ parish_id: item.id }).subscribe( () => { this.setItem(item, 'parish_id'); this.loadingService.dismiss(); this.goBack(); }, () => { this.loadingService.dismiss(); } ) } else { this.goBack(); } break; } } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { QuestionaresPageRoutingModule } from './questionares-routing.module'; import { QuestionaresPage } from './questionares.page'; import { HeaderModule } from '../@modular/header/header.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, QuestionaresPageRoutingModule, HeaderModule ], declarations: [QuestionaresPage] }) export class QuestionaresPageModule {} <file_sep>import { ActivatedRoute } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { DoctrineService, IPageRequest, LOADING } from 'src/app/@app-core/http'; import { LoadingService } from 'src/app/@app-core/utils'; import { AlertController } from '@ionic/angular'; @Component({ selector: 'app-catechism-marriage', templateUrl: './catechism-marriage.page.html', styleUrls: ['./catechism-marriage.page.scss'], }) export class CatechismMarriagePage implements OnInit { headerCustom: any; list = []; id; public pageResult: IPageRequest = { page: 1, per_page: 1000, total_objects: 0, search: '', }; constructor( private route: ActivatedRoute, private doctrineService: DoctrineService, private loadingService: LoadingService, private alertController: AlertController ) { } ngOnInit() { this.route.queryParams.subscribe(data => { this.headerCustom = { title: data.data }; this.id = data.id }) this.getDataName(); } getDataName() { if (this.id === "1") { this.doctrineService.getAll(this.pageResult).subscribe((data: any) => { this.list = data.doctrine_classes; }) return } this.doctrineService.getCateckism(this.pageResult).subscribe((data: any) => { this.list = data.doctrine_classes; }) } formatTime(date) { date = new Date(date); var hours = date.getHours(); var minutes = date.getMinutes(); hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + 'h' + ':' + minutes return strTime } register(id) { this.loadingService.present() let data = { "register_detail": { "doctrine_class_id": id } } this.doctrineService.register(data).subscribe((data) => { this.ngOnInit(); this.loadingService.dismiss(); }) } unregister(id) { this.loadingService.present(); let data = { "register_detail": { "doctrine_class_id": id } } this.doctrineService.unregister(data).subscribe((data) => { this.ngOnInit(); this.loadingService.dismiss(); }) } submit(type, id) { if (type === true) { this.register(id); } else { this.unregister(id); } } async openAlertRegister(id, type, text) { const alert = await this.alertController.create({ cssClass: 'my-custom-class', header: text + ' lớp học', mode: 'ios', buttons: [ { text: 'Đóng', }, { text: text, handler: () => { this.submit(type, id); } } ] }); await alert.present(); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { PostService } from 'src/app/@app-core/http'; import { UploadPhotoService } from 'src/app/@app-core/utils/upload-photo.service'; import { CameraService, LoadingService, SocialSharingService } from '../@app-core/utils'; @Component({ selector: 'app-community', templateUrl: './community.page.html', styleUrls: ['./community.page.scss'], }) export class CommunityPage implements OnInit { headerCustom = { title: 'Cộng đồng giáo dân' } posts: any clickComment = false CommentIDSelected commentContent imageurl repplyCommentID showfullcontenttext = "Xem thêm..." listComment = [] commentIdReply constructor( private postService: PostService, private uploadService: UploadPhotoService, private router: Router, private loadingService: LoadingService, private socialSharingSerivce: SocialSharingService, private cameraService: CameraService ) { } type = '' ngOnInit() { this.getData() } getData() { this.loadingService.present() this.postService.getAllPosts().subscribe(data => { this.loadingService.dismiss() this.posts = data.posts; this.posts.forEach(element => { !element?.owner?.thumb_image?.url && (element.owner.thumb_image = { url: "assets/img/avatar.png" }); element.showAll = false if (element.liked) { element.nameIcon = 'assets/icon/liked.svg' } else { element.nameIcon = 'assets/icon/like.svg' } }); }); } showMore(post) { post.showAll = true } showLess(post) { post.showAll = false } clickOutSideComment() { this.clickComment = false } likeToogle(post) { if (post.liked) { post.liked = false post.nameIcon = 'assets/icon/like.svg' this.postService.dislike(post.id).subscribe(() => { }); } else { post.liked = true post.nameIcon = 'assets/icon/liked.svg' this.postService.addLike(post.id).subscribe(() => { }); } } showcomment(id) { localStorage.setItem('commentsID', id); this.router.navigate(['/community/comment']); } comment(id) { this.CommentIDSelected = id; this.clickComment = this.clickComment ? false : true this.type = 'add' } sendComment() { this.clickComment = false if (this.type == 'add') { this.postService.addComment(this.CommentIDSelected, this.commentContent, this.imageurl).subscribe((data) => { this.getData() this.commentContent = '' }) } else if (this.type == 'reply') { this.postService.repplycomment(this.CommentIDSelected, this.commentContent, this.imageurl, this.commentIdReply).subscribe((data) => { this.getData() this.commentContent = '' }) } } Share() { this.socialSharingSerivce.share() } replyComment(id, ID) { this.clickComment = true this.type = 'reply' this.CommentIDSelected = id this.commentIdReply = ID } loadImg() { this.imageurl = this.uploadService.uploadPhoto(); console.log('url', this.imageurl) var image this.cameraService.getAvatarUpload(image) } }<file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-rule', templateUrl: './rule.page.html', styleUrls: ['./rule.page.scss'], }) export class RulePage implements OnInit { headerCustom = { title: '<NAME>', background: 'transparent', color: '#002d63' }; rules = [ { rule: 'Người chơi chọn chủ đề hoặc cấp độ để bắt đầu trò chơi.' }, { rule: 'Mỗi lượt chơi sẽ có một số câu hỏi với 4 đáp án A, B, C, D (thời gian là 12s/1 câu). Người chơi chọn 1 trong 4 đáp án để trả lời câu hỏi.' }, { rule: 'Người chơi có 3 mạng, mỗi câu trả lời sai sẽ bị trừ 1 mạng. Đến khi hết 3 mạng sẽ kết thúc trò chơi.' }, { rule: 'Điểm sau khi kết thúc sẽ được tích lũy vào bảng xếp hạng.' } ] constructor() { } ngOnInit() { } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { BishopService, DioceseNewsService, DioceseService, ParishesService, VaticanService } from 'src/app/@app-core/http'; import { PopeService } from 'src/app/@app-core/http/pope'; import { LoadingService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-news-detail', templateUrl: './news-detail.page.html', styleUrls: ['./news-detail.page.scss'], }) export class NewsDetailPage implements OnInit { headerCustom = { title: '' }; data = null; map = false; constructor( private route: ActivatedRoute, private vaticanService: VaticanService, private popeService: PopeService, private dioceseService: DioceseService, private parishService: ParishesService, private dioceseNewsService: DioceseNewsService, private bishopService: BishopService, private loading: LoadingService ) { } ngOnInit() { this.loading.present(); this.route.queryParams.subscribe(params => { const dataParams = JSON.parse(params['data']); switch (dataParams.type.general) { case 'news': this.headerCustom.title = 'Tin tức'; break; case 'info': this.headerCustom.title = 'Thông tin'; break; case 'story': this.headerCustom.title = 'Tiểu sử'; case 'parish': this.headerCustom.title = 'Thông tin'; break; } switch (dataParams.type.detail) { case 'vatican': this.vaticanService.getDetail(dataParams.id).subscribe(data => { this.loading.dismiss(); this.data = data.vatican_news; }) break; case 'pope': this.popeService.getDetail(dataParams.id).subscribe(data => { this.loading.dismiss(); this.data = data.pope_info; }) break; case 'diocese': this.map = true; this.dioceseService.getDetail(dataParams.id).subscribe(data => { this.loading.dismiss(); this.data = data.diocese; }) break; case 'parish': this.map = true; this.parishService.getDetail(dataParams.id).subscribe(data => { this.map = true; this.loading.dismiss(); this.data = data.parish; }) break; case 'parish_news': this.parishService.getParishNewsByid(dataParams.id).subscribe(data => { this.loading.dismiss(); this.data = data.parish_news; }) break; case 'dioceseNews': this.dioceseNewsService.getDetail(dataParams.id).subscribe(data => { this.loading.dismiss(); this.data = data.diocese_news; }) break; case 'bishop': this.bishopService.getDetail(dataParams.id).subscribe(data => { this.loading.dismiss(); this.data = data.bishop_info; }) break; } }) } imgnotFound(item) { !item?.thumb_image?.url && (item.thumb_image = { url: "https://i.imgur.com/UKNky29.jpg" }); } goToMap() { window.open('https://www.google.com/maps/dir/?api=1&destination=' + this.data.location.lat + ',' + this.data.location.long); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-introduce', templateUrl: './introduce.page.html', styleUrls: ['./introduce.page.scss'], }) export class IntroducePage implements OnInit { isShowLicense = false; constructor() { } headerCustom = { title: 'Giới thiệu' }; ngOnInit() { } showLicense() { if(this.isShowLicense == false) { this.isShowLicense = true; } else this.isShowLicense = false; } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { CatechismMarriagePageRoutingModule } from './catechism-marriage-routing.module'; import { CatechismMarriagePage } from './catechism-marriage.page'; import { HeaderModule } from 'src/app/@modular/header/header.module'; import { SearchBarNavModule } from 'src/app/@modular/search-bar-nav/search-bar-nav.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, CatechismMarriagePageRoutingModule, HeaderModule, SearchBarNavModule ], declarations: [CatechismMarriagePage] }) export class CatechismMarriagePageModule {} <file_sep>export * from './questionares.service';<file_sep>export * from './store.service'; export * from './store.DTO';<file_sep>export * from './global.service'; export * from './global.DTO';<file_sep>import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Location } from "@angular/common"; import { HymnMusicService } from 'src/app/@app-core/http'; import { Howl } from 'howler'; import { IonRange } from '@ionic/angular'; import { LoadingService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-bible-song-detail', templateUrl: './bible-song-detail.component.html', styleUrls: ['./bible-song-detail.component.scss'], }) export class BibleSongDetailComponent implements OnInit { headerCustom = { title: '' }; public id; data; hDisplay: any; mDisplay: any; progress = 0; songs = []; activeSong = null; player: Howl = null; activeScrollLyric = true; shuffledSongs = []; progressInterval = null; timeFlag = 0; mixed = false; notFound = false; REPEATING_TYPE = { NONE: 0, REPEAT_ONE: 1, REPEAT_ALL: 2 } repeatingType = this.REPEATING_TYPE.REPEAT_ALL; @ViewChild('contentLyric') lyricContent: ElementRef; @ViewChild('range', { static: false }) range: IonRange; constructor( private route: ActivatedRoute, private location: Location, private hymnVideoServicer: HymnMusicService, private loadingService: LoadingService ) { } ngOnInit() { this.route.params.subscribe((params) => { if (params.id !== undefined) { this.id = params.id; this.getItem(); } else { this.location.back() } }); } getItem() { this.loadingService.present(); this.hymnVideoServicer.getBibleSongDetail(this.id).subscribe((res: any) => { this.data = res.bible_song; this.start(this.data); this.hymnVideoServicer.getAllBibleSong({ page: 1, per_page: 1000 }).subscribe((data) => { this.songs = data.bible_songs }) this.loadingService.dismiss(); }) } onEndSong() { switch (this.repeatingType) { case this.REPEATING_TYPE.REPEAT_ONE: this.player.play(); break; case this.REPEATING_TYPE.REPEAT_ALL: this.next(); break; } } start(song) { this.activeSong = song; if (this.player) { this.player.stop(); } this.player = new Howl({ src: [song.url], html5: true, onplay: () => { // this.timeFlag = 0; this.updateProgress(); let maxTime = this.player.duration(); let heightLyric = this.lyricContent.nativeElement.offsetHeight; let InitHeight = 0; let that = this; let timeLoading = heightLyric / (maxTime - 20); // let time = this.timeFlag; let contentLyricDOM = document.querySelector('.lyric'); function myLoop() { setTimeout(function () { // if (!that.activeScrollLyric) { // setTimeout(() => { // that.activeScrollLyric = true; // that.timeFlag = Math.round(Number(that.player.seek())); // myLoop(); // }, 2000); // } that.timeFlag += 1; if (that.timeFlag > 20) { contentLyricDOM.scrollTop = (that.timeFlag) + timeLoading; // InitHeight = (that.timeFlag - 20) + timeLoading; } if (that.timeFlag <= 20) { contentLyricDOM.scrollTop = 0; } if (that.timeFlag < maxTime && that.player.playing() && that.activeScrollLyric) { // console.log('that.timeFlag', that.timeFlag, '/', timeLoading); myLoop(); } }, 1000) } myLoop(); }, onend: () => { this.onEndSong(); } }); this.player.play(); } togglePlayer() { if (this.player.playing()) { this.player.pause(); this.timeFlag--; } else { this.player.play(); } } toggleMixed() { this.mixed = !this.mixed; } changeRepeatingType() { switch (this.repeatingType) { case this.REPEATING_TYPE.REPEAT_ALL: this.repeatingType = this.REPEATING_TYPE.REPEAT_ONE; break; case this.REPEATING_TYPE.REPEAT_ONE: this.repeatingType = this.REPEATING_TYPE.NONE; break; case this.REPEATING_TYPE.NONE: this.repeatingType = this.REPEATING_TYPE.REPEAT_ALL; break; } } getCurrentListAndIndex() { let list = []; let index = null; if (this.mixed) { list = this.shuffledSongs index = list.indexOf(this.activeSong); if (index === -1) { list = this.shuffledSongs; index = list.indexOf(this.activeSong); } } else { list = this.songs; index = list.indexOf(this.activeSong); console.log(index); if (index === -1) { list = this.songs; index = list.indexOf(this.activeSong); } } return { list: list, index: index }; } next() { const { list, index } = this.getCurrentListAndIndex(); this.data = list[index + 1]; this.start(index === list.length + 1 ? list[0] : list[index + 1]); // this.activeLyric = list[index + 1].lyric; } prev() { const { list, index } = this.getCurrentListAndIndex(); this.data = list[index - 1]; this.start(index > 0 ? list[index - 1] : list[list.length - 1]) // this.activeLyric = list[index - 1].lyric; } seek() { let newValue = +this.range.value; let duration = this.player.duration(); this.player.seek(duration * (newValue / 100)); this.timeFlag = Math.round(duration * (newValue / 100)); } updateProgress() { clearInterval(this.progressInterval); this.progressInterval = setInterval(() => { const seek = this.player.seek(); this.progress = (<any>seek / this.player.duration()) * 100 || 0; }, 1000) } secondsToHms(d) { d = Number(d); const h = Math.floor(d / 3600); const m = Math.floor(d % 3600 / 60); const s = Math.floor(d % 3600 % 60); this.hDisplay = h > 0 ? h : ''; var mDisplay = m > 0 ? m : ''; mDisplay = mDisplay > 9 ? mDisplay : '0' + mDisplay + ':'; var sDisplay = s > 0 ? s : ''; sDisplay = sDisplay > 9 ? sDisplay : '0' + sDisplay; return this.hDisplay + mDisplay + sDisplay; } shuffleSongs() { this.shuffledSongs = this.shuffleArr(this.songs); } shuffleArr(arr) { const tempArr = [...arr]; for (let i = tempArr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [tempArr[i], tempArr[j]] = [tempArr[j], tempArr[i]]; } return tempArr; } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; import { IonSlides } from '@ionic/angular'; import { SlideService } from 'src/app/@modular/slide/slide.service'; import { IDataSlide } from '../page-noti/page-noti.service'; @Component({ selector: 'app-slide', templateUrl: './slide.component.html', styleUrls: ['./slide.component.scss'], }) export class SlideComponent implements OnInit { @ViewChild ('mySlider',{ static: true }) slides: IonSlides; slideOpts = { initialSlide: 1, speed: 400 }; constructor( // private slideService: SlideService, private router: Router ) { } public title; public image; public routerLink = ''; public label = ''; clicked = 0; ngOnInit() { // if(this.clicked == 0) { // this.title = "Service and Event"; // this.image = "assets/img/slide1.svg"; // this.label = 'NEXT'; // } } Skip() { this.router.navigate(['auth-manager/login']); } goNext(){ this.slides.slideNext(); } } <file_sep>export * from './diocese-news.service';<file_sep>export * from './pope.service';<file_sep>import { Role } from '../account/account.DTO'; export const DROPDOWNNOTFOUND = 'Không tìm thấy kết quả'; export const PageNavigation = { page: 1, amount: 10, typesort: '1', search: '', totalAmount: 0, totalPage: 0 }; export const COUNTPERPAGE = [ { number: 10, name: 10 }, { number: 20, name: 20 }, { number: 30, name: 30 }, { number: 40, name: 40 }, { number: 50, name: 50 } ]; export const TIMEOUTSEARCH = 500; export const PERMISSIONS = [ { valueView: 'Guest', value: 'guest' }, { valueView: 'Standard', value: 'standard' }, { valueView: 'Premium', value: 'premium' } ]; export const PRODUCT_TYPE = [ { valueView: 'Đồ ăn', value: 'food' }, { valueView: 'Thức uống', value: 'drink' } ]; export const STATUS_ORDER = [ { valueView: 'Đang xác nhận', value: 'pending' }, { valueView: 'Đã xác nhận', value: 'confirmed' }, { valueView: 'Đang giao hàng', value: 'delivering' }, { valueView: 'Giao hàng thành công', value: 'delivery_sucessed' }, { valueView: 'Giao hàng thất bại', value: 'delivery_failed' } ] export const STATUS_BOOKING = [ { valueView: 'Đang xác nhận', value: 'pending' }, { valueView: 'Đã xác nhận', value: 'confirmed' }, { valueView: 'Hủy đặt chỗ', value: 'reject' }, ] export const AREA_TYPE = [ { valueView: 'coffee', value: 'coffee' }, { valueView: 'game', value: 'game' }, { valueView: 'buffet', value: 'buffet' }, ] export const STATUS_SERVICE = [ { valueView: 'Sẵn sàng', value: 'ready' }, { valueView: 'Tạm khóa', value: 'locked' } ] <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ModalController } from '@ionic/angular'; import { DateTimeService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-add-store', templateUrl: './add-store.component.html', styleUrls: ['./add-store.component.scss'], }) export class AddStoreComponent implements OnInit { @Input() item: any; amount = 1; cart = []; constructor( public dateTimeService: DateTimeService, private modalController: ModalController, private router: Router ) { } ngOnInit() { this.getCart(); } decreaseAmount() { if (this.amount > 1) { this.amount--; } } increaseAmount() { if (this.amount < 999) { this.amount++; } } dismiss() { this.modalController.dismiss(); } getCart() { this.cart = JSON.parse(localStorage.getItem('cart')) || []; } setCart() { localStorage.setItem('cart', JSON.stringify(this.cart)); } addToCart() { let duplicated = false; for (let i = 0; i < this.cart.length; i++) { if (this.cart[i].id == this.item.id) { this.cart[i].amount += this.amount; this.amount = this.cart[i].amount; duplicated = true; break; } } if (!duplicated) { this.item.amount = this.amount; this.cart.push(this.item); } this.setCart(); this.modalController.dismiss(this.amount, 'ok'); } calTotalItem() { const total = this.cart.reduce((acc, item) => acc + item.amount, 0); return total <= 99 ? total : 99; } goToCart() { this.modalController.dismiss(); this.router.navigateByUrl('main/store/cart'); } } <file_sep># Công Giáo VN<file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-setting-languages', templateUrl: './setting-languages.page.html', styleUrls: ['./setting-languages.page.scss'], }) export class SettingLanguagesPage implements OnInit { headerCustom = { title: 'Ngôn ngữ' }; languages = [ { name: 'Tiếng Việt', id: 0 }, { name: 'English', id: 1 }, ]; selectedLanguage = { name: 'Việt Nam', id: 0 }; constructor() { } ngOnInit() { this.getLanguage(); } getLanguage() { this.selectedLanguage = JSON.parse(localStorage.getItem('language')) || { name: 'Việt Nam', id: 0 }; } setLanguage(language) { localStorage.setItem('language', JSON.stringify(language)); } } <file_sep>import { DioceseService } from './../@app-core/http/diocese/diocese.service'; import { Component, OnInit, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService, DonateService, ParishesService, VaticanService } from '../@app-core/http'; import { AlertController, IonInfiniteScroll, ModalController, NavController, Platform } from '@ionic/angular'; import { AccountService } from '../@app-core/http/account/account.service'; import { GeolocationService, LoadingService, OneSignalService, ToastService } from '../@app-core/utils'; import { IPageVatican } from '../@app-core/http/vatican/vatican.DTO'; import { IPageRequest } from 'src/app/@app-core/http/global/global.DTO'; import { IPageParishes } from 'src/app/@app-core/http/parishes/parishes.DTO'; import { OneSignal } from '@ionic-native/onesignal/ngx'; @Component({ selector: 'app-main', templateUrl: './main.page.html', styleUrls: ['./main.page.scss'], }) export class MainPage implements OnInit { @ViewChild(IonInfiniteScroll) infinityScroll: IonInfiniteScroll; name = ''; avatar = ''; menu = [ { name: '(Tổng) <NAME>', thumbImage: 'assets/img/menu/tonggiaophan.svg', desUrl: 'main/tonggiaophan', fullWidth: true }, { name: 'Tin tức giáo xứ', thumbImage: 'assets/img/menu/tintuc.svg', desUrl: 'news', fullWidth: true }, { name: 'Chi tiết giờ lễ', thumbImage: 'assets/img/menu/chitietgiole.svg', desUrl: 'main/prayer-time', }, { name: '<NAME>', thumbImage: 'assets/img/menu/lophocgiaoly.svg', desUrl: 'main/catechism-class', }, // { // name: '<NAME>', // thumbImage: 'assets/img/menu/donggop.svg', // desUrl: 'donate', // }, // { // name: '<NAME>', // thumbImage: 'assets/img/menu/xinle.svg', // desUrl: 'pray', // }, { name: '<NAME>', thumbImage: 'assets/img/menu/lichconggiao.svg', desUrl: 'main/calendar', }, { name: '<NAME>', thumbImage: 'assets/img/menu/cuahang.svg', desUrl: 'main/store', }, { name: '<NAME>', thumbImage: 'assets/img/menu/thanhca.svg', desUrl: 'main/hymn-music', }, { name: '<NAME>', thumbImage: 'assets/img/menu/baigiang.svg', desUrl: 'main/hymn-video', }, ] vaticanList = { items: [], type: { general: 'news', detail: 'vatican' } } subscribe: any; public alertPresented = false; count = 0; interval: any; pageRequestDioceses: IPageRequest = {}; onseSignalAppId = '17a2acbf-854f-4011-97b8-43f2640b7312' googleProjectId = 'kitoapp-312008' device_id = '5af57365-d47c-4f17-bae0-06447b6d8f72ic' token_id = '' pageRequestParishes: IPageParishes = { diocese_id: 0, } constructor( private router: Router, private OneSignalService: OneSignalService, private accountService: AccountService, private authService: AuthService, public modalCtrl: ModalController, public vaticanService: VaticanService, private loading: LoadingService, private platform: Platform, private alertController: AlertController, private toarst: ToastService, private navController: NavController, private geolocationSerivce: GeolocationService, private diocesesService: DioceseService, private parishesService: ParishesService, public oneSignal: OneSignal, public donateService: DonateService ) { this.getTokenID(); } ionViewWillEnter() { // this.autoJoinEvent(); // this.checkAvatar(); } ngOnInit() { this.geolocationSerivce.getCurrentLocationNoLoading(); this.OneSignalService.startOneSignal(); this.getVatican(); this.blockBackBtn(); } checkAvatar() { this.name = localStorage.getItem('fullname'); this.accountService.getAccounts().subscribe(data => { this.name = data.app_user.full_name; if (data.app_user.thumb_image == null) { data.app_user['thumb_image'] = "https://i.imgur.com/edwXSJa.png"; this.avatar = data.app_user.thumb_image; localStorage.setItem('avatar', this.avatar); } else if (data.app_user.thumb_image.url == null) { data.app_user['thumb_image'] = "https://i.imgur.com/edwXSJa.png"; this.avatar = data.app_user.thumb_image; localStorage.setItem('avatar', this.avatar); } else { this.avatar = data.app_user.thumb_image.url; localStorage.setItem('avatar', this.avatar); } }) } blockBackBtn() { this.subscribe = this.platform.backButton.subscribeWithPriority(99999, () => { if (this.router.url === '/main') { this.count++; if (this.count == 1) { this.toarst.presentSuccess('Nhấn lần nữa để thoát!'); } else { this.presentAlert(); } setTimeout(() => { this.count = 0; }, 2000); } else { this.navController.back(); } }) } autoJoinEvent() { let dateObj = new Date(); let currentDay = dateObj.toISOString().substr(0, 10); this.diocesesService.getAttention(currentDay).subscribe((dataCalendar) => { for (let calendar of dataCalendar.calendars) { if (calendar.date.slice(0, 10) == currentDay && calendar.joined == false) { this.parishesService.getAll(this.pageRequestParishes).subscribe((dataParishes) => { let timeOut, timeClear = 0; if (parseInt(localStorage.getItem('timeOut')) > 0) { timeOut = parseInt(localStorage.getItem('timeOut')) + 1; } else timeOut = 0; if (localStorage.getItem('isRepeat') == 'true') { this.repeatAlert(); } clearInterval(this.interval); this.interval = setInterval(() => { this.geolocationSerivce.getCurrentLocationNoLoading(); if (timeOut >= 1200) { let currentTime = dateObj.getHours() + ":" + dateObj.getMinutes(); let attention_log = { cal_time: currentDay + ' ' + currentTime, long: parseFloat(localStorage.getItem('lng')), lat: parseFloat(localStorage.getItem('lat')) } this.diocesesService.creatAttention({ attention_log }).subscribe((data) => { clearInterval(this.interval); if (data.message == 'Thành công!') { this.presentAlertJoinEvent(data.message); } else localStorage.removeItem('timeOut'); }) } for (let parish of dataParishes.parishes) { parish.location == null ? parish.location = [] : parish.location let tempDistance = this.geolocationSerivce.distanceFromUserToPointMet( localStorage.getItem('lat'), localStorage.getItem('lng'), parish.location.lat, parish.location.long, ) if (tempDistance - 30 <= 0) { timeOut++; break; } } localStorage.setItem('timeOut', timeOut.toString()); if (timeClear == 99) { console.clear(); } timeClear++; }, 1500) }) break; } } }) } async repeatAlert() { const alert = await this.alertController.create({ header: 'Giữ ứng dụng luôn được bật trong vòng 30 phút để tự động điểm danh khi gần nhà thờ', mode: 'ios', buttons: [ { text: 'Đồng ý', handler: () => { } }, { text: 'Không nhắc lại', handler: () => { localStorage.setItem('isRepeat', 'false') } } ] }); await alert.present(); } async presentAlertJoinEvent(data) { const alert = await this.alertController.create({ header: 'Điểm danh tự động: ' + data, mode: 'ios', backdropDismiss: false, buttons: [ { text: 'Đồng ý', handler: () => { localStorage.removeItem('timeOut'); } } ] }); await alert.present(); } async presentAlert() { this.alertPresented = true; const alert = await this.alertController.create({ cssClass: 'logout-alert', header: 'Bạn có muốn thoát ứng dụng ?', mode: 'ios', buttons: [ { text: 'Hủy', handler: () => { this.alertPresented = false; return; } }, { text: 'Đồng ý', handler: () => { localStorage.removeItem('isRepeat'); navigator['app'].exitApp(); } }, ] }); await alert.present(); } getVatican() { const pageRequest: IPageVatican = { page: 1, per_page: 4, category_id: 9 } this.vaticanService.getAll(pageRequest).subscribe(data => { this.loading.dismiss(); data.vatican_news.forEach(v => v.type = this.vaticanList.type); this.vaticanList.items = data.vatican_news; }) } goToDetail(item) { if (item.desUrl == 'donate') { const data = { type: 'donate' } this.authService.sendData(data) this.router.navigateByUrl(item.desUrl); } else if (item.desUrl == 'pray') { const data = { type: 'pray' } this.authService.sendData(data) this.router.navigateByUrl(item.desUrl); } else if (item.desUrl == 'news') { const data = { id: localStorage.getItem('parish_id'), type: { detail: 'parish_news', general: 'news' } } this.router.navigate(['/news'], { queryParams: { data: JSON.stringify(data) } }) } else this.router.navigateByUrl(item.desUrl); } getTokenID() { if (this.platform.is('cordova')) { if (this.platform.is('android')) { this.oneSignal.startInit(this.onseSignalAppId, this.googleProjectId) } else if (this.platform.is('ios')) { this.oneSignal.startInit(this.onseSignalAppId) } this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.Notification) this.oneSignal.handleNotificationReceived().subscribe(() => { // do something when notification is receive }) this.oneSignal.handleNotificationOpened().subscribe(result => { // do something when a notification is opened }) this.oneSignal.endInit() this.oneSignal.getIds().then(identity => { this.token_id = identity.pushToken this.device_id = identity.userId this.saveDeviceID(); }) } } saveDeviceID() { const param = { "register_device": { "token": <PASSWORD> } } this.donateService.registerDevice(param).subscribe(() => { }) } goToAccountSetting() { this.router.navigateByUrl('account-setting'); } }<file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { ChooseStorePageRoutingModule } from './choose-store-routing.module'; import { ChooseStorePage } from './choose-store.page'; import { HeaderModule } from 'src/app/@modular/header/header.module'; import { SearchBarNavModule } from 'src/app/@modular/search-bar-nav/search-bar-nav.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, ChooseStorePageRoutingModule, HeaderModule, SearchBarNavModule ], declarations: [ChooseStorePage] }) export class ChooseStorePageModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { AlertController, ModalController, PopoverController } from '@ionic/angular'; import { AccountService, PATTERN } from '../@app-core/http'; import { CameraService, ImageService, LoadingService, ToastService } from '../@app-core/utils'; import { ChangepasswordPage } from '../changepassword/changepassword.page'; @Component({ selector: 'app-account', templateUrl: './account.page.html', styleUrls: ['./account.page.scss'], }) export class AccountPage implements OnInit { image_avatar: any; avatar = ''; headerCustom = { title: 'Thông tin cá nhân' }; activatedInput = false; loadedData = false; form: FormGroup; lastForm = {}; isUpdating = false; validationMessages = { full_name: [ { type: 'required', message: 'Name is required.' } ], phone_number: [ { type: 'required', message: 'Phone number is required.' }, { type: 'pattern', message: 'Phone number is invalid.' }, ], email: [ { type: 'required', message: 'Email is required.' }, { type: 'pattern', message: 'Email is invalid.' }, ], } constructor( private fb: FormBuilder, public popoverController: PopoverController, private accountService: AccountService, private passwordModal: ModalController, private loadingService: LoadingService, private toastService: ToastService, public imageService: ImageService, private alertCtrl: AlertController, private cameraService: CameraService, private router: Router, ) { } ngOnInit() { this.initForm(); this.getData(); } ngDoCheck() { this.avatar = localStorage.getItem('avatar') } ionViewWillEnter() { this.avatar = localStorage.getItem('avatar') } initForm() { this.form = this.fb.group({ avatar: new FormControl(''), full_name: new FormControl('', Validators.required), birthday: new FormControl(''), phone_number: new FormControl('', Validators.compose([ Validators.required, Validators.pattern(PATTERN.PHONE_NUMBER_VIETNAM_FULL) ])), email: new FormControl('', Validators.compose([ Validators.required, Validators.pattern(PATTERN.EMAIL) ])), }); } async avatarSetting() { let alertAvatarSetting = await this.alertCtrl.create({ message: 'Cài đặt ảnh đại diện', mode: 'ios', buttons: [ { text: 'Xem ảnh đại diện', handler: () => { this.cameraService.viewAvatar(); } }, { text: "Thay đổi ảnh đại diện", handler: () => { this.router.navigateByUrl('/account-setting/change-avatar'); } }, { text: 'Xóa ảnh đại diện', handler: () => { this.cameraService.removeAvatar(); } }, { text: 'Đóng', role: 'destructive', }, ] }); await alertAvatarSetting.present(); } async openModalPassword() { const popover = await this.passwordModal.create({ component: ChangepasswordPage, cssClass: 'modalPassword', }); return await popover.present(); } activateInput() { this.activatedInput = true; this.lastForm = this.form.value; } deactivateInput() { this.activatedInput = false; this.form.patchValue(this.lastForm); } getData() { this.accountService.getAccounts().subscribe(data => { data.app_user.birthday; this.form.patchValue(data.app_user); this.loadedData = true; this.loadingService.dismiss(); }); } updateInfo() { this.loadingService.present(); let data = this.form.value; this.accountService.updateProfile(data).subscribe((data) => { localStorage.setItem('fullname', data.app_user.full_name); this.activatedInput = false; this.loadingService.dismiss(); this.toastService.presentSuccess('Cập nhật thành công !'); }); } canUpdate() { return JSON.stringify(this.lastForm) !== JSON.stringify(this.form.value) && this.form.valid; } } <file_sep>import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; import { IonContent, IonSlides } from '@ionic/angular'; import { CalendarService, EventsService, IPageEvent, ParishesService } from 'src/app/@app-core/http'; import { DateTimeService, LoadingService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-prayer-time', templateUrl: './prayer-time.page.html', styleUrls: ['./prayer-time.page.scss'], }) export class PrayerTimePage implements OnInit { @ViewChild('slides', { static: false }) slides: IonSlides; @ViewChild(IonContent) ionContent: IonContent; @ViewChild('fixed', { static: false }) fixedEl: ElementRef; slideOptions = { initialSlide: 0, autoHeight: true }; pageReq: IPageEvent = { calendar_id: null, parish_id: null } parish = null; dateList = []; activeDateItemId; fixedElHeight = 0; constructor( public dateTimeService: DateTimeService, private router: Router, private eventsService: EventsService, private calendarService: CalendarService, private parishService: ParishesService, private loading: LoadingService ) { } ngOnInit() { this.loading.present(); this.initDateList(); this.getData(localStorage.getItem('parish_id')); } ionViewWillEnter() { const dateItemId = localStorage.getItem('dateItemId'); if (dateItemId) { this.changeSegment(dateItemId); localStorage.removeItem('dateItemId'); } const parishId = localStorage.getItem('tempParishId'); if (parishId) { this.getData(parishId); localStorage.removeItem('tempParishId'); } } ionViewDidEnter() { this.fixedEl && (this.fixedElHeight = this.fixedEl.nativeElement.offsetHeight); } initDateList() { const now = new Date(); for (let i = 0; i < 7; i++) { let nextDate: any = new Date(now); nextDate.setDate(nextDate.getDate() + i); this.dateList.push({ id: i, date: nextDate, color: '', name: '', events: [] }) this.activeDateItemId = this.dateList[0].id; } } checkDate(date) { return parseInt(date); } getParish() { this.parishService.getDetail(this.pageReq.parish_id).subscribe(data => { this.loading.dismiss(); this.parish = data.parish; }) } getEvents() { this.calendarService.getByWeek(new Date()).subscribe(data => { for (let i = 0; i < 7; i++) { this.dateList[i].name = data.calendars[i].mass_name; this.dateList[i].color = data.calendars[i].shirt_color.color_code; this.pageReq.calendar_id = data.calendars[i].id; this.eventsService.getAll(this.pageReq).subscribe(data => { if (!data.events.length) { return; } data.events.forEach(event => { event.start_time = new Date(event.start_time); event.name = event.start_time.getHours() >= 12 ? 'Lễ tối' : 'Lễ sáng'; }); this.dateList[i].events = data.events; }) } }) } getData(parishId) { this.pageReq.parish_id = parishId; this.getParish(); this.getEvents(); } changeDateItem(id) { this.activeDateItemId = id } changeSegmentSlide() { this.slides.getActiveIndex().then(index => { this.changeDateItem(index); }) } scrollToTop(value) { this.ionContent.scrollToTop(value); } changeSegment(id) { this.slides.slideTo(id).then(() => this.changeDateItem(id)); } goToEventDetail(dateItem, event) { const data = { dateList: this.dateList, dateItem: dateItem, eventId: event.id, dateActive: this.activeDateItemId } this.router.navigate(['main/prayer-time/prayer-detail'], { queryParams: { data: JSON.stringify(data) } }) } paddingTopIonContent() { return this.fixedElHeight + 'px'; } seeMore() { this.router.navigateByUrl('main/prayer-time/select-diocese'); } goToMap() { window.open('https://www.google.com/maps/dir/?api=1&destination=' + this.parish.location.lat + ',' + this.parish.location.long); } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { APICONFIG } from '../@http-config/api'; import { catchError, map } from 'rxjs/operators'; // import { ToastrService } from 'ngx-toastr'; // import { SUCCESS } from '../@http-config/messages'; import { Router } from '@angular/router'; import { StorageService } from 'src/app/@app-core/storage.service'; import { BehaviorSubject, Observable } from 'rxjs'; import { ToastController } from '@ionic/angular'; import { LoadingService, ToastService } from '../../utils'; @Injectable() export class AuthService { private data: BehaviorSubject<string> = new BehaviorSubject<string>(''); constructor( private http: HttpClient, private router: Router, private storage: StorageService, public toastController: ToastController, ) { } public get receiveData(): Observable<any> { return this.data.asObservable(); } public sendData(value: any) { this.data.next(value); } public forgotPassword(req) { return this.http.post(`${APICONFIG.AUTH.RESET_PASSWORD_EMAIL}`, req).pipe( map((result: any) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; })); } public checkcodePassword(req) { return this.http.post(`${APICONFIG.AUTH.CHECK_CODE_RESET}`, req).pipe( map((result: any) => { this.storage.clear(); localStorage.setItem('Authorization', result.token); this.storage.setInfoAccount(); return result; }), catchError((errorRes: any) => { throw errorRes.error; } )); } public newPassword(req) { return this.http.post(`${APICONFIG.AUTH.RESET_PASSWORD_NEW}`, req).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; } )); } public resetPassword(req) { return this.http.post(`${APICONFIG.AUTH.RESET_PASSWORD}`, req).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; } )); } public login(req) { return this.http.post(`${APICONFIG.AUTH.LOGIN}`, req).pipe( map((result: any) => { this.storage.clear(); localStorage.setItem('Authorization', result.token); this.storage.setInfoAccount(); this.router.navigate(['/main']); return result; }), catchError((errorRes: any) => { throw errorRes.error; })); } logout() { localStorage.clear(); this.storage.clear(); window.location.assign('/'); } public signup(req) { return this.http.post(`${APICONFIG.AUTH.SIGNUP}`, req).pipe( map((result: any) => { this.storage.clear(); localStorage.setItem('Authorization', result.token); this.storage.setInfoAccount(); this.router.navigate(['/main']); return result; }), catchError((errorRes: any) => { throw errorRes.error; })); } public countryCode() { return this.http.get(`${APICONFIG.AUTH.COUNTRY_CODE}`).pipe( map((result: any) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; })) } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; import { AlertController, IonInfiniteScroll } from '@ionic/angular'; import { IPageRequest, ParishesService } from 'src/app/@app-core/http'; @Component({ selector: 'app-choose-store', templateUrl: './choose-store.page.html', styleUrls: ['./choose-store.page.scss'], }) export class ChooseStorePage implements OnInit { @ViewChild('infiniteScroll') infinityScroll: IonInfiniteScroll; headerCustom = { title: 'Chọn cửa hàng khác' }; list = []; pageReq: IPageRequest = { page: 1, per_page: 20 } constructor( private parishesService: ParishesService, private alertController: AlertController, private router: Router ) { } ngOnInit() { this.loadData(); } loadData(event?) { this.parishesService.getAll(this.pageReq).subscribe(data => { this.list = this.list.concat(data.parishes); this.pageReq.page++; if (this.list.length >= data.meta.pagination.total_objects) { this.infinityScroll.disabled = true; } if (event) { event.target.complete(); } }) } async alertChooseStore(item) { const alert = await this.alertController.create({ header: `Vào cửa hàng ${item.name}`, mode: 'ios', buttons: [ { text: 'Hủy', role: 'cancel' }, { text: 'Đồng ý', handler: () => { localStorage.setItem('tempParishId', item.id); this.router.navigateByUrl('main/store'); } } ] }) await alert.present(); } loadMoreData(event) { this.loadData(event); } } <file_sep>import { Injectable } from '@angular/core'; import { AccountService } from '../http'; @Injectable({ providedIn: 'root' }) export class ImageService { avatar = ''; constructor( public accountService: AccountService ) { } public getImage() { this.accountService.getAccounts().subscribe(data => { if(data.app_user.thumb_image == null) { data.app_user['thumb_image'] = "https://i.imgur.com/edwXSJa.png"; this.avatar = data.app_user.thumb_image; } else if( data.app_user.thumb_image.url == null) { data.app_user['thumb_image'] = "https://i.imgur.com/edwXSJa.png"; this.avatar = data.app_user.thumb_image; } else { this.avatar = data.app_user.thumb_image.url; } }) } } <file_sep>import { from } from "rxjs"; export * from './donate.service';<file_sep>import { IPageRequest } from "../global/global.DTO"; export interface IPageProduct extends IPageRequest { category_id: any; } export interface IPageCategory extends IPageRequest { parish_id; }<file_sep>import { IPageRequest } from "../global"; export interface IHymnMusic extends IPageRequest { filter: string; filter_type: string } <file_sep>import { LoadingService } from './../@app-core/utils/loading.service'; import { DioceseService } from './../@app-core/http/diocese/diocese.service'; import { Component, OnInit, ViewChild } from '@angular/core'; import { IonSlides, IonContent, IonButtons } from '@ionic/angular'; import { DateTimeService } from '../@app-core/utils'; import { ClassMethod } from '@angular/compiler'; @Component({ selector: 'app-statistic', templateUrl: './statistic.page.html', styleUrls: ['./statistic.page.scss'], }) export class StatisticPage implements OnInit { @ViewChild('slides', { static: false }) slides: IonSlides; @ViewChild(IonContent, { static: false }) ionContent: IonContent; @ViewChild('segment', { static: false }) segment: any; headerCustom = { title: 'Thống kê' }; years = []; data: any = []; selectedMonthId; selectedYear: any; hasYearOptions = false; slideOptions = { initialSlide: 0 }; constructor( public DateTimeService: DateTimeService, private dioceseService: DioceseService, private loadingService: LoadingService ) { } ngOnInit() { this.initData(); } initData() { this.loadingService.present(); for (let year = 2020; year <= new Date().getFullYear(); year++) { this.years.push({ number: year, months: [] }) } this.selectedYear = this.years[this.years.length - 1].number; this.years.forEach(year => { let months = []; for (let i = 1; i <= 12; i++) { const daysInMonth = 1; let dates = []; this.dioceseService.getAttention(year.number + '-' + i + '-' + daysInMonth).subscribe((data) => { this.data = data.calendars; for (let data of this.data) { let number; if (data.date.slice(8, 9) == '0') { number = data.date.replace(data.date.slice(8, 9), '').slice(8, 9); } else number = data.date.slice(8, 10) dates.push({ id: data.id, number: number, hasJoin: data.joined, special: 0, mass_type: data.mass_type, }) } }) months.push({ id: i - 1, name: `Tháng ${i}`, dates: dates }) } year.months = months; setTimeout(() => { this.loadingService.dismiss(); }, 1500) }) this.selectedMonthId = 0; } calJoinedEvents(dates) { return dates.reduce((acc, cur) => cur.hasJoin ? ++acc : acc, 0); } calJoinedSpecialEvents(dates) { return dates.reduce((acc, cur) => cur.special && cur.hasJoin ? ++acc : acc, 0); } calSpecialEvents(dates) { return dates.reduce((acc, cur) => cur.special ? ++acc : acc, 0); } scrollToTop(value) { this.ionContent.scrollToTop(value); } changeSegment(id, event) { const offsetLeft = event.target.offsetLeft; const offsetWidth = event.target.offsetWidth; const segmentOffsetWidth = this.segment.el.offsetWidth; this.segment.el.scroll(offsetLeft - segmentOffsetWidth / 2 + offsetWidth / 2, 0); this.slides.lockSwipes(false).then(() => { this.slides.slideTo(id).then(() => { this.changeSlide(id); this.slides.lockSwipes(true); }); }) } changeSlide(id) { this.selectedMonthId = id; } toggleHasYearOptions(bool) { this.hasYearOptions = bool; } disableSwipe() { this.slides.lockSwipes(true); } changeYear(year) { event.stopPropagation(); if (this.selectedYear != year.number) { this.selectedYear = year.number; this.selectedMonthId = 0; } this.toggleHasYearOptions(false); } onScrollContent(event) { this.toggleHasYearOptions(false); } }<file_sep>export * from './hymn-music.service'<file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { ParishesService } from 'src/app/@app-core/http'; import { IPageParishes } from 'src/app/@app-core/http/parishes/parishes.DTO'; import { LoadingService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-select-parish', templateUrl: './select-parish.page.html', styleUrls: ['./select-parish.page.scss'], }) export class SelectParishPage implements OnInit { headerCustom = { title: 'Chọn giáo xứ' }; list = []; notFound = false; id; pageRequest: IPageParishes = { page: 1, per_page: 100, diocese_id: null } constructor( private router: Router, private parishService: ParishesService, private route: ActivatedRoute, private loadingService: LoadingService ) { } ngOnInit() { this.loadingService.present(); this.route.queryParams.subscribe(params => { this.pageRequest.diocese_id = JSON.parse(params['data']).id; }) this.getData(); } getData() { this.notFound = false; this.parishService.getAllWithDioceseId(this.pageRequest).subscribe((data) => { this.loadingService.dismiss(); this.notFound = true; this.list = data.parishes; }) } search(value: string) { if (typeof value != 'string') { return; } else if (!value) { delete this.pageRequest.search; } else { this.pageRequest.search = value; } this.reset(); this.getData(); } reset() { this.list = []; this.pageRequest.page = 1; } select(item) { localStorage.setItem('tempParishId', item.id); this.router.navigateByUrl('main/prayer-time'); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-questionares', templateUrl: './questionares.page.html', styleUrls: ['./questionares.page.scss'], }) export class QuestionaresPage implements OnInit { headerCustom = { title: '<NAME>', background:'transparent', color: '#fff' }; constructor( private router: Router, ) { } ngOnInit() { } ionViewWillEnter() { localStorage.removeItem('questionType'); localStorage.removeItem('questionTypeName'); } goToChooseQuestionType(type) { this.router.navigate(['questionares/choose-question']); localStorage.setItem('questionType', type); } rule() { this.router.navigate(['questionares/rule']); } rank() { this.router.navigate(['questionares/rank']); } } <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-main-item', templateUrl: './main-item.component.html', styleUrls: ['./main-item.component.scss'], }) export class MainItemComponent implements OnInit { @Input() data: any; constructor( private router: Router ) { } ngOnInit() { } goToDetail() { switch (this.data.diocese_type) { case 'vatican': this.router.navigateByUrl('main/tonggiaophan/parish-news'); break; case 'archdiocese': case 'diocese': const data = { diocese: { id: this.data.id, name: this.data.name, type: this.data.diocese_type } } this.router.navigate(['/main/tonggiaophan/archdiocese-detail'], { queryParams: { data: JSON.stringify(data) } }) break; } } } <file_sep>import { MainPage } from './../main/main.page'; import { HymnMusicService } from './http/hymn-music/hymn-music.service'; import { NgModule, ModuleWithProviders, ErrorHandler } from '@angular/core'; import { CommonModule } from '@angular/common'; import { AuthService, AccountService, GlobalService, EventsService, OrderService, VaticanService, CourseService, CalendarService, DoctrineService } from './http'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { IntercepterService } from './http-interceptor'; import { API_URL } from './http/@http-config'; import { StorageService } from './storage.service'; import { environment } from 'src/environments/environment.prod'; import { GlobalErrorHandler } from './GlobalErrorHandler'; import { ConnectivityService } from './utils/connectivity.service'; import { DateTimeService, LoadingService, ToastService, NetworkService } from './utils'; import { HistoryService } from './http/history'; import { DioceseService } from './http/diocese'; import { PopeService } from './http/pope'; @NgModule({ declarations: [], imports: [ CommonModule, HttpClientModule, ] }) export class CoreModule { public static forRoot(): ModuleWithProviders<unknown> { return { ngModule: CoreModule, providers: [ ToastService, { provide: API_URL, useValue: environment.apiUrl }, { provide: HTTP_INTERCEPTORS, useClass: IntercepterService, multi: true }, { provide: ErrorHandler, useClass: GlobalErrorHandler }, AuthService, StorageService, AccountService, EventsService, GlobalService, ConnectivityService, LoadingService, DateTimeService, HistoryService, OrderService, DioceseService, VaticanService, DoctrineService, PopeService, CourseService, CalendarService, HymnMusicService, MainPage, NetworkService ] }; } } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { map, catchError } from 'rxjs/operators'; import { requestQuery } from '../../utils'; import { APICONFIG } from '../@http-config'; import { IPageEvent } from './event.DTO'; @Injectable() export class EventsService { constructor( private http: HttpClient ) { } public getAll(request: IPageEvent) { return this.http.get<any>(`${APICONFIG.EVENTS.GET}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } public getDetail(id: string) { return this.http.get<any>(`${APICONFIG.EVENTS.GET_DETAIL(id)}`).pipe( map((result) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } } <file_sep>import { Injectable } from '@angular/core'; import { Geolocation } from '@ionic-native/geolocation/ngx'; import { NativeGeocoder, NativeGeocoderOptions, NativeGeocoderResult } from '@ionic-native/native-geocoder/ngx'; import { LoadingService } from './loading.service'; import { ModalController, Platform } from '@ionic/angular'; import { MapPage } from '../../@modular/map/map.page' interface Location { lat: number; lng: number; address: string; } @Injectable() export class GeolocationService { geoEncoderOptions: NativeGeocoderOptions = { useLocale: true, maxResults: 5 }; customerLocation: Location = { lat: 0, lng: 0, address: null }; centerService: google.maps.LatLngLiteral = { lat: parseFloat(localStorage.getItem('lat')), lng: parseFloat(localStorage.getItem('lng')) }; constructor(public geolocation: Geolocation, public nativeGeocoder: NativeGeocoder, public loadingService: LoadingService, public PlatForm: Platform, public modalCtrl: ModalController, ) { } ngOnInit() { } getCurrentLocation() { this.PlatForm.ready().then(() => { this.loadingService.present(); this.geolocation.getCurrentPosition().then((resp) => { this.centerService.lat = resp.coords.latitude; this.centerService.lng = resp.coords.longitude; this.getGeoEncoder(this.centerService.lat, this.centerService.lng); localStorage.setItem('address', this.customerLocation.address); localStorage.setItem('lat', this.centerService.lat.toFixed(8).toString()); localStorage.setItem('lng', this.centerService.lng.toFixed(8).toString()); this.loadingService.dismiss(); }) }) } getCurrentLocationNoLoading() { this.PlatForm.ready().then(() => { this.geolocation.getCurrentPosition().then((resp) => { this.centerService.lat = resp.coords.latitude; this.centerService.lng = resp.coords.longitude; this.getGeoEncoder(this.centerService.lat, this.centerService.lng); localStorage.setItem('address', this.customerLocation.address); localStorage.setItem('lat', this.centerService.lat.toFixed(8).toString()); localStorage.setItem('lng', this.centerService.lng.toFixed(8).toString()); }) }) } getGeoEncoder(latitude, longitude) { this.nativeGeocoder.reverseGeocode(latitude, longitude, this.geoEncoderOptions) .then((result: NativeGeocoderResult[]) => { this.customerLocation.address = this.generateAddress(result[0]); }) .catch(() => { }); // do not delete } generateAddress(addressObj) { let obj = []; let address = ''; for (let key in addressObj) { obj.push(addressObj[key]); } obj.reverse(); for (let val in obj) { if (obj[val].length) address += obj[val] + ', '; } return address.slice(4, address.length - 6); } distanceFromUserToPoint(lat1, lon1, lat2, lon2) { var R = 6371; var dLat = this.deg2rad(lat2 - lat1); var dLon = this.deg2rad(lon2 - lon1); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2) ; var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return Math.trunc(d); } distanceFromUserToPointMet(lat1, lon1, lat2, lon2) { var R = 6378100; var dLat = this.deg2rad(lat2 - lat1); var dLon = this.deg2rad(lon2 - lon1); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2) ; var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return Math.round((d + Number.EPSILON) * 100) / 100; } deg2rad(deg) { return deg * (Math.PI / 180) } async openModalGoogleMap() { this.loadingService.present(); const modal = await this.modalCtrl.create({ component: MapPage, cssClass: 'google-map-modal', swipeToClose: true, }); modal.present(); } }<file_sep>import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'; import { Platform } from '@ionic/angular'; import { SpeechRecognition } from '@ionic-native/speech-recognition/ngx' @Component({ selector: 'app-search-bar-nav', templateUrl: './search-bar-nav.component.html', styleUrls: ['./search-bar-nav.component.scss'], }) export class SearchBarNavComponent implements OnInit { @ViewChild('search') search: any; @Output() output = new EventEmitter<string>(); input = ''; hiddenSearchBar = true; constructor( public PlatForm: Platform, private speechRecognition: SpeechRecognition ) { } ngOnInit() { } async showSearch() { // this.hiddenSearchBar = value; // if (!value) { // // this.searchBar.setFocus(); // } this.hiddenSearchBar = await false; setTimeout(async () => { this.search.setFocus() }, 100); } BlurSearch() { this.hiddenSearchBar = true; } startVoice() { this.PlatForm.ready().then(() => { this.speechRecognition.requestPermission().then( async () => { await this.startVoiceRecord(); this.search.setFocus(); } ) }) return; } startVoiceRecord() { this.speechRecognition.startListening().subscribe((matches: Array<string>) => { this.input = matches[0]; }) } changeInput(value) { this.output.emit(value); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { DiocesesPageRoutingModule } from './dioceses-routing.module'; import { DiocesesPage } from './dioceses.page'; import { HeaderModule } from '../@modular/header/header.module'; import { SearchBarNavModule } from '../@modular/search-bar-nav/search-bar-nav.module'; import { ListDiocesesModule } from '../@modular/list-dioceses/list-dioceses.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, DiocesesPageRoutingModule, HeaderModule, SearchBarNavModule, ListDiocesesModule ], declarations: [DiocesesPage] }) export class DiocesesPageModule {} <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { PageNotiRoutingModule } from './page-noti-routing.module'; import { PageNotiComponent } from './page-noti.component'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, PageNotiRoutingModule ], declarations: [PageNotiComponent], exports: [PageNotiComponent], }) export class PageNotiModule { } <file_sep>export * from './priest.service';<file_sep>import { IPageRequest } from '../global'; export interface IAccount { username?: string; password?: string; } export interface IGetAccounts { user: { fullname: string, email: string, role: string, phone_number: string, } } export interface Role { valueView: string; value: any; } export interface IPageAccount extends IPageRequest { role?: string; }<file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ListDiocesesComponent } from './list-dioceses.component'; import { ListDiocesesRoutingModule } from './list-dioceses-routing.module'; import { IonicModule } from '@ionic/angular'; @NgModule({ declarations: [ListDiocesesComponent], imports: [ CommonModule, ListDiocesesRoutingModule, IonicModule ], exports: [ ListDiocesesComponent ] }) export class ListDiocesesModule { } <file_sep>import { HymnMusicService } from './../../@app-core/http/hymn-music/hymn-music.service'; import { Component, ElementRef, HostListener, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core'; import { Howl } from 'howler' import { IonInfiniteScroll, IonRange, IonContent, ModalController, GestureController, Gesture } from '@ionic/angular'; import { LoadingService } from 'src/app/@app-core/utils'; import { IPageRequest } from 'src/app/@app-core/http'; import { ComfillerComponent } from 'src/app/@modular/comfiller/comfiller.component'; import { IHymnMusic } from 'src/app/@app-core/http/hymn-music/hymn-music.DTO'; import { async } from '@angular/core/testing'; @Component({ selector: 'app-hymn-music', templateUrl: './hymn-music.page.html', styleUrls: ['./hymn-music.page.scss'], }) export class HymnMusicPage implements OnInit { @ViewChild('range', { static: false }) range: IonRange; @ViewChild('infiniteScrollSongs', { static: false }) infinityScroll: IonInfiniteScroll; @ViewChild('infiniteScrollFaveolate', { static: false }) infiniteScrollFaveScroll: IonInfiniteScroll; @ViewChild(IonContent) ionContent: IonContent; @ViewChild('contentLyric') lyricContent: ElementRef; // @ViewChild('contentLyric', { read: ElementRef }) contentLyricTouch: ElementRef // @ViewChild(IonContent, { read: ElementRef }) // @HostListener("lyricContent:scroll", ['$event']) // scrollMe(event) { // // this.activeLyric = false; // } headerCustom = { title: 'Nhạc Thánh ca' }; segmentValue = 'all'; selectFiller = "all"; selectSort = "asc"; timeFlag = 0; activeScrollLyric = true; songs = []; favoriteSongs = []; shuffledSongs = []; shuffledFavoriteSongs = []; activeSong = null; activeLyric = null; player: Howl = null; progress = 0; progressInterval = null; hasModal = false; hDisplay: any; mDisplay: any; mixed = false; notFound = false; REPEATING_TYPE = { NONE: 0, REPEAT_ONE: 1, REPEAT_ALL: 2 } repeatingType = this.REPEATING_TYPE.REPEAT_ALL; pageRequestSongs: IHymnMusic = { page: 1, per_page: 16, filter: "", filter_type: "asc" } pageRequestFavoriteSongs: IHymnMusic = { page: 1, per_page: 16, filter: "", filter_type: "asc" } loadedSong = false; notFoundSong = false; constructor( private hymnMusicService: HymnMusicService, private loadingService: LoadingService, private modalCtrl: ModalController, private gestureCtrl: GestureController ) { // const gesture: Gesture = this.gestureCtrl.create({ // el: this.lyricContent.nativeElement, // threshold: 15, // gestureName: 'my-gesture', // onStart: ev => this.onMoveHandler(ev) // }, true); } ngOnInit() { this.loadingService.present(); this.getData(); } ngOnDestroy() { clearInterval(this.progressInterval); this.player && this.player.unload(); } search(value: string) { if (typeof value != 'string') { return; } else if (!value) { delete this.pageRequestSongs.search; delete this.pageRequestFavoriteSongs.search } else { this.pageRequestSongs.search = value; this.pageRequestFavoriteSongs.search = value; } this.pageRequestSongs.page = 1; this.pageRequestFavoriteSongs.page = 1; this.songs = []; this.favoriteSongs = []; this.getData(); this.infinityScroll.disabled = false; this.infiniteScrollFaveScroll.disabled = false; this.ionContent.scrollToTop(0); } shuffleArr(arr) { const tempArr = [...arr]; for (let i = tempArr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [tempArr[i], tempArr[j]] = [tempArr[j], tempArr[i]]; } return tempArr; } secondsToHms(d) { d = Number(d); const h = Math.floor(d / 3600); const m = Math.floor(d % 3600 / 60); const s = Math.floor(d % 3600 % 60); this.hDisplay = h > 0 ? h : ''; var mDisplay = m > 0 ? m : ''; mDisplay = mDisplay > 9 ? mDisplay : '0' + mDisplay + ':'; var sDisplay = s > 0 ? s : ''; sDisplay = sDisplay > 9 ? sDisplay : '0' + sDisplay; return this.hDisplay + mDisplay + sDisplay; } shuffleSongs() { this.shuffledSongs = this.shuffleArr(this.songs); } shuffleFavoriteSongs() { this.shuffledFavoriteSongs = this.shuffleArr(this.favoriteSongs); } getSongs(func?) { this.notFound = false; this.hymnMusicService.getAll(this.pageRequestSongs).subscribe(data => { this.notFound = true; this.songs = this.songs.concat(data.songs) this.pageRequestSongs.page++; func && func(); if (this.songs.length >= data.meta.pagination.total_objects) { this.infinityScroll.disabled = true; } setTimeout(() => { this.loadingService.dismiss(); }, 1500) }) } getFavoriteSongs(func?) { this.notFound = false; this.hymnMusicService.getAllFavorite(this.pageRequestFavoriteSongs).subscribe(data => { this.notFound = true; this.favoriteSongs = this.favoriteSongs.concat(data.songs) this.pageRequestFavoriteSongs.page++; func && func(); if (this.favoriteSongs.length >= data.meta.pagination.total_objects) { this.infiniteScrollFaveScroll.disabled = true; } setTimeout(() => { this.loadingService.dismiss(); }, 1500) }) } getData() { this.getSongs(); this.getFavoriteSongs(); } changedSegment(event) { this.segmentValue = event.target.value; this.ionContent.scrollToTop(0); // this.pageRequestFavoriteSongs.page = 1; // this.pageRequestSongs.page = 1; // this.infiniteScrollFaveScroll.disabled = true; // this.infinityScroll.disabled = true; if (this.checkAllSegment()) { // this.infinityScroll.complete(); if (!this.loadedSong) { // this.infinityScroll.disabled = false; } } else { // this.infiniteScrollFaveScroll.complete(); // this.infiniteScrollFaveScroll.disabled = false; } // this.segmentValue = event.target.value; } onEndSong() { switch (this.repeatingType) { case this.REPEATING_TYPE.REPEAT_ONE: this.player.play(); break; case this.REPEATING_TYPE.REPEAT_ALL: this.next(); break; } } start(song) { console.log(song); this.timeFlag = -1; this.activeSong = song; if (this.player) { this.player.stop(); } this.player = new Howl({ src: [song.url], html5: true, onplay: () => { this.updateProgress(); let maxTime = this.player.duration(); // let heightLyric = this.lyricContent.nativeElement.offsetHeight; let InitHeight = 0; let that = this; let timeLoading = 300 / (maxTime - 20); // let time = this.timeFlag; let contentLyricDOM = document.querySelector('.modal-content'); function myLoop() { setTimeout(function () { if (!that.activeScrollLyric) { setTimeout(() => { that.activeScrollLyric = true; that.timeFlag = Math.round(Number(that.player.seek())); myLoop(); }, 2000); } that.timeFlag += 1; if (that.timeFlag > 20) { contentLyricDOM.scrollTop = (that.timeFlag) + timeLoading; // InitHeight = (that.timeFlag - 20) + timeLoading; } if (that.timeFlag <= 20) { contentLyricDOM.scrollTop = 10; } if (that.timeFlag < maxTime && that.player.playing() && that.activeScrollLyric) { console.log('that.timeFlag', that.timeFlag, '/', timeLoading); myLoop(); } }, 1000) } myLoop(); }, onend: () => { this.onEndSong(); } }); this.player.play(); } togglePlayer() { if (this.player.playing()) { this.player.pause(); this.timeFlag--; } else { this.player.play(); } } toggleLike(song) { event.stopPropagation(); if (this.checkAllSegment()) { if (song.favourite) { this.hymnMusicService.unfavorite(song.id).subscribe(() => { song.favourite = !song.favourite; this.favoriteSongs = this.favoriteSongs.filter(favoriteSong => favoriteSong.id !== song.id); this.loadingService.dismiss(); }) } else { this.shuffleFavoriteSongs(); this.hymnMusicService.favorite(song.id).subscribe(() => { song.favourite = !song.favourite; this.favoriteSongs.push(song); this.loadingService.dismiss(); }); } } else { this.hymnMusicService.unfavorite(song.id).subscribe(() => { this.favoriteSongs = this.favoriteSongs.filter(favoriteSong => favoriteSong.id !== song.id); document.documentElement.scrollTop = 0; }); } } async toggleHasModal(bool) { const lyrictest = this.lyricContent.nativeElement; const gesture = await this.gestureCtrl.create({ el: this.lyricContent.nativeElement, gestureName: 'swipe', direction: 'y', onMove: ev => { this.activeScrollLyric = false; }, onEnd: ev => { } } ); gesture.enable(true); this.hasModal = bool; this.hymnMusicService.getDetail(this.activeSong.id).subscribe((data: any) => { this.activeLyric = data.song.lyric; }) } toggleMixed() { this.mixed = !this.mixed; } changeRepeatingType() { switch (this.repeatingType) { case this.REPEATING_TYPE.REPEAT_ALL: this.repeatingType = this.REPEATING_TYPE.REPEAT_ONE; break; case this.REPEATING_TYPE.REPEAT_ONE: this.repeatingType = this.REPEATING_TYPE.NONE; break; case this.REPEATING_TYPE.NONE: this.repeatingType = this.REPEATING_TYPE.REPEAT_ALL; break; } } getCurrentListAndIndex() { let list = []; let index = null; if (this.mixed) { list = this.checkAllSegment() ? this.shuffledSongs : this.shuffledFavoriteSongs; index = list.indexOf(this.activeSong); if (index === -1) { list = this.shuffledSongs; index = list.indexOf(this.activeSong); } } else { list = this.checkAllSegment() ? this.songs : this.favoriteSongs; index = list.indexOf(this.activeSong); if (index === -1) { list = this.songs; index = list.indexOf(this.activeSong); } } return { list: list, index: index }; } next() { const { list, index } = this.getCurrentListAndIndex(); this.start(index === list.length - 1 ? list[0] : list[index + 1]); this.activeLyric = list[index + 1].lyric; } prev() { const { list, index } = this.getCurrentListAndIndex(); this.start(index > 0 ? list[index - 1] : list[list.length - 1]) this.activeLyric = list[index - 1].lyric; } seek() { let newValue = +this.range.value; let duration = this.player.duration(); this.player.seek(duration * (newValue / 100)); this.timeFlag = Math.round(duration * (newValue / 100)); } updateProgress() { clearInterval(this.progressInterval); this.progressInterval = setInterval(() => { const seek = this.player.seek(); this.progress = (<any>seek / this.player.duration()) * 100 || 0; }, 1000) } checkActiveSong(song) { return this.activeSong && song.id === this.activeSong.id; } checkAllSegment() { return this.segmentValue === 'all'; } loadMoreSongs(event) { this.getSongs(() => { event.target.complete(); }); } loadMoreSongsFavorite(event) { this.getFavoriteSongs(() => { event.target.complete(); }) } async clickFiller() { const popover = await this.modalCtrl.create({ component: ComfillerComponent, swipeToClose: true, cssClass: 'modalFiller', componentProps: { fillerItem: this.selectFiller, sortItem: this.selectSort } }); popover.onDidDismiss() .then(async (data) => { if (data.data?.filler) { this.selectFiller = data.data.filler; if (data.data.filler == "all") { this.pageRequestSongs.filter = ""; } else { this.pageRequestSongs.filter = data.data.filler; } } if (data.data?.sort) { this.selectSort = data.data.sort; this.pageRequestSongs.filter_type = data.data.sort; } this.songs = await []; this.favoriteSongs = await []; this.pageRequestFavoriteSongs.page = await 0; this.pageRequestSongs.page = await 0; this.getData(); }); return await popover.present(); } }<file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { NavController } from '@ionic/angular'; import { EventsService } from 'src/app/@app-core/http'; import { DateTimeService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-prayer-detail', templateUrl: './prayer-detail.page.html', styleUrls: ['./prayer-detail.page.scss'], }) export class PrayerDetailPage implements OnInit { headerCustom = {title: 'Chi tiết bài đọc'}; dateList = []; data: any; dateItem: any; dateActive: any; event = { description: '', prayers: '' } constructor( private route: ActivatedRoute, public dateTimeService: DateTimeService, private navCtrl: NavController, private eventsService: EventsService ) { } ngOnInit() { this.getData(); } getData() { this.route.queryParams.subscribe(params => { this.data = JSON.parse(params['data']); this.dateList = this.data.dateList; this.dateActive = this.data.dateActive; this.dateList.forEach(dateItem => dateItem.date = new Date(dateItem.date)); this.eventsService.getDetail(JSON.parse(params['data']).eventId).subscribe(data => { this.event = data.event; }) this.dateItem = this.data.dateItem; this.dateItem.date = new Date(this.dateItem.date) }).unsubscribe(); } changeDateItem(dateItem) { if (dateItem.id == this.dateItem.id) { return; } localStorage.setItem('dateItemId', dateItem.id); this.navCtrl.back(); } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { IonContent, IonInfiniteScroll, ModalController } from '@ionic/angular'; import { HistoryService } from '../@app-core/http'; @Component({ selector: 'app-history', templateUrl: './history.page.html', styleUrls: ['./history.page.scss'], }) export class HistoryPage implements OnInit { @ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll; @ViewChild(IonContent) ionContent: IonContent; currentSegmentValue = 'service'; lastScrollTop = 0; data: any; constructor( private modalController: ModalController, private historyService: HistoryService ) { this.init(); } ngOnInit() { this.getDataServices(); this.getDataEvents(); } init() { this.data = { services: { pageRequest: { page: 1, per_page: 5 }, array: [], loadedData: false }, events: { pageRequest: { page: 1, per_page: 5 }, array: [], loadedData: false } }; } changedSegment(value) { this.ionContent.getScrollElement().then(content => { const scrollTop = content.scrollTop; this.ionContent.scrollToTop().then(() => { this.currentSegmentValue = value; this.ionContent.scrollByPoint(0, this.lastScrollTop, 0); this.lastScrollTop = scrollTop; }) }) } getDataServices(func?) { let events = this.data.services; this.historyService.getServices(events.pageRequest).subscribe(data => { events.array = events.array.concat(data.events); func && func(); events.pageRequest.page++; if (events.array.length >= data.meta.pagination.total_objects) { events.loadedData = true; } }) } getDataEvents(func?) { let events = this.data.events; this.historyService.getEvents(events.pageRequest).subscribe(data => { events.array = events.array.concat(data.events); func && func(); events.pageRequest.page++; if (events.array.length >= data.meta.pagination.total_objects) { events.loadedData = true; } }) } loadMoreDataServices(event) { this.getDataServices(() => { event.target.complete(); }) } loadMoreDataEvents(event) { this.getDataEvents(() => { event.target.complete(); }) } doRefresh(event) { this.init(); let count = 0; this.getDataServices(() => { count++; count == 2 && event.target.complete(); }) this.getDataEvents(() => { count++; count == 2 && event.target.complete(); }) } scrollToTop(event) { event.target.value == this.currentSegmentValue && this.ionContent.scrollToTop(300); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { AuthService } from '../@app-core/http'; import { ParishesService } from '../@app-core/http/parishes'; import { IPageParishes } from '../@app-core/http/parishes/parishes.DTO'; import { LoadingService } from '../@app-core/utils'; @Component({ selector: 'app-parishes', templateUrl: './parishes.page.html', styleUrls: ['./parishes.page.scss'], }) export class ParishesPage implements OnInit { headerCustom = { title: 'Chọn giáo xứ' }; constructor( public parishesService: ParishesService, public authService: AuthService, private route: ActivatedRoute, private loadingService: LoadingService ) { } pageParish: IPageParishes = { diocese_id: null, page: 1, per_page: 1000 } data; dataParish = []; type_page; notFound = false; ngOnInit() { this.loadingService.present(); this.route.queryParams.subscribe(params => { this.data = JSON.parse(params['data']); this.pageParish.diocese_id = this.data.id; this.type_page = this.data.type_page; }); this.getAll(); } getAll() { this.notFound = false; this.parishesService.getAllWithDioceseId(this.pageParish).subscribe((data: any) => { this.notFound = true; this.loadingService.dismiss() this.dataParish = data.parishes; }); } search(value: string) { if (typeof value != 'string') { return; } else if (!value) { delete this.pageParish.search; } else { this.pageParish.search = value; } this.pageParish.page = 1; this.dataParish = []; this.getAll(); } } <file_sep>import { DioceseService } from './../../@app-core/http/diocese/diocese.service'; import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import { Platform } from '@ionic/angular'; import { GeolocationService } from 'src/app/@app-core/utils'; import { ParishesService } from 'src/app/@app-core/http/parishes'; import { IPageParishes } from 'src/app/@app-core/http/parishes/parishes.DTO'; import { IPageRequest } from 'src/app/@app-core/http/global/global.DTO'; @Component({ selector: 'app-map', templateUrl: './map.page.html', styleUrls: ['./map.page.scss'], }) export class MapPage implements OnInit { title = ''; map: google.maps.Map; center: google.maps.LatLngLiteral = this.GeolocationService.centerService; infoWindows: any = []; pageRequestParishes: IPageParishes = { diocese_id: localStorage.getItem('diocese_id'), } pageRequestDioceses: IPageRequest = { } markers: any = [] mapMarker: any; @ViewChild('map', { read: ElementRef, static: false }) mapRef: ElementRef; constructor( public platform: Platform, private GeolocationService: GeolocationService, private parishesService: ParishesService, private geolocationService: GeolocationService, private DioceseService: DioceseService, ) { } ngOnInit() { let tempTitle = JSON.parse(localStorage.getItem('diocese_id')) || '.'; this.DioceseService.getDetail(tempTitle).subscribe((data) => { this.title = 'Bản đồ ' + data.diocese.name; }) this.GeolocationService.getCurrentLocation(); } ionViewWillEnter() { this.center = this.GeolocationService.centerService; this.initMap(); } initMap(): void { this.map = new google.maps.Map(document.getElementById("map") as HTMLElement, { center: this.center, zoom: 15, disableDefaultUI: true, }); this.addDataMarkerToMap(); } getCurrentLocation() { this.GeolocationService.getCurrentLocation(); this.center = this.GeolocationService.centerService; this.initMap(); this.addCurrenMarker(); } addCurrenMarker() { let currentMarker = new google.maps.Marker({ position: new google.maps.LatLng(this.center.lat, this.center.lng), label: 'Vị trí của bạn, kéo thả để thay đổi', icon: 'assets/icon/current-marker.png', draggable: true, }); currentMarker.setMap(this.map); this.getCurrentMarkerLatLng(currentMarker, this.center.lat, this.center.lng); } getCurrentMarkerLatLng(currentMarker, lat, lng) { google.maps.event.addListener(currentMarker, 'dragend', function (event) { lat = event.latLng.lat(); lng = event.latLng.lng(); }); } addDataMarkerToMap() { this.pageRequestParishes.diocese_id = JSON.parse(localStorage.getItem('diocese_id')); this.parishesService.getAllWithDioceseId(this.pageRequestParishes).subscribe(data => { for (let marker of data.parishes) { if (marker.location != null) { this.markers.push(marker) }; } this.deleteMapMarkers(this.markers); data.parishes.length <= 10 ? this.addMarkersToMap(this.markers, true) : this.addMarkersToMap(this.markers, false); }) } addMarkersToMap(markers, isEligible: boolean) { for (let marker of markers) { let distance: any = this.geolocationService.distanceFromUserToPoint(this.center.lat, this.center.lng, marker.location.lat, marker.location.long); let tempUnit = ' km'; if (distance < 1) { distance = this.geolocationService.distanceFromUserToPointMet(this.center.lat, this.center.lng, marker.location.lat, marker.location.long).toFixed(); tempUnit = ' m'; } distance = distance + tempUnit; let position = new google.maps.LatLng(marker.location.lat, marker.location.long); this.mapMarker = new google.maps.Marker({ position: position, label: marker.name, icon: 'assets/icon/map.png', }); this.mapMarker.setMap(this.map); if (isEligible == true) { let mapMarkerInfo = { name: marker.name, url: marker.thumb_image.url, priest_name: marker.priest_name, address: marker.address, distance: distance, lat: marker.location.lat, lng: marker.location.long, } this.addInfoWindowToMarker(this.mapMarker, mapMarkerInfo); } else { let mapMarkerInfo = { name: marker.name, priest_name: marker.priest_name, address: marker.address, distance: distance, lat: marker.location.lat, lng: marker.location.long, } this.addInfoWindowToMarker(this.mapMarker, mapMarkerInfo, 'https://vcdn1-vnexpress.vnecdn.net/2018/05/23/chim-bo-cau-1-1527049236.jpg?w=1200&h=0&q=100&dpr=1&fit=crop&s=ZLofFUONkZraeibrYKozJw'); } } } deleteMapMarkers(mapMarkers) { mapMarkers = null } async addInfoWindowToMarker(marker, mapMarkerInfo, url?) { if (url) { mapMarkerInfo.url = url } let infoWindowContent = '<div *ngIf=" markers.length != null ">' + '<h3 style=" display: block; text-align: center; ">' + mapMarkerInfo.name + '</h3>' + '<img style=" height: 120px; width: 100%; display: block; margin: auto; border-radius: 12px; " src=' + mapMarkerInfo.url + '>' + '<h5 style=" display: block; text-align: center; font-size: 17px; ">' + mapMarkerInfo.priest_name + '</h5>' + '<h6>' + mapMarkerInfo.address + '</h6>' + '<p>Khoảng cách ước tính: ' + mapMarkerInfo.distance + '<ion-button id="navigate" mode="ios" style=" --background: #F6C33E; --border-radius: 15px; display: block; margin: auto; margin-top: 5px; --background-activated: #CC9D3E; ">' + 'Chỉ đường tới đây' + '</ion-button>' '</div>'; let infoWindow = new google.maps.InfoWindow({ content: infoWindowContent, }); marker.addListener('click', () => { this.closeAllInfoWindows(); infoWindow.open(this.map, marker); google.maps.event.addListenerOnce(infoWindow, 'domready', () => { document.getElementById('navigate').addEventListener('click', () => { window.open('https://www.google.com/maps/dir/?api=1&destination=' + mapMarkerInfo.lat + ',' + mapMarkerInfo.lng); }); }); }); this.infoWindows.push(infoWindow); } closeAllInfoWindows() { for (let window of this.infoWindows) { window.close(); } } }<file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-catechism-class', templateUrl: './catechism-class.page.html', styleUrls: ['./catechism-class.page.scss'], }) export class CatechismClassPage implements OnInit { headerCustom = {title: 'Lớp học giáo lý'}; catechismList = [ { id:0, name: '<NAME>', thumbImage: 'assets/img/catechism-menu-1.svg', desUrl: 'main/catechism-class/catechism' }, { id: 1, name: '<NAME>', thumbImage: 'assets/img/catechism-menu-2.svg', desUrl: 'main/catechism-class/catechism-marriage' }, { id: 2, name: '<NAME>', thumbImage: 'assets/img/catechism-menu-4.svg', desUrl: 'main/catechism-class/catechism-marriage' }, { id: 3, name: '<NAME>', thumbImage: 'assets/img/catechism-menu-3.svg', desUrl: '/questionares' } ] constructor( private router: Router, ) { } ngOnInit() { } goToCatechismDetail(catechism) { this.router.navigate([catechism.desUrl], { queryParams: { data: catechism.name, id: catechism.id } }) } } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { catchError, map } from 'rxjs/operators'; import { APICONFIG } from '../@http-config/api'; @Injectable({ providedIn: 'root' }) export class QuestionaresService { constructor(private http: HttpClient) { } public getTopic() { return this.http.get<any>(`${APICONFIG.QUESTIONARES.GET_TOPIC}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ); } public getLevel() { return this.http.get<any>(`${APICONFIG.QUESTIONARES.GET_LEVEL}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ); } public getQuesTopic(topic: any) { return this.http.get<any>(`${APICONFIG.QUESTIONARES.GET_QUES_TOPIC(topic)}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ); } public getQuesLevel(level: any) { return this.http.get<any>(`${APICONFIG.QUESTIONARES.GET_QUES_LEVEL(level)}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ); } public checkAnswer(answerKey: string) { return this.http.get(`${APICONFIG.QUESTIONARES.CHECK_ANSWER(answerKey)}`).pipe( map((result: any) => { return result; }), catchError((errorRes) => { throw errorRes.error; }) ); } public updateScore(score: any) { return this.http.put(`${APICONFIG.QUESTIONARES.UPDATE_SCORE}`, score).pipe( map((result: any) => { return result; }), catchError((errorRes) => { throw errorRes.error; }) ) } public getRanking() { return this.http.get<any>(`${APICONFIG.QUESTIONARES.RANKING}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ); } }<file_sep> import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { MainPage } from './main.page'; const routes: Routes = [ { path: '', component: MainPage, }, { path: 'catechism-class', loadChildren: () => import('./catechism-class/catechism-class.module').then( m => m.CatechismClassPageModule) }, { path: 'tonggiaophan', loadChildren: () => import('./tonggiaophan/tonggiaophan.module').then( m => m.TonggiaophanPageModule) }, { path: 'prayer-time', loadChildren: () => import('./prayer-time/prayer-time.module').then( m => m.PrayerTimePageModule) }, { path: 'store', loadChildren: () => import('./store/store.module').then( m => m.StorePageModule) }, { path: 'calendar', loadChildren: () => import('./../calendar/calendar.module').then( m => m.CalendarPageModule) }, { path: 'hymn-music', loadChildren: () => import('./hymn-music/hymn-music.module').then( m => m.HymnMusicPageModule) }, { path: 'hymn-video', loadChildren: () => import('./hymn-video/hymn-video.module').then( m => m.HymnVideoPageModule) }, { path: '', redirectTo: '', pathMatch: 'full' }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class MainPageRoutingModule { } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { ParishNewsPageRoutingModule } from './parish-news-routing.module'; import { ParishNewsPage } from './parish-news.page'; import { HeaderModule } from 'src/app/@modular/header/header.module'; import { MainSlideModule } from 'src/app/@modular/main-slide/main-slide.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, ParishNewsPageRoutingModule, HeaderModule, MainSlideModule ], declarations: [ParishNewsPage] }) export class ParishNewsPageModule {} <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { map, catchError } from 'rxjs/operators'; import { APICONFIG } from '..'; import { requestQuery } from '../../utils'; import { IPageCalendar } from './calendar.DTO'; @Injectable({ providedIn: 'root' }) export class CalendarService { constructor( private http: HttpClient ) { } public getByMonth(request: IPageCalendar) { return this.http.get<any>(`${APICONFIG.CALENDARS.GET_BY_MONTH}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } public getByWeek(cal_date) { return this.http.get<any>(`${APICONFIG.CALENDARS.GET_BY_WEEK}?cal_date=${cal_date}`).pipe( map((result) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } public getByday(request: IPageCalendar) { return this.http.get<IPageCalendar>(`${APICONFIG.CALENDARS.GET_BY_DAY}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } } <file_sep>import { MainPage } from './../../main/main.page'; import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ModalController } from '@ionic/angular'; @Component({ selector: 'app-popuplogout', templateUrl: './popuplogout.component.html', styleUrls: ['./popuplogout.component.scss'], }) export class PopuplogoutComponent implements OnInit { constructor( public modalController: ModalController, private router: Router, private mainPage: MainPage) { } ngOnInit() {} async presentModal() { const modal = await this.modalController.create({ component: PopuplogoutComponent, swipeToClose: true, cssClass: 'modal__logout' }); } dismissModal() { this.modalController.dismiss(null, 'cancel'); } logout() { this.modalController.dismiss(null, 'cancel'); clearInterval(this.mainPage.interval); localStorage.clear(); this.router.navigate(['auth-manager/login']); } } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { map, catchError } from 'rxjs/operators'; import { IPageRequest, APICONFIG } from '..'; import { requestQuery } from '../../utils'; @Injectable({ providedIn: 'root' }) export class DioceseNewsService { constructor(private http: HttpClient) { } public getAll(request: IPageRequest) { return this.http.get<any>(`${APICONFIG.DIOCESE_NEWS.GET}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ); } public getDetail(id) { return this.http.get<any>(`${APICONFIG.DIOCESE_NEWS.GET_DETAIL(id)}`).pipe( map(result => { return result; }), catchError(errorRes => { throw errorRes.error; }) ); } } <file_sep>import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { catchError, map } from 'rxjs/operators'; import { requestQuery } from 'src/app/@app-core/utils'; import { APICONFIG } from '../@http-config/api'; import { IPageRequest } from '../global'; import { IPageParishes } from './parishes.DTO'; @Injectable({ providedIn: 'root' }) export class ParishesService { constructor(private http: HttpClient) { } public getAllWithDioceseId(request: IPageParishes) { return this.http.get<any>(`${APICONFIG.PARISHES.GET_ALL_WITH_DIOCESE_ID}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; })); } public getAllNewsByParish(request: IPageParishes) { return this.http.get<any>(`${APICONFIG.PARISHES.GETNEWS}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; })); } public getParishNewsByid(id) { return this.http.get<any>(`${APICONFIG.PARISHES.GETNEWS}/${(id)}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; })); } public getAll(request: IPageRequest) { return this.http.get<any>(`${APICONFIG.PARISHES.GET_ALL}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ) } public getDetail(id) { return this.http.get<any>(`${APICONFIG.PARISHES.GET_DETAIL(id)}`).pipe( map(result => { return result; }), catchError(errorRes => { throw errorRes.error; }) ); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { PrayerDetailPageRoutingModule } from './prayer-detail-routing.module'; import { PrayerDetailPage } from './prayer-detail.page'; import { HeaderModule } from 'src/app/@modular/header/header.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, PrayerDetailPageRoutingModule, HeaderModule ], declarations: [PrayerDetailPage] }) export class PrayerDetailPageModule {} <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { ToastController } from '@ionic/angular'; import { DonateService } from '../@app-core/http'; import { LoadingService } from '../@app-core/utils'; import { IDataNoti, PageNotiService } from '../@modular/page-noti/page-noti.service'; declare var Stripe; @Component({ selector: 'app-payment', templateUrl: './payment.page.html', styleUrls: ['./payment.page.scss'], }) export class PaymentPage implements OnInit { data:any; stripe = Stripe('<KEY>'); card: any; amount?: any; purpose?: any; headerCustom = {title: '<NAME>', background: '#fff'} constructor( private route: ActivatedRoute, private pageNotiService: PageNotiService, private router: Router, private donateService: DonateService, public loadingService: LoadingService, public toastController: ToastController, ) { } ngOnInit() { this.route.queryParams.subscribe(params => { this.data = JSON.parse(params['data']); }) if(this.data.type_page == 'pray') { this.amount = this.data.pray_log.amount; this.purpose = this.data.pray_log.note; } else { this.amount = this.data.donation.amount; this.purpose = this.data.donation.note; } } async presentToast(message, color) { const toast = await this.toastController.create({ message: message, duration: 1000, color: color, }); toast.present(); } showStripe() { this.loadingService.present(); const datapasing: IDataNoti = { title: 'ĐÓNG GÓP THÀNH CÔNG!', des: 'Cảm ơn sự đóng góp của bạn!', routerLink: '/main/chabad' } if(this.data.type_page == 'pray') { const pray_log = { "pray_log" : this.data.pray_log } this.donateService.prayByVisa(pray_log).subscribe((data) => { this.loadingService.dismiss() this.pageNotiService.setdataStatusNoti(datapasing); this.router.navigateByUrl('/page-noti'); }) }else { const donation_log = { "donation" : this.data.donation } this.donateService.donateByVisa(donation_log).subscribe((data) => { this.loadingService.dismiss() this.pageNotiService.setdataStatusNoti(datapasing); this.router.navigateByUrl('/page-noti'); }) } } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { SettingPage } from './setting.page'; const routes: Routes = [ { path: '', component: SettingPage }, { path: 'setting-languages', loadChildren: () => import('./setting-languages/setting-languages.module').then( m => m.SettingLanguagesPageModule) }, { path: 'select-diocese', loadChildren: () => import('./select-diocese/select-diocese.module').then( m => m.SelectDiocesePageModule), }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class SettingPageRoutingModule {} <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { ModalController, NavParams } from '@ionic/angular'; import { AuthService } from 'src/app/@app-core/http'; @Component({ selector: 'app-modal-donate', templateUrl: './modal-donate.component.html', styleUrls: ['./modal-donate.component.scss'], }) export class ModalDonateComponent implements OnInit { constructor(private router: Router, private modalCtrl: ModalController, ) { } @Input() diocese_id: any; @Input() type_page: any; data; title; ngOnInit() { if(this.type_page == 'news_parish'){ this.title = 'loại tin tức' } else { this.title = 'nơi đóng góp' } } async closeModal() { await this.modalCtrl.dismiss(); } gotoDestination() { const data = { id: this.diocese_id, source_type: 'Diocese', type_page: this.type_page } const dataDiocesenews = { id: this.diocese_id, type: { detail: 'dioceseNews', general: 'news' } } this.closeModal(); if(this.type_page == 'donate') { this.router.navigate(['donate'], { queryParams: { data: JSON.stringify(data) } }) } else if(this.type_page == 'pray'){ this.router.navigate(['pray'], { queryParams: { data: JSON.stringify(data) } }) } else if(this.type_page == 'news_parish') { this.router.navigate(['news'], { queryParams: { data: JSON.stringify(dataDiocesenews) } }) } } goToParishes() { if(this.type_page == 'news_parish') { this.data = { id: this.diocese_id, type_page: 'parish_news', type: { detail: 'parish_news', general: 'news' } } } else { this.data = { id: this.diocese_id, source_type: 'Parish', type_page: this.type_page } } this.router.navigate(['/parishes'], { queryParams: { data: JSON.stringify(this.data) } }) this.closeModal(); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { CatechismPageRoutingModule } from './catechism-routing.module'; import { CatechismPage } from './catechism.page'; import { HeaderModule } from 'src/app/@modular/header/header.module'; import { SearchBarNavModule } from 'src/app/@modular/search-bar-nav/search-bar-nav.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, CatechismPageRoutingModule, HeaderModule, SearchBarNavModule ], declarations: [CatechismPage] }) export class CatechismPageModule {} <file_sep>export * from './vatican.service' <file_sep>export class IPageRequest { page?: number; per_page?: number; total_objects?: number; search?: string; sort?: string; typeSort?: number; } <file_sep>import { IPageRequest } from "../global/global.DTO"; export interface IPageVatican extends IPageRequest { category_id?: number; }<file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { TabbarManagerPageRoutingModule } from './tabbar-manager-routing.module'; import { TabbarManagerPage } from './tabbar-manager.page'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, TabbarManagerPageRoutingModule ], declarations: [TabbarManagerPage] }) export class TabbarManagerPageModule {} <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { ModalController, ToastController } from '@ionic/angular'; import { DonateService, OrderService } from '../../@app-core/http'; import { LoadingService, ToastService } from '../../@app-core/utils'; import { IDataNoti, PageNotiService } from '../page-noti/page-noti.service'; declare var Stripe; @Component({ selector: 'app-paymentup', templateUrl: './paymentup.component.html', styleUrls: ['./paymentup.component.scss'], }) export class PaymentupComponent implements OnInit { data: any; stripe = Stripe('<KEY>'); card: any; constructor( private route: ActivatedRoute, private router: Router, public modalController: ModalController, public loadingService: LoadingService, public toastController: ToastController, private orderService: OrderService, private pageNotiService: PageNotiService, private toart: ToastService ) { } ngOnInit() { let url = window.location.href; if (url.includes('?')) { this.route.queryParams.subscribe(params => { this.data = JSON.parse(params['data']); }).unsubscribe(); } this.setupStripe(); } dismissModal() { this.modalController.dismiss(); } setupStripe() { let elements = this.stripe.elements(); var style = { base: { color: '#32325d', lineHeight: '24px', fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: 'antialiased', fontSize: '16px', '::placeholder': { color: '#aab7c4' } }, invalid: { color: '#fa755a', iconColor: '#fa755a' } }; this.card = elements.create('card', { style: style }); this.card.mount('#card-element'); this.card.addEventListener('change', event => { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } }); var form = document.getElementById('payment-form'); form.addEventListener('submit', event => { this.loadingService.present(); event.preventDefault(); this.stripe.createSource(this.card).then(result => { if (result.error) { var errorElement = document.getElementById('card-errors'); errorElement.textContent = result.error.message; } else { const datapasing: IDataNoti = { title: 'THÀNH CÔNG', des: 'Thanh toán thành công!', routerLink: '/main/chabad' } if(this.data.type_page == 'pray') { this.loadingService.dismiss(); this.data.pray_log.token = result.source.id; this.data.pray_log.payment_type = 'visa_master'; this.router.navigate(['/payment'], { queryParams: { data: JSON.stringify(this.data) } },) } else if(this.data.type_page == 'donate') { this.loadingService.dismiss(); this.data.donation.token = result.source.id; this.data.donation.payment_type = 'visa_master'; this.router.navigate(['/payment'], { queryParams: { data: JSON.stringify(this.data) } },) } else { const paramOrder = { order_payment : { "email": localStorage.getItem('email'), "token": result.source.id, "order_id": this.data.order_id } } this.orderService.paymentOrder_Visa(paramOrder).subscribe((data)=>{ this.loadingService.dismiss(); this.pageNotiService.setdataStatusNoti(datapasing); this.router.navigateByUrl('/page-noti'); }, (error: any)=> { this.loadingService.dismiss(); this.toart.presentSuccess('Hãy thử lại sau'); }) } this.dismissModal(); } }); }); } async presentToastValid(message, color) { const toast = await this.toastController.create({ message: message, duration: 1500, color: color, }); toast.present(); } async presentToast(message, color) { const toast = await this.toastController.create({ message: message, duration: 1000, color: color, }); toast.present(); } } <file_sep>import { Injectable } from '@angular/core'; import { CanActivate, Router } from '@angular/router'; import { Observable, of } from 'rxjs'; @Injectable() export class AuthGuard implements CanActivate { constructor( private router: Router, ) { } canActivate(): Observable<boolean> { if (localStorage.getItem('Authorization')) { return of(true); } else { this.router.navigateByUrl('/auth-manager/login', { queryParams: { returnUrl: window.location.pathname } }); return of(false); } } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AlertController, ModalController, PopoverController } from '@ionic/angular'; import { AccountService } from '../@app-core/http/account/account.service'; import { GeolocationService, ImageService } from '../@app-core/utils'; import { PopuplogoutComponent } from '../@modular/popuplogout/popuplogout.component'; @Component({ selector: 'app-account-setting', templateUrl: './account-setting.page.html', styleUrls: ['./account-setting.page.scss'], }) export class AccountSettingPage implements OnInit { headerCustom = { title: 'Thiết lập tài khoản' }; name = localStorage.getItem('fullname') || ''; avatar = ''; // list = [ // { // name: '<NAME>', // ionUrl: 'assets/icon/user.svg', // desUrl: 'account' // }, // { // name: '<NAME>', // ionUrl: 'assets/icon/statistic.svg', // desUrl: 'statistic' // }, // { // name: '<NAME>', // ionUrl: 'assets/icon/wallet.svg', // desUrl: 'paymentmethods' // }, // { // name: '<NAME>', // ionUrl: 'assets/icon/setting.svg', // desUrl: 'account-setting/setting' // }, // { // name: '<NAME>', // ionUrl: 'assets/icon/user.svg', // desUrl: 'account-setting/introduce' // }, // { // name: '<NAME>', // ionUrl: 'assets/icon/user.svg', // desUrl: 'account' // }, // ] constructor( public modalController: ModalController, private popoverController: PopoverController, private router: Router, private accountService: AccountService, private imageService: ImageService, private geolocationService: GeolocationService, private alertCtrl: AlertController, ) { } ngOnInit() { } ionViewWillEnter() { // this.imageService.getImage(); this.avatar = localStorage.getItem('avatar') } routerLink(path) { this.router.navigateByUrl(path); } async openModalLogOut() { const modal = await this.modalController.create({ component: PopuplogoutComponent, swipeToClose: true, cssClass: 'modal__logout', }); await modal.present(); } async openModalGoogleMap() { if(localStorage.getItem('diocese_id')) this.geolocationService.openModalGoogleMap(); else { let alert = await this.alertCtrl.create({ message: 'Hãy chọn giáo phận của bạn trong cài đặt.', mode: 'ios' }) await alert.present(); } } } <file_sep>import { IPageRequest } from "../global"; export interface IPageEvent extends IPageRequest { calendar_id?: string; parish_id?: string; }<file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AccountSettingPage } from './account-setting.page'; const routes: Routes = [ { path: '', component: AccountSettingPage }, { path: 'orders-history', loadChildren: () => import('./orders-history/orders-history.module').then( m => m.OrdersHistoryPageModule) }, { path: 'setting', loadChildren: () => import('./setting/setting.module').then( m => m.SettingPageModule) }, { path: 'introduce', loadChildren: () => import('./introduce/introduce.module').then( m => m.IntroducePageModule) }, { path: 'support', loadChildren: () => import('./support/support.module').then( m => m.SupportPageModule) }, { path: 'my-parish', loadChildren: () => import('./my-parish/my-parish.module').then( m => m.MyParishPageModule) }, { path: 'change-avatar', loadChildren: () => import('./change-avatar/change-avatar.module').then( m => m.ChangeAvatarPageModule) }, { path: 'notification', loadChildren: () => import('./notification/notification.module').then( m => m.NotificationPageModule) } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class AccountSettingPageRoutingModule {} <file_sep>import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { catchError, map } from 'rxjs/operators'; import { requestQuery } from '../../utils'; import { APICONFIG } from '../@http-config/api'; import { IPageRequest } from '../global'; @Injectable({ providedIn: 'root' }) export class HymnMusicService { constructor( private http: HttpClient, ) { } public getAll(request: IPageRequest) { return this.http.get<any>(`${APICONFIG.MUSIC.GET_ALL}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ) } public getDetail(id) { return this.http.get(`${APICONFIG.MUSIC.GET_DETAIL(id)}`).pipe( map((result) => { return result; }), catchError((errorRes) => { throw errorRes.error; }) ) } public getAllFavorite(request: IPageRequest) { return this.http.get<any>(`${APICONFIG.MUSIC.GET_ALL_FAVORITE}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes) => { throw errorRes.error; }) ) } public favorite(songId) { const req = { favourite_song: { song_id: songId } } return this.http.post(`${APICONFIG.MUSIC.FAVORITE}`, req).pipe( map((result) => { return result; }), catchError((errorRes) => { throw errorRes.error; }) ) } public unfavorite(songId) { const option = { body: { favourite_song: { song_id: songId } } } return this.http.request<any>('delete', `${APICONFIG.MUSIC.UNFAVORITE}`, option).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; })); } public getAllLectureVideo(request: IPageRequest) { return this.http.get<any>(`${APICONFIG.VIDEO.GET_ALL}?${(requestQuery(request))}`).pipe( map((result) => { return result; }), catchError((errorRes: any) => { throw errorRes.error; }) ) } public getAllBibleSong(request: IPageRequest) { return this.http.get<any>(`${APICONFIG.VIDEO.GET_BIBEL_SONG}?${(requestQuery(request))}`).pipe( map((result) => { return result }), catchError((errorRes: any) => { throw errorRes.console.error; }) ) } public getBibleSongDetail(id: string) { return this.http.get<any>(`${APICONFIG.VIDEO.GET_BIBLE_SONG_DETAIL(id)}`).pipe( map((result) => { return result; }), catchError((errorRes) => { throw errorRes.error; })); } }<file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { QuestionaresService } from 'src/app/@app-core/http'; import { QuestionDataService } from './choose-question.service'; @Component({ selector: 'app-choose-question', templateUrl: './choose-question.page.html', styleUrls: ['./choose-question.page.scss'], }) export class ChooseQuestionPage implements OnInit { title = ''; headerCustom = { title: '', background: 'transparent', color: '#fff' }; questions = []; questionType = ''; constructor( private router: Router, private questionService: QuestionDataService, private questionaresService: QuestionaresService ) { } ngOnInit() { } ionViewWillEnter() { this.setUpQuestion(); localStorage.removeItem('questionTypeName'); if (localStorage.getItem('score')) { localStorage.removeItem('score'); } } setUpQuestion() { if (localStorage.getItem('questionType') == 'topic') { this.questionaresService.getTopic().subscribe((data) => { this.questions = data.question_topics; this.checkThumbImage(data.question_topics) }) this.questionType = 'Chủ đề' this.title = 'CHỌN CHỦ ĐỀ'; } else if (localStorage.getItem('questionType') == 'level') { this.questionaresService.getLevel().subscribe((data) => { this.questions = data; }) this.questionType = 'Cấp độ' this.title = 'CHỌN CẤP ĐỘ'; } this.headerCustom.title = this.title; localStorage.removeItem('questionTypeName'); if (localStorage.getItem('score')) { localStorage.removeItem('score'); } } async goToQuestion(name) { await this.questionService.changeMessage(name); this.router.navigate(['questionares/choose-question/detail']); // if (localStorage.getItem('questionType') == 'topic') { // localStorage.setItem('idTopic', name.id); // } // else if (localStorage.getItem('questionType') == 'level') { // localStorage.setItem('idLevel', name.level); // } // localStorage.setItem('questionTypeName', this.questionType + ' ' + name.name); // this.router.navigate(['questionares/question']); } checkThumbImage(data) { for (let obj of data) { if (obj.thumb_image == null) obj.thumb_image = 'src/assets/img/giamphan.jpg' } } } <file_sep>import { IPageRequest } from "../global"; export interface IPriest extends IPageRequest{ parish_id?; }<file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { ArchdioceseDetailPageRoutingModule } from './archdiocese-detail-routing.module'; import { ArchdioceseDetailPage } from './archdiocese-detail.page'; import { HeaderModule } from 'src/app/@modular/header/header.module'; import { MainSlideModule } from 'src/app/@modular/main-slide/main-slide.module'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, ArchdioceseDetailPageRoutingModule, HeaderModule, MainSlideModule ], declarations: [ArchdioceseDetailPage] }) export class ArchdioceseDetailPageModule { } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; import { IonInfiniteScroll } from '@ionic/angular'; import { IPageRequest, ParishesService, PopeService } from 'src/app/@app-core/http'; import { IPope } from 'src/app/@app-core/http/pope/pope.DTO'; import { LoadingService } from 'src/app/@app-core/utils'; @Component({ selector: 'app-my-parish', templateUrl: './my-parish.page.html', styleUrls: ['./my-parish.page.scss'], }) export class MyParishPage implements OnInit { @ViewChild('infiniteScroll') infiniteScroll: IonInfiniteScroll; tabNew = true; headerCustom = { title: 'Thông tin giáo xứ'}; listPriest = []; news: any; data; img = ''; id_parish = localStorage.getItem('parish_id'); popeRequest: IPope = { parish_id: this.id_parish, page: 1, per_page: 6 } total:any; constructor( private router: Router, private parishService: ParishesService, private loadingService: LoadingService, private popeService: PopeService) { } ngOnInit() { this.loadingService.present() this.getPriest(); this.myPrish(); } myPrish() { this.parishService.getDetail(this.id_parish).subscribe(data => { this.loadingService.dismiss() this.data = data.parish; // this.imgnotFound(data.parish); this.img = data.parish.thumb_image.url; }) } getUrl() { return `url(${this.img})` } imgnotFound(item) { !item?.thumb_image?.url && (item.thumb_image = { url: "https://i.imgur.com/UKNky29.jpg" }); } changeTabs() { if (this.tabNew) { this.tabNew = false; } else { this.tabNew = true; } } getPriest(func?) { if(this.listPriest.length >= this.total) { this.infiniteScroll.disabled = true; return; } this.popeService.getAllByParish(this.popeRequest).subscribe(data => { this.total = data.meta.pagination.total_objects; !data?.pope_infos?.forEach(element => { // this.imgnotFound(element) }); this.listPriest = this.listPriest.concat(data.pope_infos); func && func(); this.popeRequest.page++; if (this.listPriest.length >= this.total) { this.infiniteScroll.disabled = true; } }) } loadMoreData(event) { this.getPriest(() => { event.target.complete(); }); } goToStoryDetail(item) { const data = { type: { general: 'story', detail: 'pope', }, id: item.id } this.router.navigate(['/news-detail'], { queryParams: { data: JSON.stringify(data) } }) } counter(i: number) { return new Array(i); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { DioceseNewsService, DioceseService, IPageRequest } from 'src/app/@app-core/http'; @Component({ selector: 'app-select-diocese', templateUrl: './select-diocese.page.html', styleUrls: ['./select-diocese.page.scss'], }) export class SelectDiocesePage implements OnInit { headerCustom = {title: 'Chọn giáo phận'}; list = []; notFound = false; pageRequest: IPageRequest = { page: 1, per_page: 10 } constructor( private router: Router, private dioceseService: DioceseService ) { } ngOnInit() { this.getData(); } getData() { this.notFound = false; this.dioceseService.getAll(this.pageRequest).subscribe(data => { this.notFound = true; this.list = data.dioceses; }) } search(value: string) { if (typeof value != 'string') { return; } else if (!value) { delete this.pageRequest.search; } else { this.pageRequest.search = value; } this.reset(); this.getData(); } reset() { this.list = []; this.pageRequest.page = 1; } goToSelectParish(item) { const data = { id: item.id, } this.router.navigate(['main/prayer-time/select-parish'], { queryParams: { data: JSON.stringify(data) } }) } } <file_sep>import { IonInfiniteScroll } from '@ionic/angular'; import { Component, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { DioceseNewsService, IPageRequest, ParishesService, VaticanService } from 'src/app/@app-core/http'; import { IPageParishes } from 'src/app/@app-core/http/parishes/parishes.DTO'; import { LoadingService } from 'src/app/@app-core/utils'; import { IPageVatican } from 'src/app/@app-core/http/vatican/vatican.DTO'; @Component({ selector: 'app-news', templateUrl: './news.page.html', styleUrls: ['./news.page.scss'], }) export class NewsPage implements OnInit { @ViewChild('infiniteScroll') infiniteScroll: IonInfiniteScroll; headerCustom = { title: 'Tin tức' }; news = []; pageRequestVatican: IPageVatican = { page: 1, category_id: 2, per_page: 10 } pageRequestDioceseNews: IPageParishes = { page: 1, per_page: 10, diocese_id: null } pageRequestParish: IPageParishes = { parish_id: localStorage.getItem('parish_id'), page: 1, per_page: 10, } dataParams = null; check = false; newsParish = false; vatican = false; listCate = [] idActive; displayCate = false; toggle = true; notFound = false; constructor( private router: Router, private route: ActivatedRoute, private vaticanService: VaticanService, private dioceseNewsService: DioceseNewsService, private parishesService: ParishesService, private loading: LoadingService, ) { } ngOnInit() { this.loading.present(); this.vaticanService.getCategory().subscribe((data) => { data.vatican_news_categories.forEach(element => { if (element.name == "Vatican") { this.pageRequestVatican.category_id = element.id; } }); this.getParams(); }) } ionViewWillEnter() { const parishId = localStorage.getItem('tempParishId'); if (parishId) { this.pageRequestParish.parish_id = parishId; this.news = []; this.pageRequestParish.page = 1; this.infiniteScroll.disabled = false; this.getData(); } localStorage.removeItem('tempParishId'); this.vaticanService.getCategory().subscribe(data => { this.listCate = data.vatican_news_categories; this.listCate.forEach(e => { if (e.name === 'Vatican') { this.idActive = e.id; } }) }) } ionViewWillLeave() { localStorage.removeItem('voice'); } goToNewsDetail(item) { const data = { id: item.id, type: item.type } this.router.navigate(['/news-detail'], { queryParams: { data: JSON.stringify(data) } }) } getData(func?) { this.notFound = false; if (this.dataParams.id) { switch (this.dataParams.type.detail) { case 'dioceseNews': this.headerCustom.title = 'Tin tức Giáo phận'; this.dioceseNewsService.getAll(this.pageRequestDioceseNews).subscribe(data => { this.notFound = true; this.loading.dismiss(); data.diocese_news.forEach(element => { element.type = this.dataParams.type; element.time = element.created_at.slice(11, 16); element.yymmdd = element.created_at.slice(0, 10); }); this.news = this.news.concat(data.diocese_news); func && func(); this.pageRequestDioceseNews.page++; if (this.news.length >= data.meta.pagination.total_objects) { this.infiniteScroll.disabled = true; } }) break; case 'parish_news': this.newsParish = true; this.headerCustom.title = 'Tin tức Giáo xứ '; this.parishesService.getAllNewsByParish(this.pageRequestParish).subscribe(data => { this.notFound = true; this.loading.dismiss(); data.parish_news.forEach(element => { element.type = this.dataParams.type; element.time = element.created_at.slice(11, 16) element.yymmdd = element.created_at.slice(0, 10); }); this.news = this.news.concat(data.parish_news); func && func(); this.pageRequestParish.page++; if (this.news.length >= data.meta.pagination.total_objects) { this.infiniteScroll.disabled = true; } }) break; case 'vatican': this.vatican = true; this.headerCustom.title = "Tin tức Vatican" this.vaticanService.getAll(this.pageRequestVatican).subscribe(data => { this.notFound = true; this.loading.dismiss(); data.vatican_news.forEach(element => { element.type = this.dataParams.type element.time = element.created_at.slice(11, 16) element.yymmdd = element.created_at.slice(0, 10); }); this.news = this.news.concat(data.vatican_news); func && func(); this.pageRequestVatican.page++; if (this.news.length >= data.meta.pagination.total_objects) { this.infiniteScroll.disabled = true; } }) break; } } else { switch (this.dataParams.type.detail) { case 'vatican': this.vatican = true; this.vaticanService.getAll(this.pageRequestVatican).subscribe(data => { this.notFound = true; this.loading.dismiss(); data.vatican_news.forEach(element => { element.type = this.dataParams.type element.time = element.created_at.slice(11, 16) element.yymmdd = element.created_at.slice(0, 10); }); this.news = this.news.concat(data.vatican_news); func && func(); this.pageRequestVatican.page++; if (this.news.length >= data.meta.pagination.total_objects) { this.infiniteScroll.disabled = true; } }) break; } } } changeCate(c) { this.idActive = c.id; this.pageRequestVatican.category_id = c.id; this.reset(); this.getData(); this.headerCustom.title = c.name; this.displayCate = false; } showCate() { this.displayCate = true; if (this.toggle) { this.toggle = false; } else { this.toggle = true; } } checkShowCate(): boolean { return this.toggle == false && this.displayCate == true } search(value: string) { if (typeof value != 'string') { return; } else if (!value) { delete this.pageRequestParish.search; delete this.pageRequestDioceseNews.search; delete this.pageRequestVatican.search; } else { if (this.dataParams.id == null) { this.pageRequestVatican.search = value; } else if (this.dataParams.type.detail == 'dioceseNews') { this.pageRequestDioceseNews.search = value; } else if (this.dataParams.type.detail == 'parish_news') { this.pageRequestParish.search = value; } else if (this.dataParams.type.detail == 'vatican') { this.pageRequestVatican.search = value; } } this.reset(); this.getData(); } reset() { this.news = []; this.infiniteScroll.disabled = false; this.pageRequestDioceseNews.page = 1; this.pageRequestParish.page = 1; this.pageRequestVatican.page = 1; } getParams() { let url = window.location.href; if (url.includes('?')) { this.route.queryParams.subscribe(params => { this.dataParams = JSON.parse(params['data']); this.pageRequestDioceseNews.diocese_id = this.dataParams.id; this.getData(); }).unsubscribe(); } // this.vaticanService.getCategory().subscribe((data) => { // data.vatican_news_categories.forEach(element => { // if (element.name == "Vatican") { // this.pageRequestVatican.category_id = element.id; // } // }); // this.getData(); // }) } loadMoreData(event) { this.getData(() => { event.target.complete(); }); } imgNotFound(item) { !item?.thumb_image?.url && (item.thumb_image = { url: "https://i.imgur.com/UKNky29.jpg" }); } goToOtherParishes() { const data = this.dataParams; data['type_page'] = 'parish_news' this.router.navigate(['/dioceses'], { queryParams: { data: JSON.stringify(data) } }) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from 'src/app/@app-core/http'; import { LoadingService } from 'src/app/@app-core/utils'; import { IDataNoti, PageNotiService } from 'src/app/@modular/page-noti/page-noti.service'; @Component({ selector: 'app-new-password', templateUrl: './new-password.page.html', styleUrls: ['./new-password.page.scss'], }) export class NewPasswordPage implements OnInit { passwordValue = '359'; confirmedPasswordValue = ''; invalidPassword = ''; invalidConfirmedPassword = ''; constructor( private pageNotiService: PageNotiService, private router: Router, private authService: AuthService, private loadingService: LoadingService ) { } ngOnInit() {} clearPassword(event) { event.target.value = ''; this.invalidPassword = ''; this.invalidConfirmedPassword = ''; } saveValue(event) { if (event.target.name == 'password') { this.passwordValue = event.target.value; } else if (event.target.name == 'confirmedPassword') { this.confirmedPasswordValue = event.target.value; } } checkValidPassword(name: string, value: string) { if (value == '') { this.loadingService.dismiss(); return `${name} không được trống`; } if (value.length < 6) { this.loadingService.dismiss(); return `${name} không được ít hơn 6 ký tự`; } if (name == 'Xác nhận mật khẩu') { this.loadingService.dismiss(); if (this.passwordValue != this.confirmedPasswordValue) { return 'Xác nhận mật khẩu không trùng khớp'; } } return ''; } confirmPassword() { this.loadingService.present(); const datapasing: IDataNoti = { title: 'THÀNH CÔNG!', des: 'Lấy lại mật khẩu thành công!', routerLink: '/main' } this.invalidPassword = this.checkValidPassword('<PASSWORD>', this.passwordValue); this.invalidConfirmedPassword = this.checkValidPassword('<PASSWORD>', this.confirmedPasswordValue); if (this.invalidPassword == '' && this.invalidConfirmedPassword == '') { let dataSubmit = { "new_password": <PASSWORD>, "new_password_confirmation": this.confirmedPasswordValue } this.authService.newPassword(dataSubmit).subscribe((data) => { this.pageNotiService.setdataStatusNoti(datapasing); this.router.navigateByUrl('/page-noti'); this.loadingService.dismiss(); }) } } }
65ed66113feed012c6ce5c1604627250643c18de
[ "Markdown", "TypeScript" ]
167
TypeScript
PATITEK/Kito-App
94f360c3d6198d4a7d8ced5fcf1b5bfd4bb3fec0
4679711501ad31915ffd9540c8653e0e9ae6d37e
refs/heads/master
<repo_name>duxuyang/map<file_sep>/README.md # 微信小程序 地图天气 地图笔记 调用百度地图 天气 <file_sep>/pages/map/map.js // pages/map/map.js var bmap = require('../libs/bmap-wx.min.js'); const app = getApp(); var wxMarkerData = []; Page({ /** * 页面的初始数据 */ data: { latitude:'', longitude:'', winHeight:'', sugData:[], ismap:true }, controltap:function(e){//移动到中心 var that=this; if (e.controlId==1){ this.movetoPosition(); } }, /** * 生命周期函数--监听页面加载 */ onLoad:function (options) { var that=this; wx.getLocation({ type: 'wgs84', success: function (res) { that.setData({ latitude :res.latitude, longitude :res.longitude }) app.globalData.lat = res.latitude; app.globalData.lng = res.longitude; that.showress(); } }) wx.getSystemInfo({ success: function (res) { that.setData({ winHeight: res.windowHeight, controls: [{ id: 1, iconPath: '../img/location.png', position: { left: res.windowWidth- 60, top: res.windowHeight - 150, width: 50, height: 50 }, clickable: true } ] }); } }) }, movetoPosition: function () { this.mapCtx.moveToLocation();//地图中心 }, bindKeyInput: function (e) {//键盘输入 var that = this; if (e.detail.value!= '') { that.setData({ ismap: false }); var BMap = new bmap.BMapWX({ ak: 'bk2GxHHoQiqUKgwLj1wW1GQIbCpcnKri' }); var fail = function (data) { console.log(data) }; var success = function (data) { var sugData = []; for (var i = 0; i < data.result.length; i++) { sugData.push(data.result[i].name) //sugData = sugData + data.result[i].name + '\n'; } that.setData({ sugData: sugData }); } BMap.suggestion({ query: e.detail.value, region: '北京', city_limit: true, fail: fail, success: success }); } }, ok: function (e) {//键盘输入确认e.detail.value var that=this; this.setData({ ismap: true }); wx.request({ url: 'https://api.map.baidu.com/geocoder/v2/?address=' + e.detail.value + '&output=json&ak=bk2GxHHoQiqUKgwLj1wW1GQIbCpcnKri&ret_coordtype=gcj02ll', data: { }, header: { 'content-type': 'application/json' // 默认值 }, success: function (res) { wx.openLocation({ latitude: res.data.result.location.lat, longitude: res.data.result.location.lng, scale: 15, name: e.detail.value // address: "当前位置:" + app.globalData.maddress }) } }) }, danji(e) {//点击列表e.currentTarget.dataset.m var that = this; this.setData({ ismap: true }); wx.request({ url: 'https://api.map.baidu.com/geocoder/v2/?address=' + e.currentTarget.dataset.m + '&output=json&ak=bk2GxHHoQiqUKgwLj1wW1GQIbCpcnKri&ret_coordtype=gcj02ll', data: { }, header: { 'content-type': 'application/json' // 默认值 }, success: function (res) { wx.openLocation({ latitude: res.data.result.location.lat, longitude: res.data.result.location.lng, scale: 15, name: e.currentTarget.dataset.m, // address: "当前位置:" + app.globalData.maddress }) } }) }, bfocus(e){//触发焦点 var that=this; if (e.detail.value!=''){ this.setData({ ismap: false }) } }, lost(){//失去焦点 var that = this; this.setData({ ismap: true }) }, //根据经纬度解析地址 showress:function(){ var that = this; var BMap = new bmap.BMapWX({ ak: '<KEY>' }); var fail = function (data) { console.log(data) }; var success=function(data){ wxMarkerData = data.wxMarkerData; app.globalData.maddress = wxMarkerData[0].address; that.setData({ maddress: wxMarkerData[0].address }); } BMap.regeocoding({ fail: fail, success: success }); }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { this.mapCtx = wx.createMapContext("map"); this.movetoPosition(); }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { wx.showShareMenu({ withShareTicket: true, success(res) { console.log(res) }, fail(res){ console.log(res) } }) } })
faaa2955aaa7373dc4d1bca2d3a0752aa7f40d0a
[ "Markdown", "JavaScript" ]
2
Markdown
duxuyang/map
701b15cec1d240fe7a591c3b0fc44936756ee39a
697271ba8db47b98cc769ca2a0cc9326dbf6c859
refs/heads/master
<file_sep>package com.github.mrdynamo.Project_4; public class FTableException extends Exception { public FTableException(String s) { super(s); } // End constructor } // End FTableException <file_sep>Data Structures CS 341-02 Fall-2020 Programming project 4 for class. To implement ADT Frequency Table using various data structures and analyze the efficiency. <file_sep>package com.github.mrdynamo.Project_4; import java.io.IOException; public interface ADTFrequencyTable { int size(); // Determines the size of the table. // Precondition: // Postcondition: // Throws: boolean isEmpty(); // Determines whether the table is empty. // Precondition: // Postcondition: // Throws: void insert(KeyedItem newItem) throws FTableException; // Inserts a newItem to the table. If newItem is already in the table, increment its count. // Otherwise newItem is inserted to the table with the count 1. // Set the number of comparisons required for this task accordingly. // Precondition: // Postcondition: // Throws: FTableException if frequency table is full. int retrieve(Comparable<String> searchKey); // Retrieves the count of an item with a given searchKey. Return 0 if not found. // Set the number of comparisons required for this task accordingly. // Precondition: // Postcondition: // Throws: void saveFTable(String filename) throws IOException; // Saves the words and their frequencies in the table in the output file filename in the ascending order based on the searchKey. // Precondition: // Postcondition: // Throws: IOException writing the file int getNumOfComps(); // Returns the number of key comparisons required to perform a particular frequency table operation. // (In reality this operation might not be an operation of ADT frequency table. // It is included to obtain the statistics of comparisons. // Precondition: // Postcondition: // Throws: } // End ADTFrequencyTable <file_sep>package com.github.mrdynamo.Project_4; public class TreeNode<K extends Comparable<? super K>> extends KeyedItem<K> { K key; // Key TreeNode<K> leftChild; // Yes answer TreeNode<K> rightChild; // No answer // Initializes tree node with item and no children. public TreeNode(K key) { super(key); leftChild = null; rightChild = null; } // End constructor // Initializes tree node with item and the left and right children references. public TreeNode(K key, TreeNode<K> left, TreeNode<K> right) { super(key); leftChild = left; rightChild = right; } // End constructor } // End TreeNode<file_sep>package com.github.mrdynamo.Project_4; import java.io.FileWriter; import java.io.IOException; public class FTableBST extends BinaryTreeBasis<Word> implements ADTFrequencyTable { private final int MAX_SIZE = 10000; private TreeNode<Word> root; private int numComparisons, numInsertions, totalWordCount, distinctWordCount; // Constructor public FTableBST() { root = null; numComparisons = 0; numInsertions = 0; totalWordCount = 0; distinctWordCount = 0; } // Returns size of BST @Override public int size() { return size(root); } // Returns size of BST public int size(TreeNode<Word> node) { if (node == null) return 0; else return(size(node.leftChild) + 1 + size(node.rightChild)); } // Checks if BST is empty @Override public boolean isEmpty() { return root == null; } // Inserts word into frequency table @Override public void insert(KeyedItem newItem) throws FTableException { if (this.size() > MAX_SIZE) throw new FTableException("FTableException: Frequency table full!"); TreeNode<Word> r = root, prev = null, tmpNode = null; Word tmp = new Word(newItem.toString().toUpperCase(), 1); tmpNode = new TreeNode<Word>(tmp); while (r != null) { prev = r; if (r.getKey().compareTo(tmp) < 0) { r = r.rightChild; } else { r = r.leftChild; } numComparisons++; } if (root == null) { root = tmpNode; totalWordCount++; distinctWordCount++; numComparisons++; } else if (prev.getKey().compareTo(tmp) < 0) { prev.rightChild = new TreeNode<Word>(tmp); totalWordCount++; distinctWordCount++; numComparisons++; } else if (prev.getKey().compareTo(tmp) == 0) { prev.getKey().addCount(1); totalWordCount++; numComparisons++; } else { prev.leftChild = new TreeNode<Word>(tmp); totalWordCount++; distinctWordCount++; numComparisons++; } numInsertions++; } // Returns count of searchKey @Override public int retrieve(Comparable searchKey) { Word tmp = new Word(searchKey.toString().toUpperCase()); TreeNode<Word> tmpNode = findNode(root, tmp); if (tmpNode == null) return 0; else return tmpNode.getKey().getCount(); } // Saves frequency table to file @Override public void saveFTable(String fileName) throws IOException { FileWriter writer = new FileWriter(fileName); writer.write("total_number_of_words: " + this.getTotalWordCount() + System.lineSeparator()); writer.write("total_number_of_distinct_words: " + this.getDistinctWordCount() + System.lineSeparator()); writer.write(System.lineSeparator()); writer.write("number_of_comparisons: " + this.getNumOfComps() + System.lineSeparator()); writer.write(inOrder()); writer.write(System.lineSeparator()); writer.close(); } // Returns number of comparisons made @Override public int getNumOfComps() { return numComparisons; } // Return total word count public int getTotalWordCount() { return this.totalWordCount; } // Return distinct word count public int getDistinctWordCount() { return this.distinctWordCount; } // Sets root item of BST @Override public void setRootItem(Word key) { this.root = new TreeNode<Word>(key); } // InOrder traversal private String inOrder() { return inOrder(this.root); } // InOrder traversal private String inOrder(TreeNode<Word> node) { String tmp = ""; if (node != null) { tmp += inOrder(node.leftChild) + System.lineSeparator(); tmp += node.getKey().toString().toUpperCase() + " " + node.getKey().getCount(); tmp += inOrder(node.rightChild); } return tmp; } private TreeNode<Word> findNode(TreeNode<Word> node, Word w) { // Base Cases: root is null or key is present at root numComparisons++; if (node == null || node.getKey().compareTo(w) == 0) return node; numComparisons++; // Key is greater than root's key if (node.getKey().compareTo(w) < 0) return findNode(node.rightChild, w); numComparisons++; // Key is smaller than root's key return findNode(node.leftChild, w); } } // End FTableBST <file_sep>package com.github.mrdynamo.Project_4; public abstract class BinaryTreeBasis<K extends Comparable<? super K>> { protected TreeNode<K> root; public BinaryTreeBasis() { root = null; } public BinaryTreeBasis(K key) { root = new TreeNode<K>(key, null, null); } public boolean isEmpty() { // Returns true if the tree is empty, else returns false. return root == null; } public void makeEmpty() { // Removes all nodes from the tree. root = null; } public K getRootItemKey() throws TreeException { // Returns the item in the tree's root. if (root == null) { throw new TreeException("TreeException: Empty tree"); } else { return root.key; } // end if } public abstract void setRootItem(K key); // Throws UnsupportedOperationException if operation // is not supported. } // End BinaryTreeBasis
163a34dde47cea6079d6c3a4a9e4e6ab788eb5dd
[ "Markdown", "Java" ]
6
Java
MrDynamo/Data-Structures_Project-4
ca1cf0b66d892aabe5651cfc2ed378562845f569
d97d146d0cefb8e722bc402ff3009a38d3c31b93