447 points · by ducktective · 5y ago · 179 comments
https://news.ycombinator.com/item?id=26958154
https://news.ycombinator.com/item?id=24919571
It's great to see GUI frameworks being designed in Rust, countering the trend of doing everything in Electron.
https://github.com/femtovg/femtovg
It's a decent starting point for trying to build your own toolkit.
I have recently added a wgpu backend but for now it lives in my fork https://github.com/adamnemecek/femtovg
run the demo with `cargo run --example wgpu_demo --release`.
Also join the femtovg discord https://discord.gg/V69VdVu
- GPLv3 - free
- "Ambassador" - free commercial license (after approval), in exchange for marketing as being built with sixtyfps and authorization to use your logo and feedback
- Normal commercial - paid
I kinda like the addition of the "Ambassador" tier. Seems like a fair exchange for an in-development framework, and would be a good option for people that are building a new product and don't yet have the revenue to justify the cost during the prototyping phase.
For the record, the rust community has mostly settled around dual-licensing under MIT/Apache for what you can call "foundational" crates ("libraries"), which are both far more liberal than the GPL.
To wit: Here's a way to implement it with Python and Tkinter for an old school reactive GUI.
https://maldus512.medium.com/how-to-setup-correctly-an-appli...
I wanted React with Elm-like architectures in WX enough that I got annoyed and built one ^_^
The real issue in that example seems to be that the event loop needs to wait for both UI events and read/write readyness on the serial port. This could probably be handled either with createfilehandler[1] (although it doesn't work on Windows) or by dedicating a thread to handling the serial port and posting messages to the Tkinter event loop as suggested at the end.
[1] https://docs.python.org/3/library/tkinter.html#file-handlers
Is the community active at all in 2021 or is it just the result of having basically one person working on the language?
I think there is a slow shift toward community built tools such as lambdera. The language itself is pretty stable (and good, IMHO).
Most of the news are available on the discourse discourse.elm-lang.org
Personally, I find working with Elm's state management features is like heaven compared to dealing with Redux+Typescript's intensely noisy types.
Anybody have any experience on how this compares to ReasonML + React?
Answering your question, the difference is Elm has a more expressive type system than javascript, and will catch a lot of errors for you, with excellent error reporting from the compiler.
The layout of the code becomes less important, because the compiler will catch most errors (actually recommended in elm guides not to split in too many files until overwhelmingly necessary)
https://crates.io/crates/iced/versions https://crates.io/crates/iced-x86/versions
I'm not sure there's a naming conflict here. There is little overlap between x86 decoding and a GUI library. If software is eating the world, then it's similar to Giant Bicycles and Giant Food Stores.
> There is little overlap between x86 decoding and a GUI library.
I work on a graphical tool that visualizes x86 binaries! It uses iced (the decoder), and it could very easily end up using iced (the GUI library).
I think both can keep their names long-term.
struct Counter {
// The counter value
value: i32,
// The local state of the two buttons
increment_button: button::State,
decrement_button: button::State,
}
impl Counter {
pub fn view(&mut self) -> Column<Message> {
...
}
}
this looks like it holds state in the ui layer... wouldn't it be better to keep state in some separate state/model object (struct) and bind the ui to that instead?not doing it this way couples a lot of logic/state to the ui framework which means its much harder to switch ui frameworks later, not to mention testing the logic independently of the ui choice...
im asking because i hope to get some insight not a silent downvote
https://github.com/ensisoft/gamestudio/blob/master/uikit/win...
I only ask because if it doesn't use platform text input, that is a non-starter for mobile.
It also would mean having to reimplement platform behavior for text input, like being able to hold Shift on macOS while moving the cursor to change text selection.
Self-implemented keyboard input pretty much only works for the simplest use case in english-native countries.
https://www.cmyr.net/blog/rust-gui-infra.html and the precursor https://www.cmyr.net/blog/gui-framework-ingredients.html
Browsers are actually a great example of my favorite approach to cross-platform UI, because they sprinkle platform-native widgets throughout the canvas that they render, controlled by a platform-agnostic programming language. Which reminds me that people were trying to use webrender[1] to build native apps in Rust.
Keyboard and key event input is much harder than it first appears. From multiple platforms to multiple languages to multiple keyboard interface devices to multiple layouts, and you cannot assume that the operating system provides a workable abstraction on its own.
I think there are approximately five viable Rust toolkits: Iced, Makepad, sixtyfps, egui, and Druid (in no particular order). Any of these five could evolve to being a real solution, with enough investment. Of course, it's possible another could arise, or that I've given short shrift to one of the other contenders (areweguiyet has a list, but that resource is not super well maintained).
There are some things easier to do in Iced than Druid (especially integration with 3D, which is something we currently don't do at all). On the other hand, we're pushing pretty hard on infrastructure: proper text handling, input methods, subwindows, etc. Currently, Druid relies on platform capabilities for 2D drawing, but my main work right now is a new GPU renderer. And we hope to work with 'mwcampbell on accessibility in the next year (integrating AccessKit).
We've got a great community, but tend not to toot our horn very loudly, so people might not be as aware of the progress we're making. By contrast, sixtyfps is a commercial product (in addition to a GPL release) and has weekly updates.
Thanks for the detailed answer. As an aching Linux user, I appreciate your focus on infrastructure and accessibility.
Here's an example of Druid rendering a button. https://github.com/linebender/druid/blob/master/druid/src/wi...
Have you done any benchmarking on how this compares with Electron on things like binary size, memory usage? Those are usually most common complaints people have with regards to Electron so would be nice to see the improvements this provides.
From what I understand, this will avoid that problem by compiling to whatever native platform you are building for? Also it'd not just be a webapp in a shell.
For some people in some senses, there's a big advantage to the 'webapp in a shell' model, because HTML/CSS is considered good, or WhizzBang.js is the familiar tool for building UIs, or whatever.
I didn't mean to say it's better (or worse) than this - it's just quite a different (more similar to Electron) approach, that'll suit some and not others.
And then accessibility brings with it the integration with different OSes via disparate APIs, so it will take some effort to offer a cross-platform API to the library user.
You'll notice that Iced is not >= 1.0 yet, so you shouldn't expect it to be fully-baked.
Neat! I really like the Rust ethos of creating modular cross-platform adopters (e.g. winit, getrandom), and from a brief skim this seems to fit that model.
It’s out there, so whether you finish it, someone forks it, or it just serves as inspiration for another project, you’ve contributed.
When you have an accident waterskiing and end up on crutches, you'll be glad for the accessibilty of doors that open with a button press. When you poke your eye hiking and need to wear an eyepatch for a few weeks, a screen reader might not seem such a niche use case.
These are even kind of extreme examples: frankly, even stuff like dark mode that we take for granted at this point is an accommodation to how some people need or want to use their computers. Migraines are a good example of an (astonishingly) common condition that benefits from flexibility around having to stare at a screen.
None of us gets younger as the days go by, either, and that comes with changed needs. I'm still thirty years from retirement and I find that the 10 point font I used to prefer isn't good enough anymore. Bumping up text size is a quotidian action for me and millions of other people.
ADDITION: Ah, finally found the quote I was looking for. Maybe not directly relevant, but thought-provoking:
> SMS texting was invented [to] figure out a way for deaf people to communicate with one another without speaking. ... Now text messages are universal.
https://blog.ai-media.tv/blog/why-designing-for-accessibilit...
I am person, who in last few days tried out to use VoiceOver and move responsibility on it to navigate me and read contents, when I could code while I had closed eyes. Ironically the most annoying interface was CLI, because I had to extend my focus on contents of the terminal. Imagine running docker-compose up and you are going to spammed with reading all logs. Next, usually I had problem to find some relative point that I could mark a "milestone" in my head, which will be further point from I will be reading.
Also, not all commands are read after executing them. Such command is silly pwd. Everytime I write it down I had to move the VO cursor to read the contents. Also many characters I would recognize as a programmer VO reads differently. Nano editor was complete unusable for me. While in vim I had notable problem to recognize indentations characters (sometimes they are read and sometimes they don't) and to know in what mode am I actually. brew update+upgrade was a nightmare for me. All kind of separators like #### are read as "number", "number" spam. The same situation was with "clear" command. It was read a hundreds of "space", "space", "space"... I was starting to think I am going to the Moon or I play Portal 2 [0].
I could continue writing down my disappointment about the CLI interface that was among my favorites in past but now after this week with VoiceOver I think it is terrible to be blind, because most of time I had to use my eyes to help myself to recognize where I am and what I need to click to move to next element. I was very surprised by the rofi-like find of elements that are on the screen (named as Rotor feature, CapsLock+U). With VO I don't any longer needed to use mouse, which for anybody who has problem with wrists is also a nice thing to consider.
1. All your actions are in one place. Figuring out what can happen as a result of a series of user interactions can be done without navigating through a component hierarchy.
2. The history of a user interaction is simple to serialize. In case of error, you can dump the user interaction history for this session (just a list of enum values, right?) to disk. This can then be submitted in bug reports for easy re-production of an issue.
3. It's simple(r) to create a time-travelling debugger that can move backwards and forwards in time, since it can simply re-play the series of messages to a specific point.
4. Since you've seperated state changes from the UI, writing unit tests that ensures that a series of user interactions results in a specific state is pretty easy. You just send in the enum values representing a specific use interaction then check what state you've ended up with.
I'd imagine it would be easier to just call a method on whatever we want to update, instead of lowering all our methods into enums. Why wouldn't we do that instead?
Also, serializing usually isn't enough to get the benefits you describe. You need true determinism for that, and that's very difficult to achieve. If you ever e.g. query the current date without recording it you've just introduced nondeterminism.
If we could really achieve deterministic replayability easily, then I might be okay with the drawback of turning methods into enums.
Easier how? The difference in lines of code is minimal. It's not going to make any meaningful difference in how much time you spend on crafting a solution.
> Also, serializing usually isn't enough to get the benefits you describe. You need true determinism for that, and that's very difficult to achieve. If you ever e.g. query the current date without recording it you've just introduced nondeterminism.
It requires some thought, but it isn't terribly difficult. Most user interactions with a gui doesn't require a side effect, and those that do can usually be written in a way that it gets represented in the enum. Even when nondeterminism creeps in, it rarely cancels out all of the benefits of having a history of user interaction. Perfect nedn't be the enemy of good.
https://blog.sigplan.org/2019/12/30/defunctionalization-ever...
There are significant advantages to this sort of defunctionalization in a system like this. It is a bit more administratively at the point of enum definition, but the flexibility and simplification of the other parts of the program will be a win for almost any non-trivial UI application, not to mention the future-proofing it gives you.
And by the way, defunctionalization sounds a lot like transforming my code into a bytecode interpreter which interprets my code. This is something I don't need and which would make my code slower and more difficult to read.
If you don't care about your values leaving your local OS process, which is a pretty common use case, there's a hybrid approach you can take too, which is to put closures inside your data structures that describe the value, instead of passing raw closures around. You get the benefits of being able to examine the values without executing the handler and being able to filter, decorate, etc. but while retaining all the advantages of being able to implement handlers inline. Depending on your local language, various slick implementations may allow this to be one degree or another of transparent, such as implementing some sort of interface/trait for all these values, or implementing __call__ in Python, etc.
"And by the way, defunctionalization sounds a lot like transforming my code into a bytecode interpreter which interprets my code. This is something I don't need and which would make my code slower and more difficult to read."
It depends on the language you're in. Most OO languages have some way of doing this that doesn't add any speed issues to speak of, it's just a slight rearrangement of code.
I'd also say this is an issue of scale. I don't bother with this in small programs and may just glue everything together with closures, but as program size increases the odds that you'll want to do something that you can't do with closures directly increase. But the languages I tend to work in don't make this much of a hassle usually, either. I think you may be overestimating the expense.
So instead of:
Button::new(&mut self.increment_button, Text::new("+"))
.on_press(Message::IncrementPressed)
you would write: Button::new(&mut self.increment_button, Text::new("+"))
.on_press(|| MY_CODE_HERE)
For comparison, in JavaScript you can write: button.onclick = function(){ ++counter; }
That's quite a direct way of formulating what you want to happen. All in a single line and no Enums involved.[Edit: Ignore this next paragraph; as steveklabnik pointed out, this change has already been implemented and "Message(|c| c.value += 1)" is accepted by the latest stable version.] Incidentally, as long as there are situations where only function pointers can be used and not closures it would be really nice to have some support for anonymous function pointers in Rust (with the fn type and not just the Fn trait) so that one could write e.g. "Message(fn |c| c.value += 1)" instead of "Message({ fn f(c: &mut Counter) { c.value += 1 } f })". Or just infer the fn type for "closures" which don't actually close over any variables without the need for an extra keyword.
[0] https://github.com/nybble41/iced-counter2/blob/master/src/ma...
I mean, we're not really doing this anymore, right?
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0) {}In Rust, if you want to access shared state, you need to hold onto a reference to it. If a reference captured by a closure is unique, the compiler conservatively prevents you from not only accessing that variable, but anything that could transitively lead to it, and if it's shared, the compiler prevents you from mutating anything that could lead to it. Additionally, you can't move or destroy the object until there's no chance any value transitively referenced through it is still borrowed--which across threads, often means pretty much no borrow length will suffice. In a UI framework sending stuff across threads, that's a totally unacceptable state of affairs. By contrast, enums that declaratively specify what you want to modify have no such issues, because the state only needs to be accessed when you actually want to run the event.
There are three ways to work around the lifetime part, but they're not ideal. The most common is to use something like Rc or Arc, which allow reference counting (a primitive form of garbage collection). Reference counting always makes your objects shared, so it guarantees you'll have to tackle the mutation problem somehow, which can be unsatisfying; it also has a runtime cost (which can be quite significant) and can cause memory leaks if you have cycles in your data (though this is rarely an issue in UI frameworks). Secondly, you can architect your application around things like arenas, which give you "scoped" access to lifetimes--these can be really efficient with the right use case, especially pointer-spaghetti graphs, but can restrict a lot of the patterns you'd write in Rust, since the arenas have to outlive everything you want to do with the objects. Finally, you can separate your shared data from the closure--which works great but now you are restricted to "bare" functions or functions that only capture unrelated state. The closure can't specify the state it wants to update, it has to be directed to the object--which is much less ideal (since now the closures aren't universal in any way, as they need to be passed in the state they want to modify).
You can work around the mutation part in two ways, but neither is that great. One is, again, to ban closures from capturing any environment state, so the data is still stored separately and has to be passed in, which has the limitations mentioned previously.
The other is to use "interior mutability" which uses some combination of runtime checks and other restrictions to guarantee that you're only accessing the element one at a time. Almost invariably, these mechanisms are slower at runtime, restrict your types somehow (e.g. making them non thread safe), can cause your program to panic if you misuse them, or are just plain annoying to use (or some combination of all of these). So when you can avoid this option, you do!
So basically: enums make a ton of sense in Rust because they totally avoid these borrow checker issues. Your intuitions about using closures for this stuff in functional or garbage collected languages don't apply here--patterns that make a lot of sense in them don't work at all in Rust. That's one big reason there are so many Rust UI frameworks rather than just wrapping the C ones or using the same patterns you see in functional languages--the usual patterns simply don't work well.
That's not say there aren't some upsides to the approach from a reasoning standpoint. A big one is that it enforces "single writer" control flow--just one place is responsible for all the state updates, so you don't have to worry about synchronization weirdness due to lots of places updating the state on their own. IME, this helps a lot with reasoning. But not everyone agrees that that outweighs the convenience of being able to use a callback, which I totally get--it's just that the "convenient way" isn't really convenient in Rust at all. And it's this that causes all these libraries to be designed this way (at least that's been my experience), not theoretical concerns about serialization and stuff which I agree is basically a nonissue in practice.
I'm trying to make a language (https://vale.dev/) that addresses the borrow checker's limitations (by making it automatic and opt-in) to handle cases like these, if you want to drop by our discord (https://discord.gg/SNB8yGH), I'd love to get your thoughts!
Unfortunately Rust as a language pays the price for its flexibility here. By not mandating any particular memory management or interior mutability strategy, it makes even the safe cases like this (which are relatively "easy" to validate for safety) much more complex. So if your use case is in the intersection that Vala supports, I agree this can be a great point in the tradeoff space! FYI, you might want to check out old work on the MLton optimizing compiler, which also did automatic region inference to avoid garbage collection.
An `update` does not always precede `view`. In fact, `view` is called first after initializing the application.
Thus, I believe the example in the `README` is following the proper order :)
I've had no issues with Iced on any other platforms, fwiw.
[1] https://github.com/hecrj/iced/tree/master/web [2] https://github.com/hecrj/iced/tree/master/wgpu [3] https://github.com/hecrj/iced/blob/master/ECOSYSTEM.md
And an outsider might have trouble following the conversation, but that would happen no matter what words are used. Whether we say "Elm" or "C++", the target audience knows what's meant and others wouldn't be able to follow either way.
All languages evolve over time, despite official bodies trying to reject foreign influence. (IIRC the French government has a department that tries to limit loan words from other languages, but good luck with that given the internet.)
So what's the actual problem with it? Only downside I see is google-ability and occasional conflicts when two projects use the same name. Both of those exist with any naming Scheme (ha!) and imho haven't really ended badly for projects or their users.
GUI state mutations are triggered by messages passed around the system. Messages can be generated from user interactions for by asynchronous subscriptions (network socket, etc).
Which is cool but a custom rendered UI would be cooler.