changeset 8:e2c6cfe8c6b7

JSON logs and presets.
author Robert Tubb <rt300@eecs.qmul.ac.uk>
date Thu, 10 Jan 2013 18:24:26 +0000
parents 845ea04f8e33
children 346807b47860
files eventLogger.h eventLogger.mm frequencer.mm grid.mm presetManager.h presetManager.mm testApp.h testApp.mm
diffstat 8 files changed, 394 insertions(+), 191 deletions(-) [+]
line wrap: on
line diff
--- a/eventLogger.h	Thu Dec 06 18:26:51 2012 +0000
+++ b/eventLogger.h	Thu Jan 10 18:24:26 2013 +0000
@@ -11,6 +11,7 @@
 #ifndef __oscSenderExample__eventLogger__
 #define __oscSenderExample__eventLogger__
 
+#define EVENT_LOG_FILENAME "log.json"
 
 #include "ofMain.h"
 #include "ofxiPhone.h"
@@ -21,8 +22,16 @@
 #include <string>
 #include <map>
 #include "2dvector.h"
+#include "json.h"
+
+#import "iViewController.h"
+
+
+
 enum leventType {SAVE_PRESET, SAVE_DESET, SCROLL, SCROLL_STOPPED, ZOOM, CHANGE_SLIDER, SWAP_VIEW, SET_MIN_ZOOM, SET_MAX_ZOOM};
 
+//---------------------------------------------------------------------------
+
 class lEvent{
 public:
     // try and make this as compact as possible.
@@ -30,14 +39,29 @@
     double val1; // x coord, scale if zoom
     double val2; // y coord, 0 if zoom
     int sliderID;
-    lEvent(leventType eType, double v1, double v2 = 0.0,int sID = 0){
+    lEvent(leventType eType, double v1 = 0.0, double v2 = 0.0,int sID = 0){
         eventType = eType;
         val1 = v1;
         val2 = v2;
         sliderID = sID;
     }
+    lEvent(const Json::Value &jevt){
+        eventType = (leventType)jevt["eventType"].asInt();
+        val1 = jevt["val1"].asFloat();
+        val2 = jevt["val2"].asFloat();
+        sliderID = jevt["sliderID"].asInt();
+    }
+    Json::Value eventToJson(){
+        Json::Value jevt;
+        jevt["eventType"] = eventType;
+        jevt["val1"] = val1;
+        jevt["val2"] = val2;
+        jevt["sliderID"] = sliderID;
+        return jevt;
+    }
 };
 //---------------------------------------------------------------------------
+// streams no longer used
 inline istream& operator>>(istream & is, lEvent& e){
     is.setf(ios_base::fixed,ios_base::floatfield);
     is.precision(1);
@@ -73,20 +97,24 @@
     
     vector<lEvent> theEvents;
     
-    unsigned int deviceID; // get something from hardware??
+    
+    // values applicable to all events
+    unsigned int deviceID; // unique get something from hardware??
     unsigned int totalInteractionTime, sessionTime, sessionStartTime;
-    string userName;
-    
+    string userName; // not unique
+    unsigned int nextUploadQty;
     EventLogger();
     void init();
-    
+    void setUsername(const char *u);
     void logEvent(const leventType& evtType,const TwoVector& centre = TwoVector(), const double& scale = 1.0, const int& sliderID = -1, const double& sliderVal = 0.0);
     void logEvent(const leventType& evtType,const int& sliderID, const double& sliderVal);
     void sendHttp();
     void checkLogFile();
-    void attemptUpload();
+    bool attemptUpload();
     void firstEverAppOpen();
+    void readJsonToLog(const string &jsonFile);
     void exitAndSave();
+    Json::Value logsToJson();
     void printAll(){
         cout << "ALL LOGGED EVENTS!: \n";
         vector<lEvent>::iterator evIter;
@@ -98,6 +126,7 @@
 };
 
 
-    
+    //---------------------------------------------------------------------------
+   
 
 #endif /* defined(__oscSenderExample__eventLogger__) */
--- a/eventLogger.mm	Thu Dec 06 18:26:51 2012 +0000
+++ b/eventLogger.mm	Thu Jan 10 18:24:26 2013 +0000
@@ -6,25 +6,111 @@
 //
 //
 
-
+//---------------------------------------------------------------------------
 #include "eventLogger.h"
 
+
 EventLogger eventLogger;
+extern IViewController *iViewController;
 
+//---------------------------------------------------------------------------
 EventLogger::EventLogger(){
+
+    loggingEnabled = true;
+ 
+}
+//---------------------------------------------------------------------------
+void EventLogger::init(){
     
-    // if first time opened request a user ID from the server... use time?
-    loggingEnabled = true;
+    readJsonToLog(ofxiPhoneGetDocumentsDirectory() + EVENT_LOG_FILENAME);
+    sessionStartTime = ofGetSystemTime();
 
+}
+//---------------------------------------------------------------------------
+void EventLogger::readJsonToLog(const string &jsonFile){
+    Json::Value root;
+    Json::Reader reader;
     
     
+    ifstream theFile(jsonFile.c_str());
+    stringstream fileText;
+    string line;
+    if(!theFile){
+        cout<<"no event log file - first APP open\n";
+        
+        firstEverAppOpen();
+        
+        return;
+    }else{
+        
+        while(theFile){
+            theFile >> line;
+            cout << line;
+            fileText << line;
+            
+        }
+        
+        theFile.close();
+    }
+    
+    bool parsingSuccessful = reader.parse( fileText.str(), root );
+    
+    if ( !parsingSuccessful )
+    {
+        // report to the user the failure and their locations in the document.
+        std::cout  << "Failed to parse preset JSON\n"
+        << reader.getFormattedErrorMessages();
+        return;
+    }
+    
+    // now put user deets into variables
+    userName = root["userName"].asString();
+    deviceID = root["deviceID"].asLargestInt();
+    totalInteractionTime = root["totalInteractionTime"].asLargestInt();
+    
+    // check for unuploaded evts
+    const Json::Value jlogs = root["events"];
+    
+    for ( int index = 0; index < jlogs.size(); ++index ) theEvents.push_back(lEvent(jlogs[index]));
+    if(theEvents.size() > 5000){
+        //try to upload
+        attemptUpload();
+    }
+    // TODO if the total interaction time is greater than a certain amount && no questions answered - questionnaire time!
+    
+    // is there logged stuff that hasn't been uploaded yet?
+    
+    // don't actually need to load old ones unless uploading? or saving...
+    //while(eventLogFile >> nextLine){
+    
+    //}
+    
+    //printAll();
+    
 }
 
-void EventLogger::init(){
-    checkLogFile();
-    sessionStartTime = ofGetSystemTime();
+//----------------------------------------------------------------------------
+
+//---------------------------------------------------------------------------
+
+void EventLogger::firstEverAppOpen(){
+    deviceID = ofGetSystemTimeMicros();
+    
+    [iViewController showUserNamePrompt:23];
+    
+    totalInteractionTime = 0;
+    
+    
+}
+//---------------------------------------------------------------------------
+// called from alertView OK in iViewController
+void EventLogger::setUsername(const char *u){
+    userName = u;
 
 }
+
+//---------------------------------------------------------------------------
+// log zoom event
 void EventLogger::logEvent(const leventType& evtType,const TwoVector& centre, const double& scale, const int& sliderID, const double& sliderVal){
     //cout << "log: " << evtType << "\n";
     
@@ -62,7 +148,7 @@
             // Code
             break;
     }
-    if(theEvents.size() > 5000){
+    if(theEvents.size() > nextUploadQty){
         //try to upload
         attemptUpload();
     }
@@ -70,6 +156,8 @@
     
     
 }
+//---------------------------------------------------------------------------
+// log slider event
 void EventLogger::logEvent(const leventType& evtType,const int& sliderID, const double& sliderVal){
     if(!loggingEnabled) return;
     // sliderThinFactor
@@ -81,19 +169,34 @@
             // Code
             break;
     }
-    if(theEvents.size() > 5000){
+    if(theEvents.size() > nextUploadQty){
         //try to upload
-        attemptUpload();
+        bool uploaded = attemptUpload();
+
     }
 }
-void EventLogger::attemptUpload(){
+//---------------------------------------------------------------------------
+
+bool EventLogger::attemptUpload(){
+    bool uploaded;
     
-    //if(fail){
+    // do simple check of internet connection ?
+    // if not connected return
+    
+    // if numlogs > 500000 show alert...
+    
+    if(!uploaded){
         // try later
-    //}
+        nextUploadQty += 5000;
+    }else{
     
-    // if success - clear memory
+        // if success - clear memory
+        theEvents.clear();
+    }
+    return uploaded;
+    
 }
+//---------------------------------------------------------------------------
 void EventLogger::sendHttp(){
     
     string url = "http://www.rootnot.co.uk/cgi-bin/zoomlogs.cgi";
@@ -105,68 +208,46 @@
     cout << "HTTP DATA  " << resp.data << "\n";
 }
 
-void EventLogger::checkLogFile(){
 
-    string fname = ofxiPhoneGetDocumentsDirectory() + "eventlog.dat";
-    ifstream eventLogFile(fname.c_str());
-    // have we opened the app before? if so get device ID and userName
-    //string firstLine, nextLine;
-    if(!eventLogFile){
-        cout<<"no event log file - first APP open\n";
-        
-        firstEverAppOpen();
-        
-        return;
-    }
-    eventLogFile >> deviceID;
-    eventLogFile >> userName;
-    eventLogFile >> totalInteractionTime;
-    
-    cout << "DeviceID" << deviceID << '\n';
-    cout << "userName" << userName << '\n';
-    cout << "totalInteractionTime" << totalInteractionTime << '\n';
-    
-    
-    // is there logged stuff that hasn't been uploaded yet?
-    
-    // don't actually need to load old ones unless uploading? or saving...
-    //while(eventLogFile >> nextLine){
-        
-    //}
-    
-    eventLogFile.close();
 
-}
-
-void EventLogger::firstEverAppOpen(){
-    deviceID = ofGetSystemTimeMicros();
-    
-    // somehow prompt for username
-    userName = "Dennis";
-    totalInteractionTime = 0;
-}
+//---------------------------------------------------------------------------
 
 void EventLogger::exitAndSave(){
+    totalInteractionTime = totalInteractionTime + (ofGetSystemTime() - sessionStartTime);
     // save user details
-    string fname = ofxiPhoneGetDocumentsDirectory() + "eventlog.dat";
-    ofstream logFile(fname.c_str());
-    logFile << deviceID << '\n';
-    logFile << userName << '\n';
-    totalInteractionTime = totalInteractionTime + sessionTime;
-    logFile << totalInteractionTime << '\n';
+    string fname = ofxiPhoneGetDocumentsDirectory() + EVENT_LOG_FILENAME;
+
+    Json::Value jlogs = logsToJson();
+    // try to upload
+    bool uploaded = attemptUpload();
     
-    if(theEvents.size() > 0){
-        attemptUpload();
+    // write to file
+    
+    ofFile logFile(fname,ofFile::WriteOnly);
 
-        // if (failed upload) save logged evts to file
-        cout << "Saving un-uploaded logs\n";
-        vector<lEvent>::iterator evtIter;
-        
-        for(evtIter = theEvents.begin(); evtIter < theEvents.end(); evtIter++){
-            
-            logFile << *evtIter << "\n";
-        }
+    logFile << jlogs;
+    
+}
+//---------------------------------------------------------------------------
+
+Json::Value EventLogger::logsToJson(){
+    // put all logged events into Json formatted string
+    Json::Value root;
+
+    vector<lEvent>::iterator eventIter;
+    
+    root["userName"] = userName;
+    root["deviceID"] = deviceID;
+    root["totalInteractionTime"] = totalInteractionTime;
+    
+    int i = 0;
+    for(eventIter = theEvents.begin(); eventIter < theEvents.end(); eventIter++){
+        root["events"][i] = (*eventIter).eventToJson();
+        i++;
     }
-    logFile.close();
- 
-}
\ No newline at end of file
+    
+    return root;
+}
+//---------------------------------------------------------------------------
+//---------------------------------------------------------------------------
+//---------------------------------------------------------------------------
--- a/frequencer.mm	Thu Dec 06 18:26:51 2012 +0000
+++ b/frequencer.mm	Thu Jan 10 18:24:26 2013 +0000
@@ -31,8 +31,6 @@
     // calculate transform
     dft();
 
-    //TODO  output freq domain - to PD
-
 }
 
 void Frequencer::timeEdit(vector<double> allValues){
--- a/grid.mm	Thu Dec 06 18:26:51 2012 +0000
+++ b/grid.mm	Thu Jan 10 18:24:26 2013 +0000
@@ -33,8 +33,8 @@
     pixSize.setCoord(ofGetWidth(), ofGetHeight());
  
     //set scale and position to mid way
-    scale = pow(32.0,6.0);
-    snapDist = TwoVector(10,10);
+    scale = pow(32.0,3.0);
+    snapDist = TwoVector(9,9);
     snapped = false;
     
     size.setCoord(pixSize.x*scale, pixSize.y*scale);
@@ -371,10 +371,7 @@
     presetManager.drawPresetsInRange(topLeft, topLeft + size);
     // draw snapped preset info
     if(snapped && closestPreset != NULL){
-    ostringstream temp;
-    temp << "Name: \t" << closestPreset->name << "\nCreation time: \t" << closestPreset->savetime << '\n';
-    string s = temp.str();
-    ofDrawBitmapString( s, pixSize.x/2+10, pixSize.y/2+10 );
+        ofDrawBitmapString( closestPreset->displayTextDescription(), pixSize.x/2+10, pixSize.y/2+10 );
     }
 }
 
--- a/presetManager.h	Thu Dec 06 18:26:51 2012 +0000
+++ b/presetManager.h	Thu Jan 10 18:24:26 2013 +0000
@@ -6,65 +6,89 @@
 //
 //
 
+// defines:
+//      PresetManager
+// and Preset
+
 #ifndef __oscSenderExample__presetManager__
 #define __oscSenderExample__presetManager__
 
+#define PRESET_FILENAME "presets.json"
+
 #include <iostream>
+#include <string>
 #include "ofMain.h"
 #include "ofxiPhone.h"
 #include "ofxiPhoneExtras.h"
 #include "2dvector.h"
 #include "grid.h"
+#include "eventLogger.h"
+#include "json.h"
+
+#import "iViewController.h"
+
+
 
 
 //---------------------------------------------------------------------------
 class Preset{
 public:
-    string userName;
-    int presetID;
-    string name;
-    long long savetime;
-    vector<ofColor> pixVals;
-    double timemsd = [NSDate timeIntervalSinceReferenceDate];
-    
-    TwoVector coordinates;
+    // important details - these saved to file (uploaded?)
+    string          creatorUserName;
+    unsigned int    creatorDeviceID; // unique user device ID
+    string          name; // name of preset
+    long long       creationTime; // datetime that preset was created
+    vector<ofColor> pixVals; // hmmm
+    TwoVector       coordinates;  // position on grid
     
     // from save button press
-    Preset(TwoVector acoord, string aname,int aID, const vector<ofColor> & pixCols){
+    Preset(TwoVector acoord, string aname,int aID, string un, unsigned int uid){
         coordinates = acoord;
         name = aname;
-        presetID = aID;
+        creatorUserName = un;
+        creatorDeviceID = uid;
+        double timemsd = [NSDate timeIntervalSinceReferenceDate];
+        creationTime = (long long)(timemsd*1000);
+        pixVals = makePresetPicture(coordinates);
         
-        timemsd = [NSDate timeIntervalSinceReferenceDate];
-        savetime = (long long)(timemsd*1000);
-        pixVals = pixCols;
-        
-
-    };
-    Preset(int aID){
-        coordinates.setCoord(0.0,0.0);
-        name = "Blank";
-        presetID = aID;
-        timemsd = [NSDate timeIntervalSinceReferenceDate];
-        savetime = (long long)(timemsd*1000);
         
     };
+    // from json value
+    Preset(Json::Value jval){
+        
+        // CRAHSED!!!!!
+        name = jval["name"].asString();
+        creatorUserName = jval["creatorUserName"].asString();
+        creatorDeviceID = jval["creatorDeviceID"].asUInt();
+        coordinates.x = jval["coordinates"].get("x", 0.0).asFloat();
+        coordinates.y = jval["coordinates"].get("y", 0.0).asFloat();
+        creationTime = jval["creationTime"].asLargestInt();
+        pixVals = makePresetPicture(coordinates);
 
-    // from file load
-    Preset(TwoVector acoord, string aname,int aID, long long stime, const vector<ofColor> & pixCols){
+    }
+    // from preset file load
+    Preset(TwoVector acoord, string aname,int aID, long long stime){
         coordinates = acoord;
         name = aname;
-        presetID = aID;
-        savetime = stime;
-        pixVals = pixCols;
+        creationTime = stime;
+        pixVals = makePresetPicture(coordinates);
         
     };
     
+    // from download request??
+    
     void draw();
-
+    Json::Value presetToJson();
+    vector<ofColor> makePresetPicture(TwoVector coord);
+    
+    string displayTextDescription(){
+        stringstream ss;
+        ss << "Name: \t" << name << "\nCreation time: \t" << creationTime << "\nCreator: \t" << creatorUserName <<  "\nCreator ID: \t" << creatorDeviceID << '\n';
+        return ss.str();
+        
+    }
 };
 
-
 //---------------------------------------------------------------------------
 class PresetManager{
 public:
@@ -75,35 +99,42 @@
     // find and return all(?) presets within a certain coordinate range
     vector<Preset *> thePresets; // we want vector ? or list? pointers using new?
     
-    int addPreset(TwoVector coord, string name); // returns id or negative error number
+    int addPreset(string name); // returns id or negative error number
     int loadPreset(const TwoVector coord, const string name, long long stime);
     
     TwoVector recallPreset(int presetID); // by name ? id?
     TwoVector recallPreset(string name); // by name ? id?
     vector<Preset *>  getPresetsInRange(TwoVector min, TwoVector max);
     void drawPresetsInRange(const TwoVector min, const TwoVector max);
-    vector<ofColor> makePresetPicture(TwoVector coord);
     void printAll();
     
     void startupLoadAll();  // get stuff from XML
     void exitAndSaveAll();  // save to XML, delete presets array (?)
     void clearAll();
+    Json::Value  allPresetsToJson();
+    void readJsonToPresets(const string &jsonFile);
     
     PresetManager();
 };
 
 
 //---------------------------------------------------------------------------
+// this is the function that 'saves' a single preset as formatted text
+// replaced with presetToJson
 inline ostream& operator<<(ostream & os, const Preset& p){
     os.setf(ios_base::fixed,ios_base::floatfield);
     os.precision(1);
     
-    os << p.savetime << ',' << p.coordinates.x << ',' << p.coordinates.y << '\n';
+    // change this to JSON
+    
+    os << p.creationTime << p.coordinates.x << ',' << p.coordinates.y << '\n';
     
     return os;
 }
     
-    //---------------------------------------------------------------------------
+//---------------------------------------------------------------------------
+// this is the function that 'reads' all presets as formatted text
+    // replaced with jsonFromPreset or somesuch
     inline istream& operator>>(istream & is, PresetManager& p)
     {
         //um
--- a/presetManager.mm	Thu Dec 06 18:26:51 2012 +0000
+++ b/presetManager.mm	Thu Jan 10 18:24:26 2013 +0000
@@ -11,9 +11,25 @@
 //---------------------------------------------------------------------------
 extern Grid theGridView;
 PresetManager presetManager;
+extern EventLogger eventLogger;
+extern IViewController *iViewController;
+//---------------------------------------------------------------------------
+vector<ofColor> Preset::makePresetPicture(TwoVector coord){
+    // convert midi parameters to a nice piccy
+    vector<int> params = theGridView.calculateParamsFromCoord(coord);
+    vector<ofColor> pixCols;
+    
+    ofColor col(255,0,0);
+    for(int i=0; i<9;i++){
+        col.setHue(params[i]*2);
+        pixCols.push_back(col);
+    }
+    return pixCols;
+}
 //---------------------------------------------------------------------------
 void Preset::draw(){
-    //
+    // TODO bit stupid actually. make it a shaded ball / dot 
+    
     int sz = 2;
     TwoVector pos = theGridView.coordToPixel(coordinates); // euch -rely on grid view?
     
@@ -55,14 +71,88 @@
     ofRect(pos.x-sz, pos.y-sz,sz,sz);
 };
 //---------------------------------------------------------------------------
+Json::Value Preset::presetToJson(){
+    // create the string for this instance of Preset object
+    
+    Json::Value presetVal;
+    
+    presetVal["creatorUserName"] = creatorUserName;
+    presetVal["creatorDeviceID"] = creatorDeviceID;
+    presetVal["creationTime"] =     creationTime;
+    presetVal["name"] =             name;
+    presetVal["coordinates"]["x"] = coordinates.x;
+    presetVal["coordinates"]["y"] = coordinates.y;
+    
+    
+    return presetVal;
+}
+//---------------------------------------------------------------------------
 PresetManager::PresetManager(){
     timesOpened = 0;
     nextID = 0;
-
+   
     string ts = ofGetTimestampString();
     cout << "ofGetTimestampString: " << ts << '\n';
 }
+//---------------------------------------------------------------------------
+Json::Value PresetManager::allPresetsToJson(){
+    Json::Value root;
+ 
+    // use jsoncpp
+    vector<Preset *>::iterator presetIter;
 
+    root["something"] = 23;
+    
+    int i = 0;
+    for(presetIter = thePresets.begin(); presetIter < thePresets.end(); presetIter++){
+        root["presets"][i] = (*presetIter)->presetToJson();
+        i++;
+    }
+    
+    return root;
+}
+//---------------------------------------------------------------------------
+void PresetManager::readJsonToPresets(const string &jsonFile){
+    Json::Value root;
+    Json::Reader reader;
+
+    
+    ifstream theFile(jsonFile.c_str());
+    stringstream fileText;
+    string line;
+    if(!theFile){
+        cout<<"can't find preset file \n";
+        
+    }else{
+        
+        while(theFile){
+            theFile >> line;
+            cout << line;
+            fileText << line;
+            
+        }
+        
+        theFile.close();
+    }
+    
+    bool parsingSuccessful = reader.parse( fileText.str(), root );
+
+    if ( !parsingSuccessful )
+    {
+        // report to the user the failure and their locations in the document.
+        std::cout  << "Failed to parse preset JSON\n"
+        << reader.getFormattedErrorMessages();
+        return;
+    }
+
+    // now put into variables
+    const Json::Value jpresets = root["presets"];
+    
+    for ( int index = 0; index < jpresets.size(); ++index ) thePresets.push_back(new Preset(jpresets[index]));
+    
+    //printAll();
+     
+}
 //---------------------------------------------------------------------------
 void PresetManager::printAll(){
     cout << "ALL PRESETS: \n";
@@ -73,8 +163,8 @@
     }
 }
 //---------------------------------------------------------------------------
-
-int PresetManager::addPreset(const TwoVector coord, const string name){
+// when save button pressed
+int PresetManager::addPreset(const string name){
 
     
     // check for same name
@@ -92,32 +182,17 @@
         return -2;
         
     }
-    
-    // make piccy
-    vector<ofColor> presetPicture = makePresetPicture(coord);
-    thePresets.push_back(new Preset(coord, name,nextID, presetPicture));
+    // yuk shouldn't have to know about eventlogger and grid view...
+    thePresets.push_back(new Preset(theGridView.getCoord(), name,nextID, eventLogger.userName, eventLogger.deviceID));
     
     // if ok
     return nextID++;
 }
-//---------------------------------------------------------------------------
-vector<ofColor> PresetManager::makePresetPicture(TwoVector coord){
-    // convert midi parameters to a nice piccy
-    vector<int> params = theGridView.calculateParamsFromCoord(coord);
-    vector<ofColor> pixCols;
-    
-    ofColor col(255,0,0);
-    for(int i=0; i<9;i++){
-        col.setHue(params[i]*2);
-        pixCols.push_back(col);
-    }
-    return pixCols;
-}
+
 //---------------------------------------------------------------------------
 
 int PresetManager::loadPreset(const TwoVector coord, const string name, long long stime){
-    vector<ofColor> presetPicture = makePresetPicture(coord); // or just store it??
-    thePresets.push_back(new Preset(coord, name,nextID, stime, presetPicture));
+    thePresets.push_back(new Preset(coord, name,nextID, stime));
    
      // if ok
     return nextID++;
@@ -154,45 +229,29 @@
     }
  
 }
-//---------------------------------------------------------------------------
+//----------------------------------------------cu-----------------------------
 void PresetManager::startupLoadAll(){
-  // get stuff from file
+    // get stuff from file
     // load file
-  
-    string fname = ofxiPhoneGetDocumentsDirectory() + "presets.dat";
-    ifstream presetFile(fname.c_str());
 
-    // simply prints file
-
-    if(!presetFile){
-        cout<<"no preset file";
-        return;
-    }
-    while(presetFile >> *this);
+    string fname = ofxiPhoneGetDocumentsDirectory() + PRESET_FILENAME;
     
-    //TODO get presets from online database...
+    readJsonToPresets(fname);
     
-    presetFile.close();
-
     timesOpened++;
 }
+
 //---------------------------------------------------------------------------
 void PresetManager::exitAndSaveAll(){
-    ofFile presetFile(ofxiPhoneGetDocumentsDirectory() +"presets.dat",ofFile::WriteOnly);
+    ofFile presetFile(ofxiPhoneGetDocumentsDirectory() +PRESET_FILENAME,ofFile::WriteOnly);
     
-    cout << "Exit and save presets\n";
-    vector<Preset *>::iterator presetIter;
-
-    for(presetIter = thePresets.begin(); presetIter < thePresets.end(); presetIter++){
-        //vector<int> params;
-        //params = theGridView.calculateParamsFromCoord((*presetIter)->coordinates);
-        presetFile << **presetIter << "\n";
-    }
-    presetFile.close();
+    // stick all the stuff in a json value
+    Json::Value root = allPresetsToJson();
     
-    // TODO dleete all the new events??
+    cout << root;
+    presetFile << root;
+     
     
-
 }
 
 //---------------------------------------------------------------------------
--- a/testApp.h	Thu Dec 06 18:26:51 2012 +0000
+++ b/testApp.h	Thu Jan 10 18:24:26 2013 +0000
@@ -15,6 +15,10 @@
 #include "ofxPd.h"
 #include "frequencer.h"
 
+#include "json.h"
+
+#import "iViewController.h"
+
 #define HOST "169.254.1.1"
 #define PORT 12345
 
@@ -27,6 +31,7 @@
     int prevTouchX;
     int prevTouchY;
     double prevDist;
+    
     // not many so dont bother with vectors/arrays?
     TwoVector touch0;
     TwoVector touch1;
--- a/testApp.mm	Thu Dec 06 18:26:51 2012 +0000
+++ b/testApp.mm	Thu Jan 10 18:24:26 2013 +0000
@@ -5,10 +5,10 @@
 extern PresetManager presetManager;
 extern EventLogger eventLogger;
 extern Frequencer frequencer;
+extern IViewController *iViewController;
 //DeviceID3523537000
 //--------------------------------------------------------------
 void testApp::setup(){
-	ofSetOrientation(OF_ORIENTATION_90_LEFT);
 
 	ofBackground( 0, 0, 0 );
     ofEnableAlphaBlending();
@@ -55,14 +55,15 @@
     freqIndexes.push_back(6);
     freqIndexes.push_back(7);
     freqIndexes.push_back(8);
+
+    ofxiPhoneDeviceType device = ofxiPhoneGetDeviceType();
+    cout << "Device: " << device << '\n';
     
-    keyboard = new ofxiPhoneKeyboard(500,380,320,32);
-	keyboard->setVisible(false);
-	keyboard->setBgColor(255, 255, 255, 255);
-	keyboard->setFontColor(0,0,0, 255);
-	keyboard->setFontSize(26);
+    ofxiPhoneSetOrientation( OF_ORIENTATION_DEFAULT ); // TODO orientation CRAP
+
     
-    ofxiPhoneSetOrientation( OF_ORIENTATION_90_RIGHT );
+    //NSString * q = @"Why the hell did you do that? Are you mad?";
+    //[iViewController showQuestionPrompt:q];
     
 //-----------------
     // the number if libpd ticks per buffer,
@@ -116,13 +117,13 @@
         if(((ofxUIButton *)e.widget)->getValue()){
             cout << "SAVE PRESET\n";
             stringstream n;
-            double timemsd = [NSDate timeIntervalSinceReferenceDate];
-            long long timems = (long long)(timemsd*1000);
-            n << "P" << timems;
+            //double timemsd = [NSDate timeIntervalSinceReferenceDate];
+            //long long timems = (long long)(timemsd*1000);
+            //n << "P" << timems;
             string name = n.str();
-            
-            presetManager.addPreset(theGridView.getCoord(),name);
-            eventLogger.logEvent(SAVE_PRESET, theGridView.getCoord());
+    
+            [iViewController showPresetNamePrompt:32];
+
         }
         /*
         if(!keyboard->isKeyboardShowing()){
@@ -147,10 +148,10 @@
     }else if(e.widget->getName() == "ZOOM MAX")
     {
         if(((ofxUIButton *)e.widget)->getValue()){
-        cout << "ZOOM MAX\n";
+            cout << "ZOOM MAX\n";
             theGridView.setMaxZoom();
             eventLogger.logEvent(SET_MAX_ZOOM);
-            //eventLogger.printAll();
+
         }
     }else{
         cout << "GUI error :  unknown event recieved\n";
@@ -290,11 +291,7 @@
     }
     
     core.pd.sendList("fromOF", seqSteps);
-    //core.pd.sendMessage("fromOF", "msg", seqSteps);
-    
-    // implement synth param calculations here?
-    // oscshape,  filt type , cut off, envelope, mod freq (fm for sine, ? for pulse, sync for saw) 
-    // oscillators:
+
     sendOscShape(sliderVals[5]);
     sendFiltType(sliderVals[6]);
     sendFiltFreq(sliderVals[7]);
@@ -302,6 +299,7 @@
     sendModFreq(sliderVals[9]);
     
 }
+//--------------------------------------------------------------
 #pragma mark STANDARD OF FUNCTIONS
 //--------------------------------------------------------------
 void testApp::update(){
@@ -570,7 +568,7 @@
 //--------------------------------------------------------------
 void testApp::deviceOrientationChanged(int newOrientation){
     cout << "orientation: " << newOrientation;
-    keyboard->updateOrientation(); // takes ages , only applies to text box
+    //keyboard->updateOrientation(); // takes ages , only applies to text box
     if(newOrientation == 4){
         ofxiPhoneSetOrientation( OF_ORIENTATION_90_RIGHT );
     }else if(newOrientation == 3){
@@ -636,7 +634,7 @@
     
     return y0;
 }
-
+//---------------------------------------------------------------
 void testApp::sendOscShape(int ctrlin){
     
     static int numpoints = 5;
@@ -667,6 +665,7 @@
     }
     
 }
+//---------------------------------------------------------------
 void testApp::sendFiltType(int ctrlin){
     static int numpoints = 3;
     static int numcontrols = 4;
@@ -693,6 +692,7 @@
         //cout << ctrlName[i] << "sending" << ctrlout[i] << "\n";
     }
 }
+//---------------------------------------------------------------
 void testApp::sendFiltFreq(int ctrlin){
     List toPD;
     
@@ -701,6 +701,7 @@
     
     core.pd.sendList("fromOF", toPD);
 }
+//---------------------------------------------------------------
 void testApp::sendEnvShape(int ctrlin){
     static int numpoints = 5;
     static int numcontrols = 3;
@@ -729,6 +730,7 @@
         //cout << ctrlName[i] << "sending" << ctrlout[i] << "\n";
     }
 }
+//---------------------------------------------------------------
 void testApp::sendModFreq(int ctrlin){
     float fm = ctrlin/127.;
     List toPD;
@@ -737,4 +739,5 @@
     toPD.addFloat(fm); // rounding here??
     
     core.pd.sendList("fromOF", toPD);
-}
\ No newline at end of file
+}
+//---------------------------------------------------------------
\ No newline at end of file