What is the state of the dart debugger? - dart

I am having hard times debugging my code with the Dart Editor version 0.5.0_r21823 on Mac OS X.
It stops with following info:
"Dart_InstanceGetClass expects argument 'instance' to be of type Instance."
I am now trying the poor man's debugger (i.e. print ...) but even that one fails.
_setupGui() {
// Bitmap background = new Bitmap(resourceManager.getBitmapData("Pigeon"));
print("Done loading resources");
ChessBoard b = new ChessBoard();
board = new ChessBoardView(b);
stage.addChild(board);
....
/**
* Holds a chess position.
*/
class ChessBoard {
static const String STARTPOS = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
ChessBoard([String fen = STARTPOS]) {
print("ChessBoard($fen)"); // This gets written
_setFromFen(fen);
}
void _setFromFen(String fen) {
print("_setFromFEN($fen)"); // This is not written
...
Console output:
Fixed Canvas Style Size !!!!
Loading resources
Done loading resources
ChessBoard(rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1)
... here it ends. I.e. setFromFEN() is not written ...

This is likely a bug, which has likely been fixed by now. If you're using Dartium; you can use the built-in dev tools to debug (much like you would with JavaScript) which can be very convenient!

Related

Lazy rendering print pages on iOS

I need to print custom UI in a cross-platform application. On Windows, the work flow is like:
Choose what to print
Open the Windows Print dialog/print preview. This only queries for print pages as they are needed.
Begin printing and report progress as each page prints.
I am trying to replicate this workflow on iOS, but it seems that all the print pages need to be print-ready before opening the iOS print dialog (UIPrintInteractionController). This is a big problem because the user may be printing a lot of pages, and each page can take awhile to prepare for printing. Therefore it takes too long to prepare and open the UIPrintInteractionController.
Is there any way on iOS to have it lazily query for the print pages one (or even a few) at a time as they are being previewed or printed? Or do they all have to be prepared ahead of presenting the UIPrintInteractionController?
EDIT: It's a major problem when printing many pages because it can easily run out of memory holding that many UIImages in memory at the same time.
I tried using the PrintItems property with UIImages, as well as a UIPrintPageRenderer. I am using Xamarin.iOS so pardon the C# syntax, but you get the idea. An answer in Swift or Objective C would be fine. Here is my sample pseudo-code:
//Version 1
public void ShowPrintUI_UsingPrintingItems()
{
UIPrintInfo printOptions = UIPrintInfo.PrintInfo;
InitializePrintOptions(printOptions);
_printer.PrintInfo = printOptions;
var printRect = new CGRect(new CGPoint(), _printer.PrintPaper.PaperSize);
//Each of these is horribly slow.
//Can I have it render only when the page is actually needed (being previewed or printed) ?
for (uint i = 0; i < numPrintPages; i++)
{
_printPages[i] = RenderPrintPage(i, printRect);
}
_printer.PrintingItems = _printPages;
_printer.Present(true, (handler, completed, error) =>
{
//Clean up, etc.
});
}
//Version 2
public void ShowPrintUI_UsingPageRenderer()
{
UIPrintInfo printOptions = UIPrintInfo.PrintInfo;
InitializePrintOptions(printOptions);
_printer.PrintInfo = printOptions;
//This still draws every page in the range and is just as slow
_printer.PrintPageRenderer = new MyRenderer();
_printer.Present(true, (handler, completed, error) =>
{
//Clean up, etc.
});
}
private class MyRenderer : UIPrintPageRenderer
{
public MyRenderer(IIosPrintCallback callback)
{
_callback = callback;
}
public override void DrawPage(nint index, CGRect pageRect)
{
DrawPrintPage(i, printRect);
}
public override nint NumberOfPages => _numPrintPages;
}

RxJava Observable to smooth out bursts of events

I'm writing a streaming Twitter client that simply throws the stream up onto a tv. I'm observing the stream with RxJava.
When the stream comes in a burst, I want to buffer it and slow it down so that each tweet is displayed for at least 6 seconds. Then during the quiet times, any buffer that's been built up will gradually empty itself out by pulling the head of the queue, one tweet every 6 seconds. If a new tweet comes in and faces an empty queue (but >6s after the last was displayed), I want it to be displayed immediately.
I imagine the stream looking like that described here:
Raw: --oooo--------------ooooo-----oo----------------ooo|
Buffered: --o--o--o--o--------o--o--o--o--o--o--o---------o--o--o|
And I understand that the question posed there has a solution. But I just can't wrap my head around its answer. Here is my solution:
myObservable
.concatMap(new Func1<Long, Observable<Long>>() {
#Override
public Observable<Long> call(Long l) {
return Observable.concat(
Observable.just(l),
Observable.<Long>empty().delay(6, TimeUnit.SECONDS)
);
}
})
.subscribe(...);
So, my question is: Is this too naïve of an approach? Where is the buffering/backpressure happening? Is there a better solution?
Looks like you want to delay a message if it came too soon relative to the previous message. You have to track the last target emission time and schedule a new emission after it:
public class SpanOutV2 {
public static void main(String[] args) {
Observable<Integer> source = Observable.just(0, 5, 13)
.concatMapEager(v -> Observable.just(v).delay(v, TimeUnit.SECONDS));
long minSpan = 6;
TimeUnit unit = TimeUnit.SECONDS;
Scheduler scheduler = Schedulers.computation();
long minSpanMillis = TimeUnit.MILLISECONDS.convert(minSpan, unit);
Observable.defer(() -> {
AtomicLong lastEmission = new AtomicLong();
return source
.concatMapEager(v -> {
long now = scheduler.now();
long emission = lastEmission.get();
if (emission + minSpanMillis > now) {
lastEmission.set(emission + minSpanMillis);
return Observable.just(v).delay(emission + minSpanMillis - now, TimeUnit.MILLISECONDS);
}
lastEmission.set(now);
return Observable.just(v);
});
})
.timeInterval()
.toBlocking()
.subscribe(System.out::println);
}
}
Here, the source is delayed by the number of seconds relative to the start of the problem. 0 should arrive immediately, 5 should arrive # T = 6 seconds and 13 should arrive # T = 13. concatMapEager makes sure the order and timing is kept. Since only standard operators are in use, backpressure and unsubscription composes naturally.

zxing windows phone 8 Memory issue

I am developing a barcode scanner.
My application scans a Barcode, than navigates to a second page (with barcodetext on it) and theres a button where i can scan a new barcode when its clicked. So now my problem is that the viewfinderbrush fills the Ram of the windows phone everytime I scan a barcode. If I scan 100 Barcodes, my applikation chrashes because of an out of memory. What can I do to free the memory?
In the zxing demo its the same issue, when I open the scanner and use the back key and open the scanner several times again, the ram is getting higher and higher.
My code for getting the ram:
string storage1 = (DeviceStatus.ApplicationCurrentMemoryUsage / 1000000).ToString() + "MB";
lblram.Text = storage1 ;
I tried everything:
1. Navigationservice.removebackstack
2. Gc.collect (Garbagecollector)
3. disposing the camera
4. use of navigationservice.goback()
Nothing helps
I found out, that the problem is the viewfinderbrush, but i have to inizialize it every time, so thats a problem.
Code:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string bla1 = (DeviceStatus.ApplicationCurrentMemoryUsage / 1000000).ToString() + "MB";
lblram.Text = bla1;//("Ram: " + Math.Round(((bla1 / 1024)/ 1024), 2));
_matches = new ObservableCollection<string>();
matchesList.ItemsSource = _matches;
// Check to see if the camera is available on the phone.
if (PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true)
{
_photoCamera = new PhotoCamera(CameraType.Primary);
// Event is fired when the PhotoCamera object has been initialized.
_photoCamera.Initialized += PhotoCameraOnInitialized;
_photoCamera.AutoFocusCompleted += PhotoCameraOnAutoFocusCompleted;
NavigationService.RemoveBackEntry();
viewfinderBrush.SetSource(_photoCamera);
}
else
{
// The camera is not supported on the phone.
MessageBox.Show("A Camera is not available on this phone.");
}
}
What can I do to solve this problem?

PrintCanvas3D won't work

I have some trouble tring to print graphics from Java3d some computer (Intel based Graphic cards) crash completly when printing. I got this exception.
javax.media.j3d.IllegalRenderingStateException: GL_VERSION
at javax.media.j3d.NativePipeline.createNewContext(Native Method)
at javax.media.j3d.NativePipeline.createNewContext(NativePipeline.java:2736)
at javax.media.j3d.Canvas3D.createNewContext(Canvas3D.java:4895)
at javax.media.j3d.Canvas3D.createNewContext(Canvas3D.java:2421)
at javax.media.j3d.Renderer.doWork(Renderer.java:895)
at javax.media.j3d.J3dThread.run(J3dThread.java:256)
DefaultRenderingErrorListener.errorOccurred:
CONTEXT_CREATION_ERROR: Renderer: Error creating Canvas3D graphics context
graphicsDevice = Win32GraphicsDevice[screen=0]
canvas = visualization.show3D.show.print.OffScreenCanvas3D[canvas0,0,0,3000x2167,invalid]
Java 3D ERROR : OpenGL 1.2 or better is required (GL_VERSION=1.1)
Java Result: 1
I know it said i have to upgrade to OpenGL 1.2 but after checking i already have 1.5 installed (error message is not accurate)
String glVersion = (String)getCanvas3D().queryProperties().get("native.version");
I tried to catch IllegalRenderingStateException but it doesn't work, JVM just crash in any case.
Doesnt anyone know how to have a printing function to work on Intel based Graphic cards ?
I found out the cause of my problem.
Some computer haven't OffScreenRendering support needed by PrintCanvas3D.java.
So i used robot to create a screen capture
public BufferedImage canvasCapture(Dimension size, Point locationOnScreen) {
Rectangle bounds = new Rectangle(locationOnScreen.x, locationOnScreen.y, size.width, size.height);
try{
Robot robot = new Robot(this.getGraphicsConfiguration().getDevice());
return robot.createScreenCapture(bounds);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
Last tricky part was to detect when to switch from proper printing method to ScreenCapture method (since catching the raised exception doesn't work), after some search i found out that queryProperties() could give me this information
here is the code in my Frame3D to choose proper method
Boolean OffScreenRenderingSupport = (Boolean)getCanvas3D().queryProperties().get("textureLodOffsetAvailable");
if (OffScreenRenderingSupport){
bImage = getOffScreenCanvas3D().doRender(dim.width, dim.height);
}else{
bImage = getOffScreenCanvas3D().canvasCapture(getCanvas3D().getSize(), getCanvas3D().getLocationOnScreen());
}
If anyone can find a better way to handle this, please let me know ;)

Flash CS5 to iOS - Using Filesystem causeing app not to run on iPhone

So I'm in the final stages of designing a game for the iPhone using Flash CS5 and I'm running into a problem with it running on the iPhone. I am a registered Developer, so I'm doing this completely legit... I'm just doing it on a PC and with Flash so there are a few workarounds being done lol. I'm at a point where it runs perfectly in the simulator but not on the iPhone itself. I load up the game and the opening screen loads up where I have my PLAY button located. The problem is, it doesn't work. It doesn't click, change screens... nada. So I worked it out to be something I'm doing wrong with the way I'm using the Filesystem and my save game file. If I take out the filestream stuff and just put in hard values into all my save game variables, the game runs just fine. The PLAY button does its thing and the game is good to go, except of course that I'm stuck to just the hard set values instead of being able to do little things like change levels. So here is the code I'm using, and hopefully someone can see where I've gone wrong.
The app starts off with running a main.as which calls the saved game file...
private function addedMain(event:Event):void {
//Set up opening screen
gameStart = new GameStart(this);
addChild(gameStart);
//set up the save game info
_savedGame = new SaveGameFile();
_savedGame.initGame();
}
gameStart runs a simple script that just has the title screen with a PLAY button. Clicking the PLAY button removes it and loads up the next screen. This is what isn't working right now. The system may be just freezing or something, at this point I don't have a way to tell exactly what's happening except that the PLAY button does nothing. So the next thing called is the saved game file itself:
package {
import flash.events.Event;
import flash.display.MovieClip;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.filesystem.File;
import flash.errors.IOError;
public class SaveGameFile extends MovieClip {
private var file:File;
private var savedGame:XML;
public function SaveGameFile() {
}
public function initGame():void {
file = File.applicationStorageDirectory;
file = file.resolvePath("savedGame.xml");
xmlLoad();
initVariables();
}
private function xmlLoad():void {
var fileStream:FileStream = new FileStream();
try {
fileStream.open(file, FileMode.READ);
} catch(e:IOError) {
createSaveFile();
xmlSave();
}
var str:String = fileStream.readMultiByte(file.size, File.systemCharset);
savedGame = XML(str);
fileStream.close();
}
public function saveTheGame():void {
xmlSave();
}
private function xmlSave():void {
var writeStream:FileStream = new FileStream();
writeStream.open(file, FileMode.WRITE);
var s:String = String(savedGame);
writeStream.writeMultiByte(s, File.systemCharset);
writeStream.close();
}
private function createSaveFile():void {
savedGame =
<savedGame>
<levelsCompleted>0</levelsCompleted>
<levelWorkingOn>0</levelWorkingOn>
<volLevel>0.05</volLevel>
<sfxLevel>0.75</sfxLevel>
<level>
<levelNum>1</levelNum>
<highScore>0</highScore> //...etc.
</level>
//you get the idea
</savedGame>
}
So as you can see, I'm creating a XML file called savedGame (created the first time the game runs and then is just loaded when the game runs) and from that I'm pulling all my level information as needed and saving scores and such. Again this is working just fine in the simulator (of course) but if I leave this code in, I don't get past the starting page. So does anything jump out to anyone as to why this isn't working? Help! Thanks ;)
Adobe a while ago published a few articles on programming AIR apps for iOs devices, maybe this one will help you out (in the unlikely case you didn't see it already):
Saving state in AIR applications for iOS devices
UPDATE: So I may have been on the wrong track all along because through messing around with my file on my computer I was finally able to see the error occur where I could easily trace problems compared to tracing on the iPhone. I don't know if my original code was flawed or not, however, I do know that this code below works perfectly, so I'm keeping it (and I like it better anyway). HOWEVER, my main problem seems to have been the fact that I'm using XML as my save file. This is perfectly fine to do, BUT for some reason, saving the file causes a couple of strange characters to be entered at the very beginning of the file. So instead of starting
<savedGame>
it was starting with something like
|Y<savedGame>
The | was actually a symbol I couldn't find that had a line in the middle and a charCode of 25 and the Y was actually a Yen sign. So whatever that was, it was causing me to get a 1088 Error. I solved this by striping any and all characters (whatever they end up being just in case it's different for everyone... not sure if it is but not taking any chances). So in my code below I added a section between //EDIT START and //EDIT STOP that is only needed if you too are using XML in your script. Otherwise you can leave this out. Hope this helps :)
ORIGINAL POST: OK so it seems that through some messing around with the code listed at the bottom of the page linked by danii, I was able to get that sites code working after all. I'm tempted to look back at my original code and mess with it to see if I can get it to work with what I've learned from this, but the game is working so I'm moving on and never looking back... lol. What I did find out though is that for my needs, that pages code was not quite workable (and why I gave up on it originally). It might have worked for their needs, but unless you package the game with a file, as far as I can tell their function "getSaveStream" will always return 'null' because the file will never be able to be written. So I removed a lot of their if's and try's because they were causing the game to fail. Here is what I ended up with in the context of my original post:
package {
import flash.events.Event;
import flash.display.MovieClip;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.filesystem.File;
import flash.errors.IOError;
public class SaveGameFile extends MovieClip {
private var f:File;
private var savedGame:XML;
public function SaveGameFile() {
}
public function initGame():void {
xmlLoad();
initVariables();
}
private function getSaveStream(write:Boolean, sync:Boolean = true):FileStream {
// The data file lives in the app storage directory, per iPhone guidelines.
f = File.applicationStorageDirectory.resolvePath("savedGame.xml");
// Try creating and opening the stream.
var fs:FileStream = new FileStream();
try {
//write is True and writing asynchronously.
if(write && !sync) {
fs.openAsync(f, FileMode.WRITE);
} else {
//For synchronous write, or all reads, open synchronously.
fs.open(f, write ? FileMode.WRITE : FileMode.READ);
}
} catch(e:Error) {
// On error return null.
return null;
}
return fs;
}
private function xmlLoad():void {
var fs:FileStream = getSaveStream(false);
if(fs) {
var str:String = fs.readMultiByte(f.size, File.systemCharset);
//EDIT START
//check for "bad characters" at the start of the XML file
var badCharCheck = str.charCodeAt(0);
//the first char MUST be '<' which has a CharCode of 60
while(badCharCheck != 60) {
//if the first character isn't '<' then remove it
str = str.replace(String.fromCharCode(badCharCheck), "") ;
//recheck the first character
badCharCheck = str.charCodeAt(0);
}
//EDIT END
savedGame = XML(str);
fs.close();
} else {
//fs returned null so create the XML file savedGame and save it
createSaveFile();
xmlSave();
}
}
public function saveTheGame():void {
//this is used to call the save function externally
xmlSave();
}
private function xmlSave():void {
//the file exists because it was created with FileMode.WRITE in getSaveStream
var fs:FileStream = getSaveStream(true, false);
var s:String = String(savedGame);
fs.writeUTF(s);
fs.close();
}
private function createSaveFile():void {
//this is only called the very first time the game is run on the iPhone
savedGame =
<savedGame>
<levelsCompleted>0</levelsCompleted>
<levelWorkingOn>0</levelWorkingOn>
<volLevel>0.05</volLevel>
<sfxLevel>0.75</sfxLevel>
<level>
<levelNum>1</levelNum>
<highScore>0</highScore> //...etc.
</level>
//you get the idea
</savedGame>
}
So I'm happy to say it tested perfectly and is now running and saving information like it is supposed to. Hope this is of use to someone who runs into the same issue I did. Happy coding!

Resources