Tuesday 5 August 2014

Coding a file explorer.

I've started work on the beginnings of a file explorer.

There's nothing much to it at the moment but I thought I'd share it in case it's some help to somebody.

I hope that one day it may become the basis of a tutorial but obviously there's quite a way to go.

So far, I've only tested it on a Tesco hudl tablet but I'm reasonably happy with it so far.

The spk with the minimal code I have at the moment is available at http://hudl.sgarman.net/public/spk/SJGexplorer_001.spk

In text form, it looks like this

//Simple file explorer by Steve Garman

var basePath = "/sdcard"

//Called when application is started.
function OnStart()
{
    //Create a layout with objects vertically centered.
    lay = app.CreateLayout( "linear", "Vertical,FillXY" );    

    //Create a text label and add it to layout.
    currPath = app.CreateText( basePath );
    lay.AddChild( currPath );

    //Get list of files in current path into an array
    filelist = app.ListFolder( currPath.GetText()).split(",");
    filelist.sort();
    //use array to populate detail list
    detail = app.CreateList( filelist );
    detail.SetOnTouch( detailTouch);
    lay.AddChild( detail );
   
    //Add layout to app.    
    app.AddLayout( lay );

    //make back key available for use
    app.EnableBackKey( false );

}

function populate_detail(){
  //called whenever current path changed
  filelist = app.ListFolder( currPath.GetText() ).split(",") ;
  filelist.sort();
  detail.SetList(filelist.join(","),",");
}

function detailTouch(name){
  //user has touched a name in detail list
  var fullPath = currPath.GetText() + "/" + name
  if( testFolder(fullPath) ){
    //it's a folder with files
    //show it
    currPath.SetText( fullPath );
    populate_detail();
  }
  else{
    deal_with_file( fullPath );
    
  }
}

function testFolder( fullPath ){
  //no proper test for folders
  //in this app, it's safe to treat an empty folder like a file
  var tst = app.ListFolder( fullPath );
  if( tst.length > 0 ) return true;
  else return false;
};

function deal_with_file( fullpath ){
  app.ShowPopup("No action defined for " + fullpath);
}

function OnBack(){
  //user pressed back key
  var tmp = currPath.GetText();
  if( tmp == basePath ) app.Exit();
  else {
    //not yet back at beginning
    //move up one level
    var tst = currPath.GetText().split("/");
    tmp = tst.pop();
    currPath.SetText( tst.join("/") );
    populate_detail();
  }
}

1 comment:

  1. If you want to prove it's looking at the actual files, the following minor change to the deal_with_file function will attempt to display any .txt or .js file you select.

    function deal_with_file( fullpath ){
      if( fullpath.indexOf(".js" ) >= 0 ||
          fullpath.indexOf(".txt" ) >= 0 )
        alert (app.ReadFile(fullpath));
      
      else app.ShowPopup("No action defined for " + fullpath);
    }

    ReplyDelete