How to send data from flash player into an external executable through a pipe - actionscript-3

I want to send data generated by a flash module into an external executable in windows. From what I've learnt about interprocess communication, I think it is appropriate to use pipes in this case. I am using Flash professional CS5 and when a 'trace' command is used in actionscript the ouput will be displayed in the output window in flash professional. I think Flash pipes the data into the output window and if so is it possible to obtain the handle to that pipe. Is there a way by which I can write the output from flash player itself when the trace commands are executed or the data generated on an event directly into the buffer of a pipe.
Please help me out.
Thanks in advance.

I did some tricks using a Flash Badge, AIR app. and C# console app..
We can send params to an AIR app. from BADGE and receive it using:
protected function onInit(event:FlexEvent):void{
NativeApplication.nativeApplication.addEventListener(BrowserInvokeEvent.BROWSER_INVOKE, onBrowserInvoke);}
protected function onBrowserInvoke(e:BrowserInvokeEvent):void{
//reading args
var a:String = e.arguments[0];
//Now we can run *.exe from windows using:
if(NativeProcess.isSupported)
{
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
nativeProcessStartupInfo.executable = File.applicationDirectory.resolvePath("ExecutableApp.exe");
nativeProcessStartupInfo.arguments.push(a);
var process:NativeProcess = new NativeProcess();
//dispatched when the process will be finished
process.addEventListener(NativeProcessExitEvent.EXIT,onProcessDone);
//run
process.start(nativeProcessStartupInfo);
}
else Alert.show("Native process are not supported\nPrinter settings may be wrong!");
}
It's a long way, but certainly works! At least for me it worked.

Related

Actionscript 3, reading two files then triggering a function, best practice

I need to read a part of two files, and once both parts of both files are loaded to trigger a function that does some work.
What is the best way to approach this problem.
I am currently triggering the second file load once the first is loaded, however it seems poor coding style, I think this because my OO code starts looking procedural.
EDIT: So its an Air based app so using filestream.
In the end I found I actually needed to read each file in a different way. Because I need the same part of both files, and I dont know the file size, I need to read one file first and once I have fileStream.bytesAvailable and position, I can then look for the same data from the second file. I found I must handle files smaller than my read size and the end of files beyond multiples of my read size.
You don't specified what file and from where you wont to load the file but you can actually load multiples files in parallel.
If you want to read only part of file from local machine you can use AIR's FileStream class - very easy and you don't have to load whole few hundreds MB file:
import flash.filesystem.*;
var file:File = File.documentsDirectory;
file = file.resolvePath("Apollo Test/test.txt");
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var str:String = fileStream.readMultiByte(file.size, File.systemCharset);
trace(str);
fileStream.close();
Another option is to use URLStream and listen for ProgressEvent.PROGRESSevents to read data of partially loaded file.
You may also want to see NetStream class which is used to stream video.
there is many options, using File, FileStream is only available on air applications.
The File class extends the FileReference class. The FileReference
class, which is available in Flash® Player as well as Adobe® AIR®,
represents a pointer to a file, but the File class adds properties and
methods that are not exposed in Flash Player (in a SWF running in a
browser), due to security considerations.
as noted above, if you are creating a non-AIR application, FileReference should be used instead of FileStream and File classes, as you dont tagged AIR in your question.
FileReference does not provide any open("path") to you (due to security considerations), but a browse method will be available and ask's your client's for selecting a file. here is an example, which also explain how to trigger a function when opening is done:
var filereference:FileReference = new FileReference();
filereference.addEventListener(Event.SELECT, onFileSelected);
var text_files:FileFilter = new FileFilter("Text Files","*.txt; *.html;*.htm;*.php");
var all_files:FileFilter = new FileFilter("All Files (*.*)","*.*");
filereference.browse([text_files, all_files]);
// triggered when a file is selected by user
function onFileSelected(e:Event):void {
filereference.removeEventListener(Event.SELECT, onFileSelected);
filereference.addEventListener(Event.COMPLETE, onFileLoaded);
filereference.load();
}
// triggered when file loading is complete
function onFileSelected(e:Event):void {
var data:ByteArray = fileReference["data"];
filereference.removeEventListener(Event.COMPLETE, onFileSelected);
}
two more events to be listened for suddenly error's occurred and displaying a progress bar for loading progress (its sync):
IOErrorEvent.IO_ERROR and ProgressEvent.PROGRESS

starling atf textures not displaying

So i'm running air 3.7, the latest starling frameworks, added -swf-version=20 -target-player=11.7 in compiler arguments and running the code
[Embed(source="/assets/wtf4.atf", mimeType="application/octet-stream")]
private static const why:Class;
var data:ByteArray = new why();
var texture:starling.textures.Texture = starling.textures.Texture.fromAtfData(data);
var image:Image = new Image(texture);
addChild(image);
if I'm using the starling atf that came with the framework demo it works fine, but whenever i try to display my own png that I create in photoshop converted into atf it gives me a error saying
ArgumentError: Error #3677: Texture decoding failed. Internal error.
The image I'm trying to convert into atf is just a red square png with 512x512 sizes with the compiler arguments: png2atf -c -i example.png -o example.atf. I'm not sure whether my flash builder isn't setup to decode atfs or if i'm creating the atfs wrong for some reason, if someone could shed some light on this it would be awesome!
When creating the .atf, did you created mipmaps also? If not, you need to set the second argument of the Texture.fromAtfData() function to false - don't use Mipmaps.
From Starlign wiki:
"If you omit mipmaps, you must set the parameter “useMipMaps” of the “Texture.fromAtfData()” method to “false”! Otherwise, you'll get a run-time error."
http://wiki.starling-framework.org/manual/atf_textures
The latest version of ATF requires AIR 3.8 (which is currently in beta). You need to download the AIR installer, and the latest AIR SDK. More details here: http://forum.starling-framework.org/topic/error-3677-texture-decoding-failed-internal-error

Compiling SWF runtime from adobeAir application

I have problem in creating swf file runtime from an adobe air application. For example I create animation using https://github.com/jamesflorentino/Flip-Planes-AS3, I have converted the Sprite extension to MovieClip, the animation runs very good. Now I would like to make the animation could be save as swf file by user.
I have tried as3swf with script like this:
private function createSwf():void{
//let make example the Main class is taken from github above
var _main:Main = new Main();
// in this case i use AS3SWF plugin
var _swf:SWF = new SWF(_main.loaderInfo.bytes);
// this is for copy byteArray from the _swf convertor
var buffer:ByteArray = new ByteArray();
_swf.publish(buffer);
saveToDesktop(buffer);
}
private function saveToDesktop(_ba:ByteArray):void{
// create the file on the desktop
var myFile:File = File.desktopDirectory.resolvePath("demo.swf");
// create a FileStream to write the file
var fs:FileStream = new FileStream();
// add a listener so you know when its finished saving
fs.addEventListener(Event.CLOSE, fileWritten);
// open the file
fs.openAsync(myFile, FileMode.WRITE);
// write the bytearray to it
fs.writeBytes(_ba);
// close the file
fs.close();
}
private function fileWritten(e:Event):void{
trace("new swf file is created");
}
After all those process i got generated swf in my desktop folder with name demo.swf but when i open the file, it is only a white background with error message:
VerifyError: Error #1014: Class flash.events::NativeWindowBoundsEvent could not be found.
at flash.display::MovieClip/nextFrame()
at mx.managers::SystemManager/deferredNextFrame()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\SystemManager.as:278]
at mx.managers::SystemManager/preloader_preloaderDocFrameReadyHandler()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\SystemManager.as:2627]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.preloaders::Preloader/timerHandler()[E:\dev\4.y\frameworks\projects\framework\src\mx\preloaders\Preloader.as:515]
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
please help me what is the best way to create swf file runtime, both from script side or command line side as long as not server side because it is desktop application.
Many Thanks
Creating a SWF at runtime is not going to be the same as taking an in memory byte array representation of an animation and saving it with a SWF extension.
If you want to build a SWF from AIR; you may consider bundling the Flex Framework with your application and use a NativeProcess to trigger mxmlc to generate a SWF. You'll need source code [or SWCs] to do this, though, it won't work with already compiled assets/classes from your running application.
Or you may want to review the file format for a SWF and go about creating it manually from your AIR application. I have no doubt this is possible, but I do not expect it to be trivial.

Access command line in AS3

I've searched on stackoverflow, but didn't find anything, and looked through the as3 documentation with the same result.
I want to do something like C's system(); or PHP's shell_exec(").
Is this possible? How?
Flash is client-side so you cannot call an executable on the server directly.
You could however create a PHP File on the server that would run your executable. Then you can launch this script from Flash using URLLoader:
var urlLoader:URLLoader = new URLLoader();
var urlRequest:URLRequest = new URLRequest('http://example.com/somescript.php');
urlLoader.load(urlRequest);

How to save BitmapData to Bitmap *.bmp file, or much faster JPE Encoding method

I have a Flash / Actionscript 3 based desktop app wrapped in an *.exe using Zinc 4.0. I am using Flash Pro CS5.
I need to start saving very large image files locally. I have messed around with JPG Encoding these images before saving them to a local file via Zinc. I solved the actionscirpt timeout issue using This "asyncronous like" method. Encoding a 1.5 MP image takes about 5 seconds which is alright, but encoding an 8 MP image file takes about 40 seconds, which is not acceptable.
One idea I had is to save the BitmapData locally to a temporary Bitmap file (*.bmp), without having the end user to wait for JPG Encoding in Flash, and then use my already existing image processor (written in C#) to read the bitmap file and encode it without waiting on Flash to do it, effectively offloading the task away from the user.
I have used BitmapData.getPixels() to try and write the byte array directly to the file, using the same Zinc method as I do successfully with encoded JPGs, but the *.bmp file is unreadable. Are there some file headers that would need to be included in addition to the BitmapData getPixel()'s byte array to successfully save a bitmap image? If so how could I successfully add them to the byte array before writing to file?
Any guidance, clarification or other solutions much appreciated.
I've found a solution for my needs, and just in case others have similar needs:
To save an actual Bitmap (*.bmp) file, Engineer's suggested Btimap encoder class was awesome. Very fast on the actual encoding; however, since my file writing call in Zinc is synchronous and bitmap files are a lot larger than JPGs it really just moved my bottle neck from encoding to the file saving, so I decided to look elsewhere. If Zinc had an asynchronous binary file writing method that would not lock up the GUI I would have been happy, but until then this is not the solution for me.
I stumbled across a Flash Alchemy solution, with great results. Instead of waitint abour 40 seconds to encode an 8 MP image, it now only takes a few seconds. This is what I did:
Downloaded the jpegencoder.swc from this page and saved it in my project directory
Added the swc: Publish Settings > Flash (tab) > Script: Actionscript 3.0 "Settings..." button > Library path (tab)> and added that .swc with Link Type = "Merged into code"
Then used it :
(below is my modified code with just the basics)
import flash.utils.ByteArray;
import flash.display.BitmapData;
import cmodule.aircall.CLibInit; //Important: This namespace changed from previous versions
var byteArrayResults:ByteArray; //Holds the encoded byte array results
public static function startEncoding(bitmapData:BitmapData):void {
var jpeginit:CLibInit = new CLibInit(); // get library
var jpeglib:Object = jpeginit.init(); // initialize library exported class to an object
var imageBA:ByteArray = bitmapData.getPixels(bitmapData.rect); //Getpixels of bitmapData
byteArrayResults = new ByteArray();
imageBA.position = 0;
jpeglib.encodeAsync(encodeComplete, imageBA, byteArrayResults, bitmapData.width, bitmapData.height, 80);
}
private static function encodeComplete(thing:*):void
{
// Do stuff with byteArrayResults
}
You may find this link useful as well:
http://last.instinct.se/graphics-and-effects/using-the-fast-asynchronous-alchemy-jpeg-encoder-in-flash/640
my answer is late but maby it helps.
i developed a AIR mobile app to save imgs from the device camera on the device and upload it to the server.
since air 3.3 you have this bitmapdata encode functionality:
var ba:ByteArray = new ByteArray();
var bd:BitmapData = new BitmapData(_lastCameraPhotoTmpBmp.width, _lastCameraPhotoTmpBmp.height);
bd.draw(_lastCameraPhotoTmpBmp);
bd.encode(new Rectangle(0, 0, 1024, 768), new JPEGEncoderOptions(80), ba);
var localFile:File = File.applicationStorageDirectory.resolvePath("bild.jpg");
var fileAccess:FileStream = new FileStream();
fileAccess.open(localFile, FileMode.WRITE);
fileAccess.writeBytes(ba, 0, ba.length);
fileAccess.close();
the encode to jpg takes ~100ms on mobile devices in my tests.
greetings stefan