Dart Keyboard Event Command Line - dart

I've been monkeying around with Dart (& Flutter more specifically on mobile) and have become quite interested in trying Flutter on Desktop.
Anyways, for this one app idea, I need the ability to create a key event. From my research, I found this: https://api.dartlang.org/stable/2.2.0/dart-html/KeyEvent-class.html which mentions a KeyEvent however this primarily relates to Dart:HTML (which I presume just means browser only).
Does Dart run in the command line support any ability for generating key events? Like say I wanted an app to type something for a user.
Thanks!

#Isaac has basically explained it in his comment but this is how it looks like in code:
import 'dart:io';
void main(){
stdin.echoMode = false;
stdin.lineMode = false;
while(true){
if(stdin.readByteSync() == 102){ // f
print('You payed respect');
}
else{break;}
}
}

Related

Dart How to load file in runtime

I'm writing a discord bot using the nyxx library and want use dynamic file import for load command info and handler. But, after 5 hours of searching with Google, I didn't find anything to help me do that.
In Node.js, I can use require() or import() for it: Does the dart have something like that?
A small code snippet, showing what I want do:
this.commands = new Collection();
fs.readdirSync('./src/commands').filter(( f ) => f.endsWith( '.js' )).forEach((file) => {
const command = require(`../commands/${file}`);
this.commands.set( command.info.name, command );
});
Is it possible to do this or not? (I don't like to write many imports for commands and register it in lib.)
You can in theory use Isolate.spawnUri to spawn external Dart programs to run in its own Isolate instances that can then communicate back to the main program using SendPort.
It does, however, come with some limitations. E.g. it is very limited what types of objects you can send though SendPort when using spawnUri since the two programs does not share any type information (compared to Isolate.spawn which does allow you to send your own custom types). The documented types you can send can be found here:
Null
bool
int
double
String
List or Map (whose elements are any of these)
TransferableTypedData
SendPort
Capability
https://api.dart.dev/stable/2.17.6/dart-isolate/SendPort/send.html
But it does allow us to make some kind of protocol and you can create some helper class around this to handle the conversion of a known object structure into e.g. Map<String, Object>.
A small example that works with Dart VM would be:
Your command implemented as: command.dart
import 'dart:isolate';
void main(List<String> arguments, Map<String, Object> message) {
final userName = message['username'] as String;
final sendPort = message['port'] as SendPort;
sendPort.send('Hi $userName. '
'You got a message from my external command program!');
}
Your server that calls your command: server.dart
import 'dart:isolate';
void main() {
final recievePort = ReceivePort();
recievePort.listen((message) {
print('Got the following message: $message');
recievePort.close();
});
Isolate.spawnUri(Uri.file('command.dart'), [], {
'username': 'julemand101',
'port': recievePort.sendPort,
});
}
If running this with: dart server.dart you, hopefully, get:
Got the following message: Hi julemand101. You got a message from my external command program!
If you want to compile your application, you can do so by doing the following. You need to compile the command.dart, since a compiled Dart program does not understand how to read Dart code.
dart compile exe server.dart
dart compile aot-snapshot command.dart
You should here change Uri.file('command.dart') to Uri.file('command.aot') since the file-extension for aot-snapshot are .aot.
If everything works, you should be able to see:
> .\server.exe
Got the following message: Hi julemand101. You got a message from my external command program!

In Dart, how do I add a ">>" before the input created by stdin.readLineSync()?

I'm writing a Dart console app for the first time and I've searched the Internet everywhere and can't find the proper answer.
In Python, the function raw_input(); takes user input from stdin in a similar way to Dart's stdin.readLineSync();, however raw_input(); takes a parameter: If I do something like raw_input(">>");, the CLI does something like:
>> _
In Dart, however, I cannot find a way to do something similar with stdin.readLineSync();, it simply outputs:
_
Is there a simple way for a new Dart user to accomplish this? Thank you for your time.
This might do what you want:
import 'dart:io';
main() {
stdout.write('>> ');
var result = stdin.readLineSync();
print(result);
}
write does not automatically add a newline.
A simpler way is to use the DCli package and its ask function:
var response = ask('>>');
print(response);
The ask function provides a number of other options that help capturing data from the cli such as the functions 'confirm' and 'menu'.
https://onepub.dev/packages/dcli

Testing Flutter code that uses a plugin and platform channel

I have a flutter plugin which uses the platform channel to do some native work.
How do I properly write tests for my application that requires this plugin?
Unit tests only are good for pure dart functions. I don't believe Widget testing will be able to test things that use the platform channel to native. So that leaves integration testing.
From what I understand is that integration testing will start your main application and you can control it around your app and test things.
For my case, I want to test just the code that uses the plugin (that uses the platform channel for native stuff).
Also what is important is the values that come back from the platform channel, so it is important to call the native side using a real platform channel and not a mock one.
Is that possible? Can I tell the integration tester to open a dummy version of my application, kind of like an integrated widget tester?
It seems the short answer to your question is no. Flutter driver (integration testing) can only interact with the UI, AFAIK. It cannot intercept calls to plugins. It is used to test the entire app from the UI.
However it is possible to intercept calls to plugins in unit and widget tests. This allows monitoring the calls to the plugin and mocking the response. That way you can test your plugin's dart code and/or a widget that uses the plugin. Testing native code would involve writing native tests.
The following is an example of intercepting calls to a plugin for testing:
MethodChannel('audio_recorder')
.setMockMethodCallHandler((MethodCall methodCall) async {
log.add(methodCall);
switch (methodCall.method) {
case 'start':
isRecording = true;
return null;
case 'stop':
isRecording = false;
return {
'duration': duration,
'path': path,
'audioOutputFormat': extension,
};
case 'isRecording':
return isRecording;
case 'hasPermissions':
return true;
default:
return null;
}
});
For a complete example see here
Flutter team do mentions that they want to do more things in widgets test instead of driver(integration) test.
We're moving away from flutter_driver in favour of extending flutter_test to work on devices.
From Flutter 2.8 breaking changes doc, you should use binding in tester instead of setMockMethodCallHandler from channel.
// old code
myMethodChannel.setMockMethodCallHandler(...);
myMethodChannel.checkMockMethodCallHandler(...);
// new code
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(myMethodChannel, ...);
tester.binding.defaultBinaryMessenger.checkMockMessageHandler(myMethodChannel, ...);
Take ImagePicker as example:
widgetTest('', (tester) async {
const channel = MethodChannel('plugins.flutter.io/image_picker');
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
channel,
(MethodCall methodCall) => Future.value('some-image'),
);
});
One additional thing to #呂學洲 answer.. is if you're writing a unit test and don't have reference to widget tester instance you can access the binder like below
TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger
Also make sure to wait for binder to initialize in the begging of the test like below
TestWidgetsFlutterBinding.ensureInitialized();
And to grab method call you can do:
final binaryBinding = TestDefaultBinaryMessengerBinding.instance;
pluginChannel = MethodChannel('channelName');
binaryBinding!.defaultBinaryMessenger.setMockMethodCallHandler(pluginChannel,
(MethodCall methodCall) async {
switch (methodCall.method) {
case 'call 1':
return mockValue;
default:
return null;
}
},
);
Hope that helps.

Xamarin Forms - iOS not processing correctly

I am using the CrossDownManager plugin for Xamarin Forms
Here
When I run the method on Android it processes as expected. On iOS Debug.Writeline("Success!") isn't being hit like it was on Android.
Here is the code:
void ViewImage(string imageLink)
{
var downloadManager = CrossDownloadManager.Current;
downloadManager.PathNameForDownloadedFile = new System.Func<IDownloadFile, string>(file =>
{
string path = DependencyService.Get<IImageSaver>().Save("YHTS" + DateTime.Today.Ticks.ToString() + ".jpg");
Debug.WriteLine("Success!");
return path;
});
try
{
var file = downloadManager.CreateDownloadFile(imageLink);
Debug.WriteLine("file created");
downloadManager.Start(file);
Debug.WriteLine("downloadstarted");
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
}
For the life of me I can't figure out why the that code block isn't processed. Any ideas?
This is an interesting issue as technically your code should work as expected. I've done a little digging and found a reply to a similar question here.
your options are many... including:
DEBUG preprocessor as you show in your question.
Use System.Diagnostic.Debug.WriteLine: Any calls to Debug.* will be
removed by the compiler due to the [Conditional("DEBUG")] attribute
being applied.
Create your own "Logger" class as a wrapper to the stdout writers and
[Conditional("DEBUG")] it
Use Fody and re-weave the assemblies to remove/NOP/redirect the
WriteLine I do this to redirect the calls to in internal log and upon
crash or user stat requests, forward this log to our crash reporting
servers. etc, .....
So there are a few alternatives to consider, one of the common suggestions I've seen is to use the fully qualified reference for WriteLine(); as such:
System.Console.WriteLine("woop woop");
I would suggest giving the above a try first.

QTP 11 Extensibility developing (.NET sdk) - calling Record() on the recorder object fails

As far as I looked, there's no answered question about QTP's Ext. sdk on stackoverflow (and almost anywhere else on the net; there isn't even a appropriated tag for it...), so I'm aware it's unlikely I get my problem solved by asking , but whatever, it worth trying.
Anyway, before I lose the attention of anyone who never heard or used the Ext. sdk, maybe I will have more luck asking you to help me figure out how to locate the error log file QTP produces at run-time. I know such a file exists in the new UFT 11.5 version, but I couldn't locate it in QTP 10 or 11 (For the record, I don't talk about QTP's Log Tracking feature, but about the "meta" error log of errors/exceptions produced by QTP itself).
Now for the question:
I'm developing an extension for QTP to support native record and run tests on my application.
I'm currently able to import an object repository, and write test steps using The COM object testing agent I developed.
Problem started when I was trying to implement the IRecordable interface; I'm getting the IRecorder object from qtp, and even able to use it as ISuppressor object to exclude redundant steps from being recorded, but all my attempts to record a step (that is, to add new recorded objects to the repository, and add steps to the test) simply failed.
This is the code that I'm using:
public class MyTestingAgent :
AutInterface.ITestable,
AutInterface.IRecordable
{
QTPInterface.IRecorder recorder;
...
public void AutInterface.IRecordable.BeginRecording(object recorder)
{
IRecordSuppressor recordSuppressor = recorder as IRecordSuppressor;
recordSuppressor.Suppress(MyTestingAgentId,
"<Suppress><Item type=\"HWND\" value=\"[#HWND]\" /></Suppress>".Replace("[#HWND]", getMyAppHWND().ToString()));
this.recorder = recorder as QTPInterface.IRecorder;
...
}
public void recordNewObjStep(string parentName, string objName, string method, Object[] arguments)
{
object[] objectHyrarchy = new object[] { findObjectId(objName), findObjectId(parentName) };
string externalParent = null;
string appDescriptionXml = getDescriptionXml(parentName, objName);
try
{
recorder.Record(MyTestingAgentId, objectHyrarchy , appDescriptionXml, externalParent, method, arguments);
Trace.TraceInformation("Record successfully done.");
}
catch (Exception e)
{
Trace.TraceError("TEAAgent.recordSTElement: " + e.ToString());
}
}
...
}
I'm pretty sure all the arguments I send with the call to Record() are accurate. getDescriptionXml() and findObjectId() are used in different cases in the code, and works fine, the method name and argument are correct.
The annoying thing is that the call to Record doesn't even throw exception, and I get "Record successfully done." in the trace log. Needless to say no new object is created in the repository, and no step is added to the test.
As I can't debug QTP, I'm pretty much in the dark with what I'm doing wrong. That's why I'm asking for help with finding QTP's log file, or any other approach that might shed some light on the subject.
For QTP 11 you can turn on the logs by going to QTP's bin directory and running ClientLogs.exe.
Specifically for TEA extensibility do the following.
select the QTP node from the list on the left
find the LogCatPackTEA from the Available Categories list
Click the > button to move it to Selected Categories
Change TEAs level to Debug2 by selecting the category and changing the level
Click OK and run QTP
The logs will show up as QTP.log in the diretory specified in Path:
I'm curious on what the problem you're facing is, please update if you find the cause.

Resources