Desiring bool any_key_pressed()
Here is a very simple version of the program I'm working on. Is there a way to write is_any_key_pressed() that doesn't block, doesn't require the Enter key, and doesn't require dragging in any complex libraries or dealing with low-level stuff like ioctl()? Is there nothing in Phobos that provides the needed functionality? I won't go into the details, but I tried threading, putting the getchar() in a separate thread that sets a global bool g_keypressed variable. It was a disaster. Maybe there's a right way to use threading? I am not talented at threads. ``` import core.thread; import core.time; import std.stdio; import std.conv; void light_on() { write("on "); stdout.flush; } void light_off() { write("off "); stdout.flush; } void wait() { Duration dur = dur!("seconds")( to!int(1) ); Thread.sleep(dur); } bool is_any_key_pressed() { getchar(); // nope, requires Enter key to be pressed, and is blocking return true; } void main(string[] args) { while (true) { light_on(); wait(); light_off(); wait(); if (is_any_key_pressed()) { break; } } } ```
Re: stdin.readln line editing and recall with up arrow
On Saturday, 25 February 2023 at 08:47:42 UTC, Richard (Rikki) Andrew Cattermole wrote: On 25/02/2023 9:45 PM, Daren Scot Wilson wrote: I went with readline. Left/right arrows work, but up arrow still does not recall earlier commands. Maybe I need also a separate input history thing? https://tiswww.case.edu/php/chet/readline/readline.html#Basic-Behavior Hmm... the add_history(), or maybe it's rl_add_history(), function seems to have been in ancient readline versions but at some point all line history code was taken out to be its own library. https://tiswww.case.edu/php/chet/readline/rltop.html https://tiswww.case.edu/php/chet/readline/history.html Arch Linux drags in both readline.so and history.so in its readline package. No one notices! Trying import gnu.history; fails since there's no distinct 'history' package (yet) and Dub doesn't drag it in along with readline. D can call C and link to anything in /usr/lib easily. Done. It works! How does D know to link to the libhistory.so library? I didn't say "history" anywhere. But it works. extern (C) { void add_history(const char*); } I'm tempted to make a history package and submit it to DUB. Maybe. After dinner...
Re: stdin.readln line editing and recall with up arrow
On Saturday, 25 February 2023 at 05:41:48 UTC, Richard (Rikki) Andrew Cattermole wrote: On 25/02/2023 6:36 PM, Daren Scot Wilson wrote: stdin.readln() works fine until I, out of habit, use the up arrow to recall an earlier input and the left/right to move around and change a character. How do I get that to work? Not with that module. You can either use GNU readline itself, or Adam's version within arsd. I went with readline. Left/right arrows work, but up arrow still does not recall earlier commands. Maybe I need also a separate input history thing?
stdin.readln line editing and recall with up arrow
stdin.readln() works fine until I, out of habit, use the up arrow to recall an earlier input and the left/right to move around and change a character. How do I get that to work?
Re: Which TOML package, or SDLang?
On Monday, 30 January 2023 at 17:54:15 UTC, H. S. Teoh wrote: XML is evil. Agreed! I'm going with TOML, community package. It's working, so far.
Which TOML package, or SDLang?
So, which package do I use for TOML? I find these three: * toml-foolery (Andrej Petrović) * toml-d, or toml.d (oglu on github) at ver 0.3.0 * toml, (dlang community on github) at ver 2.0.1 I'm guessing from version numbers that the third one, toml, is officially good for real world use. But I wonder if there are good reasons to use the others. Also, a low-effort search for TOML in the D world turned up SDLang, where the substring "DLang" has nothing to do with dlang, the common short name for D Language. SDLang looks nice. Should I ditch TOML for it? I just realized - it's been ages since I've dealt with config files, beyond editing them as an end user. I work on existing software where someone else made the choiced and wrote the code, or it's a small specialized project not needing config. I'm a config caveman! This is for a small fun personal project with potential show-off value, available on github but too primitive for now to mention. Controlling hardware, needing to store device info to recall for later runs. There are zero compatibility or standards issues to consider. Whatever is simplest to implement and tinker with is the winner.
Re: Handling CheckBox state changes in DLangUI
On Saturday, 31 December 2022 at 03:05:45 UTC, brianush1 wrote: On Saturday, 31 December 2022 at 02:40:49 UTC, Daren Scot Wilson wrote: The compiler errors I get are, for no '&' and with '&': Error: function `app.checkbox_b_clicked(Widget source, bool checked)` is not callable using argument types `()` Error: none of the overloads of `opAssign` are callable using argument types `(bool function(Widget source, bool checked))` Try: import std.functional : toDelegate; check_c.checkChange = toDelegate(&checkbox_b_clicked); That works :)
Handling CheckBox state changes in DLangUI
I'm writing a GUI program using dlangui. It has some checkboxes. I'm trying to figure out how to invoke a callback function when the user clicks the box. What are the valid ways of doing that? I can copy from dlangide's source, where a delegate is defined in-line and assigned. That seems to work. But is that the only way? bool g_x = true; bool checkbox_b_clicked(Widget source, bool checked) { g_x = checked; if (checked) { writeln(checked); } return true; } auto check_a = new CheckBox("wantalt", "Alternating"d); auto check_b = new CheckBox("wantblinkb", "Blink(delg)"d); auto check_c = new CheckBox("wantblinkc", "Blink(direct)"d); check_a.checkChange = delegate(Widget w, bool checked) { g_x=checked; return true; }; check_b.checkChange = delegate(Widget w, bool checked) { return checkbox_b_clicked(w,checked); }; check_c.checkChange = checkbox_b_clicked; check_c.checkChange = &checkbox_b_clicked; The assignment to check_a is fine with the compiler. For check_b, I try calling a function defined earlier. (Maybe in real life it's too complex to try having inline.) It was giving a compiler error until I realized I'm dumb, wasn't passing 'w' and 'checked' to it. Fixed, works fine now. Okay! But what I think I should be able to do: assign checkbox_b_clicked directly to the .checkChange property of the checkbox, as shown for check_c. It doesn't work. Oh, I see an example where '&' is used - okay let's try that... nope! The compiler errors I get are, for no '&' and with '&': Error: function `app.checkbox_b_clicked(Widget source, bool checked)` is not callable using argument types `()` Error: none of the overloads of `opAssign` are callable using argument types `(bool function(Widget source, bool checked))`
Re: How to do same as 'nmap' command from within a D program?
On Sunday, 23 January 2022 at 06:30:11 UTC, frame wrote: On Saturday, 22 January 2022 at 20:55:38 UTC, Daren Scot Wilson wrote: I don't see any D std.* libraries that do this. Are there a Dub packages I should look at? If you really want to this in D without any external app or OS API you could just ping all possible hosts, see which respond and then use `getHostByAddr()` to find the hostname. Another more professional way is to query the ARP protocol, where you send a packet as broadcast to all interfaces in the network to find a MAC for a given IP - if any host responses with a MAC, the host is up. You have to build the packet data for yourself, there are examples on the web. The socket to use is family:INET, type:RAW and protocol:ICMP for ping or RAW for ARP or anything that isn't listed in D. As you can see, it's required to test every possible IP out (except for any other discovery protocols supported by your network/router). For this reason, any OS does this scan periodically and caches the result. On UNIX you can just directly read the file `/proc/net/arp`, no need to use nmap. I'll try this. Looks more educational. This is a personal project, a show-off project. Once I'm done with another portion of it, I'll get onto this. My program will need to scan only once, not even once per run, since I can stash the results in a config file, but once whenever the user knows the hardware devices have changed.
How to do same as 'nmap' command from within a D program?
I'm writing a command line program to control certain hardware devices. I can hardcode or have in a config file the IP addresses for the devices, if I know that info. If I don't? Then I run an 'nmap' command and look for the devices. But why should I, a human, have to do any work like that? Bah! I want my program to obtain this information at runtime, automatically, and "don't make me think". One thing that might make it tough is nmap must run sudo to report the desired information. (To my knowledge; I'm no networking expert.) The exact command is: sudo nmap -sn 192.168.11.0/24 |ack -B2 "Philips" The IP address is printed two lines before the name match (ack is "better than grep"). Typical nmap output is a series of chunks of text like this: Nmap scan report for 192.168.11.10 Host is up (0.00033s latency). MAC Address: 00:17:88:4D:97:4D (Philips Lighting BV) I don't see any D std.* libraries that do this. Are there a Dub packages I should look at?
Re: Simple BeamUI project won't link
On Wednesday, 16 December 2020 at 07:45:50 UTC, Ferhat Kurtulmuş wrote: On Wednesday, 16 December 2020 at 07:40:45 UTC, Ferhat Kurtulmuş wrote: This may be not your issue, but I could manage it to work by adding this line: subPackage "examples/myproject" to the dub.sdl of the beamui. I simply put my project in examples/ folder. And compile and run using: dub run :myproject The thought crossed my mind to try putting my source under examples/ but that's not a good way to organize a real project. I'd like it be under ~/projects/, naturally. What I want to make will involve a lot more than just a GUI.
Re: Simple BeamUI project won't link
On Wednesday, 16 December 2020 at 07:40:45 UTC, Ferhat Kurtulmuş wrote: On Wednesday, 16 December 2020 at 07:02:11 UTC, Daren Scot Wilson wrote: Trying out the beamui GUI package, obtained by git clone from github. The "basic" example builds and runs. I'm working on an Arch Linux machine with lots of RAM, but a user with not enough practice at D yet. I have a little experience with beamui but only on windows. It is under WIP. You'd better open an issue with an error report on GitHub as I did before https://github.com/dayllenger/beamui/issues/16. You may get some help from the maintainer. So maybe beamui isn't ready for the real world. It's a one-off personal tool for image processing, maybe will go up on Github, so I don't need anything super-solid or well established. OTOH, if it's too much on the WIP side with lots of loose ends, it might be more work than my free time allows. At least, beamui appears to be more workable than dlangui which seems to have fallen away.
Simple BeamUI project won't link
Trying out the beamui GUI package, obtained by git clone from github. The "basic" example builds and runs. So I create a new project from scratch, with "dub init beamy beamui" (ircc) in a directory outside beamui's, sibling to it in fact. This builds and runs, but does not make use of beamui at all. So I copy a tiny bit from the basic example. It only initializes a GuiApp: import std.stdio; import beamui; int main() { GuiApp app; if (!app.initialize()) { writeln("App no init :("); return 1; } return 0; } Here's the dub file: name "beamy" description "trying BeamUI" license "none" authors "darenw" targetName "beamy" targetType "executable" dependency "beamui" path="../../beamui/" dependency "beamui:platforms" path="../../beamui/platforms/" Running "dub build" leads to compiling but no linking. undefined reference to `initPlatformProxy'. Note that this build takes place in a directory such that ../../beamui/ goes to the top-level directory for beamui. Changing the path or replacing 'beamui' with 'beamuixxx' prevents the build from getting anywhere at all, so the path is right. I compared everything with the basic example, but am either missing some obvious detail or have something screwed up, or failed to add something, or need to say some secret magic incantation. I'm working on an Arch Linux machine with lots of RAM, but a user with not enough practice at D yet.
Re: Thread to watch keyboard during main's infinite loop
On Thursday, 7 May 2020 at 01:02:57 UTC, ag0aep6g wrote: Thank you, this is 110% helpful. Actually, I'd like to return the excess 10%. My dmd compiler does not like: import core.thread: sleep; so I put the code back the way I had, just to get on with work. Use `shared` so that all threads use the same variables: shared bool running=true; shared char command = '?'; "shared" did the job. I had read about "thread local" and "shared" in D before, but did not comprehend. Now I do :) This sequence of events is entirely possible: 1) main: cmd = command 2) cmdwatcher: command = c 3) main: command = ' ' It won't happen often, but if it does, your input has no effect. For this tool, lost key hits are not a problem. At least, that's what I say for now. I may be back next week for help with that. For now, the trousered ape running the software will just have to tap the key again. (Or the key + Enter.)
Thread to watch keyboard during main's infinite loop
I'm writing a simple command line tool to send data by UDP once per second forever, to test some software on another machine. Not actually forever, of course, but until ^C or I hit 'Q'. I want to tap keys to make other things happen, like change the data or rate of sending. Not sure of the best way to do this. Thought I'd try a thread whose job is just to loop, calling readln() or getch() or something similar, and setting a global variables according to what key was tapped. The loop in the main thread can then break, or do some other action, according to the value of that variable. Code I have written is below, stripped to just the stuff relevant to key watching. It doesn't work. When it runs, it prints "Repetitive work" over and over, but never see anything appear in "cmd [ ]". When I tap 'A' I expect to see "cmd [A]" and a line of several 'A'. This does not happen. But the writeln in cmdwatcher() does show whatever I typed just fine. How to fix this, or redesign the whole thing to work? Note that I'm coming from science and fine art. My know-how in computer science is uneven, and I probably have gaps in my knowledge about threads. import std.stdio; import core.stdc.stdio; // for getchar(). There's nothing similar in D std libs? import std.concurrency; import core.thread; // just for sleep() bool running=true; char command = '?'; void cmdwatcher() { writeln("Key Watcher"); while (running) { char c = cast(char)getchar(); if (c>=' ') { command = c; writefln(" key %c %04X", c, c); } } } void main() { writeln("Start main"); spawn(&cmdwatcher); while (running) { writeln("Repetitive work"); Thread.sleep( dur!("msecs")( 900 ) ); char cmd = command; // local copy can't change during rest of this loop command = ' '; writefln("cmd [%c] running %d", cmd, running); switch (cmd) { case 'A': writeln("A A A A A"); break; case 'Q': writeln("Quitting"); running=false; break; default: break; } } }
Re: Finding position of a value in an array
On Tuesday, 31 December 2019 at 06:01:36 UTC, Paul Backus wrote: countUntil operates on ranges, and static arrays aren't ranges. To get a range from a static array, you have to slice it with the `[]` operator: int i = info.doos[].countUntil(important_d); (Why can't static arrays be ranges? Because ranges can shrink, via popFront, but a static array can never change its length.) Aha, adding [] made the compiler happy.
Re: Finding position of a value in an array
On Monday, 30 December 2019 at 23:15:48 UTC, JN wrote: On Sunday, 29 December 2019 at 08:31:13 UTC, mipri wrote: int i = a.countUntil!(v => v == 55); assert(i == 2); I also had to ask because I couldn't find it. In other languages it's named "index()", "indexOf()" or "find()". D is the only language I know which uses the "countUntil" scheme. And even so it's not obvious from the name if it's the index of the element or number of preceding elements. I had first tried myarray.index(myvalue) because I coulda sworn I wrote exactly that syntax a only a few days ago. But I've been hopping between languages, some D, some Crystal, some C++, some Javascript, and with only two cerebral hemispheres, maybe I got confused. So, D doesn't have index()? Is it called find()? Something else? It was hard to find the right stuff in the documentation. So now I know about countUntil, and I'm glad the question has gotten some traction for others to make progress with their code. I'm needing to see more examples. It might have something to do with the array I'm working with being inside a foreach loop. My code looks like this, with the problematic line duplicated to show some of the variations I tried: import std.algorithm; alias doo = ubyte; struct Info { int x; doo[NDOOS] doos; // NDOOS = 10 } immutable int INFO = 10; Info[NINFOS] infos;// global array, used heavily. float foo_function(doo important_d){ ... foreach (info; infos){ int i = info.doos.index(important_d); // #1 int i = info.doos.countUntil(d => d == important_d); // #2 int i = info.doos.countUntil!(d => d == important_d); // #3 int i = countUntil(d => d == important_d, info.doos); // #4 int i = countUntil!(d => d == important_d)(info.doos); // #5 if (i>=0) { // assuming -1 represents value not found ... do stuff with i ... } } ... } All the lines shown give me "template ... cannot deduce function from argument types..." but one time I got, but cannot reproduce now, the error "Error: template instance countUntil!((d) => d == important_d, doos) has no value"
Finding position of a value in an array
Reading documentation... Array, Algorithms, ... maybe I've been up too late... how does one obtain the index of, say, 55 in an array like this int[] a = [77,66,55,44]; I want to do something like: int i = a.find_value_returning_its_index(55); assert(i==2) I'm sure it's obvious but I'm not seeing it right now.
Signs by which to recognize D1
Someone looks at a chunk of D code of murky origin. Possibly, it is old, maybe D1 not D2. Inadequately commented, believe it or not, and not other information. What are some easy to spot details in the syntax by which the onlooker can know it's D1 not D2?
Audio file read/write?
What's the current recommended way to read and write audio files? I don't need to play it on the speakers or deal with anything real time - just read a file's data into an array, fiddle with it, and write it out to a file. I found some other threads about audio files, but none recent, mentioning SDL and OpenAL. Are these still the way to go?I'm thinking I should avoid SDL since it does far more than audio, none of which I care about. OpenAL also does way more than I care about, but at least is just audio. For my application, I need to read a few of the common formats, such as .wav, .au, .mp3, .ogg and whatever else is popular. I only need to write .wav but other audio tinkerers may want to write other formats.