Initial Commit

This commit is contained in:
david-swift 2023-09-12 07:39:39 +02:00
commit a1c8c3b891
84 changed files with 3652 additions and 0 deletions

40
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@ -0,0 +1,40 @@
name: Bug report
description: Something is not working as expected.
title: Description of the bug
labels: bug
body:
- type: textarea
attributes:
label: Describe the bug
description: >-
A clear and concise description of what the bug is.
validations:
required: true
- type: textarea
attributes:
label: To Reproduce
description: >-
Steps to reproduce the behavior.
placeholder: |
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
validations:
required: true
- type: textarea
attributes:
label: Expected behavior
description: >-
A clear and concise description of what you expected to happen.
validations:
required: true
- type: textarea
attributes:
label: Additional context
description: >-
Add any other context about the problem here.

View File

@ -0,0 +1,37 @@
name: Components request
description: Suggest an idea for a new component
title: Description of the component request
labels: enhancement
body:
- type: textarea
attributes:
label: Why would you like to add a new component?
placeholder: >-
A clear and concise description of why the component should be added.
validations:
required: false
- type: textarea
attributes:
label: Name the equivalents in GTUI.
placeholder: >-
A list of the equivalents in the GTUI library in SwiftGui (see dependencies).
validations:
required: true
- type: textarea
attributes:
label: Describe your idea for the implementation.
placeholder: >-
What could the implementation be like in Adwaita?
validations:
required: false
- type: textarea
attributes:
label: Additional context
placeholder: >-
Add any other context about the component request here.
validations:
required: false

View File

@ -0,0 +1,36 @@
name: Feature request
description: Suggest an idea for this project
title: Description of the feature request
labels: enhancement
body:
- type: input
attributes:
label: Is your feature request related to a problem? Please describe.
placeholder: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
validations:
required: false
- type: textarea
attributes:
label: Describe the solution you'd like
placeholder: >-
A clear and concise description of what you want to happen.
validations:
required: true
- type: textarea
attributes:
label: Describe alternatives you've considered
placeholder: >-
A clear and concise description of any alternative solutions or features you've considered.
validations:
required: true
- type: textarea
attributes:
label: Additional context
placeholder: >-
Add any other context or screenshots about the feature request here.
validations:
required: true

14
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,14 @@
## Steps
- [ ] Add your name or username and a link to your GitHub profile into the [Contributors.md][1] file.
- [ ] Build the project on your machine. If it does not compile, fix the errors.
- [ ] Describe the purpose and approach of your pull request below.
- [ ] Submit the pull request. Thank you very much for your contribution!
## Purpose
_Describe the problem or feature._
_If there is a related issue, add the link._
## Approach
_Describe how this pull request solves the problem or adds the feature._
[1]: /Contributors.md

30
.github/workflows/swiftlint.yml vendored Normal file
View File

@ -0,0 +1,30 @@
name: SwiftLint
on:
push:
paths:
- '.github/workflows/swiftlint.yml'
- '.swiftlint.yml'
- '**/*.swift'
pull_request:
paths:
- '.github/workflows/swiftlint.yml'
- '.swiftlint.yml'
- '**/*.swift'
workflow_dispatch:
paths:
- '.github/workflows/swiftlint.yml'
- '.swiftlint.yml'
- '**/*.swift'
jobs:
SwiftLint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: SwiftLint
uses: norio-nomura/action-swiftlint@3.2.1
with:
args: --strict
env:
WORKING_DIRECTORY: Source

11
.gitignore vendored Normal file
View File

@ -0,0 +1,11 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
xcuserdata/
DerivedData/
.swiftpm/config/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc
/Package.resolved
.Ulysses-Group.plist

170
.swiftlint.yml Normal file
View File

@ -0,0 +1,170 @@
# Opt-In Rules
opt_in_rules:
- anonymous_argument_in_multiline_closure
- array_init
- attributes
- closure_body_length
- closure_end_indentation
- closure_spacing
- collection_alignment
- comma_inheritance
- conditional_returns_on_newline
- contains_over_filter_count
- contains_over_filter_is_empty
- contains_over_first_not_nil
- contains_over_range_nil_comparison
- convenience_type
- discouraged_none_name
- discouraged_object_literal
- discouraged_optional_boolean
- discouraged_optional_collection
- empty_collection_literal
- empty_count
- empty_string
- enum_case_associated_values_count
- explicit_init
- fallthrough
- file_header
- file_name
- file_name_no_space
- first_where
- flatmap_over_map_reduce
- force_unwrapping
- function_default_parameter_at_end
- identical_operands
- implicit_return
- implicitly_unwrapped_optional
- joined_default_parameter
- last_where
- legacy_multiple
- let_var_whitespace
- literal_expression_end_indentation
- local_doc_comment
- lower_acl_than_parent
- missing_docs
- modifier_order
- multiline_arguments
- multiline_arguments_brackets
- multiline_function_chains
- multiline_literal_brackets
- multiline_parameters
- multiline_parameters_brackets
- no_extension_access_modifier
- no_grouping_extension
- no_magic_numbers
- number_separator
- operator_usage_whitespace
- optional_enum_case_matching
- prefer_self_in_static_references
- prefer_self_type_over_type_of_self
- prefer_zero_over_explicit_init
- prohibited_interface_builder
- redundant_nil_coalescing
- redundant_type_annotation
- return_value_from_void_function
- shorthand_optional_binding
- sorted_first_last
- sorted_imports
- static_operator
- strict_fileprivate
- switch_case_on_newline
- toggle_bool
- trailing_closure
- type_contents_order
- unneeded_parentheses_in_closure_argument
- yoda_condition
# Disabled Rules
disabled_rules:
- block_based_kvo
- class_delegate_protocol
- dynamic_inline
- is_disjoint
- no_fallthrough_only
- notification_center_detachment
- ns_number_init_as_function_reference
- nsobject_prefer_isequal
- private_over_fileprivate
- redundant_objc_attribute
- self_in_property_initialization
- todo
- unavailable_condition
- valid_ibinspectable
- xctfail_message
# Custom Rules
custom_rules:
github_issue:
name: 'GitHub Issue'
regex: '//.(TODO|FIXME):.(?!.*(https://github\.com/david-swift/Adwaita/issues/\d))'
message: 'The related GitHub issue must be included in a TODO or FIXME.'
severity: warning
fatal_error:
name: 'Fatal Error'
regex: 'fatalError.*\(.*\)'
message: 'Fatal error should not be used.'
severity: error
enum_case_parameter:
name: 'Enum Case Parameter'
regex: 'case [a-zA-Z0-9]*\([a-zA-Z0-9\.<>?,\n\t =]+\)'
message: 'The associated values of an enum case should have parameters.'
severity: warning
tab:
name: 'Whitespaces Instead of Tab'
regex: '\t'
message: 'Spaces should be used instead of tabs.'
severity: warning
string_literals:
name: 'String Literals'
regex: '(".*")|("""(.|\n)*""")'
message: 'String literals should not be used. Disable this rule in String and LocalizedStringResource extensions.'
match_kinds:
- string
severity: warning
# Thanks to the creator of the SwiftLint rule
# "empty_first_line"
# https://github.com/coteditor/CotEditor/blob/main/.swiftlint.yml
# in the GitHub repository
# "CotEditor"
# https://github.com/coteditor/CotEditor
empty_first_line:
name: 'Empty First Line'
regex: '(^[ a-zA-Z ]*(?:protocol|extension|class|struct) (?!(?:var|let))[ a-zA-Z:]*\{\n *\S+)'
message: 'There should be an empty line after a declaration'
severity: error
# Analyzer Rules
analyzer_rules:
- unused_declaration
- unused_import
# Options
file_header:
required_pattern: '(// swift-tools-version: .+)?//\n// .*.swift\n// Adwaita\n//\n// Created by .* on .*\.(\n// Edited by (.*,)+\.)*\n(\n// Thanks to .* for the .*:\n// ".*"\n// https://.* \(\d\d.\d\d.\d\d\))*//\n'
missing_docs:
warning: [internal, private]
error: [open, public]
excludes_extensions: false
excludes_inherited_types: false
type_contents_order:
order:
- case
- type_alias
- associated_type
- type_property
- instance_property
- ib_inspectable
- ib_outlet
- subscript
- initializer
- deinitializer
- subtype
- type_method
- view_life_cycle_method
- ib_action
- other_method

50
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,50 @@
# Contributing
Thank you very much for taking the time for contributing to this project.
## Report a Bug
Just open a new issue on GitHub and describe the bug. It helps if your description is detailed. Thank you very much for your contribution!
## Suggest a New Feature
Just open a new issue on GitHub and describe the idea. Thank you very much for your contribution!
### Suggest a New Component
If you want to be able to access a component from Libadwaita or GTK that is currently not available in Adwaita, you can add it to [SwiftGui](https://github.com/JCWasmx86/SwiftGui).
If you want to add an Adwaita interface for an already existing GTUI widget, open an issue.
## Pull Requests
I am happy for every pull request, you do not have to follow these guidelines. However, it might help you to understand the project structure and make it easier for me to merge your pull request. Thank you very much for your contribution!
### 1. Fork & Clone this Project
Start by clicking on the `Fork` button at the top of the page. Then, clone this repository to your computer.
### 2. Open the Project
Open the project folder in GNOME Builder, Xcode or another IDE.
### 3. Understand the Project Structure
- The `README.md` file contains a description of the app or package.
- The `Contributors.md` file contains the names or user names of all the contributors with a link to their GitHub profile.
- The `LICENSE.md` contains an GPL-3.0 license.
- `CONTRIBUTING.md` is this file.
- Directory `Icons` that contains PNG and PXD (Pixelmator Pro) files for the images used in the app and guides.
- Directory `Documentation` that contains the documentation generated with [SourceDocs][1].
- `Sources` contains the source code of the project.
- `Adwaita` contains the source code of the project.
- `Model` is the directory with Adwaita's basis.
- `Data Flow` contains property wrappers and protocols required for managing the updates of a view.
- `Extensions` contains all the extensions of types that are not defined in this project.
- `User Interface` contains protocols and structures that are the basis of presenting content to the user.
- `View` contains structures that conform to the `View` protocol and provide an easier-to-use wrapper around a GTUI `NativeWidgetPeer` type.
- `Window` contains structures that conform to the `Window` protocol and simplify the creation of different types of windows.
- `Tests` contains an example application for testing `Adwaita`.
### 4. Edit the Code
Edit the code. If you add a new type, add documentation in the code.
### 5. Commit to the Fork
Commit and push the fork.
### 6. Pull Request
Open GitHub to submit a pull request. Thank you very much for your contribution!
[1]: https://github.com/SourceDocs/SourceDocs

3
Contributors.md Normal file
View File

@ -0,0 +1,3 @@
# Contributors
- [david-swift](https://github.com/david-swift)

View File

@ -0,0 +1,52 @@
# Reference Documentation
## Protocols
- [App](protocols/App.md)
- [StateProtocol](protocols/StateProtocol.md)
- [View](protocols/View.md)
- [Widget](protocols/Widget.md)
- [WindowScene](protocols/WindowScene.md)
## Structs
- [Binding](structs/Binding.md)
- [Button](structs/Button.md)
- [EitherView](structs/EitherView.md)
- [HeaderBar](structs/HeaderBar.md)
- [InspectorWrapper](structs/InspectorWrapper.md)
- [State](structs/State.md)
- [Text](structs/Text.md)
- [UpdateObserver](structs/UpdateObserver.md)
- [VStack](structs/VStack.md)
## Classes
- [GTUIApp](classes/GTUIApp.md)
- [State.Storage](classes/State.Storage.md)
- [ViewStorage](classes/ViewStorage.md)
- [WindowStorage](classes/WindowStorage.md)
## Enums
- [ArrayBuilder](enums/ArrayBuilder.md)
- [ArrayBuilder.Component](enums/ArrayBuilder.Component.md)
- [ViewBuilder](enums/ViewBuilder.md)
- [ViewBuilder.Component](enums/ViewBuilder.Component.md)
## Extensions
- [App](extensions/App.md)
- [Array](extensions/Array.md)
- [NativeWidgetPeer](extensions/NativeWidgetPeer.md)
- [String](extensions/String.md)
- [View](extensions/View.md)
- [Widget](extensions/Widget.md)
## Typealiases
- [Body](typealiases/Body.md)
- [Scene](typealiases/Scene.md)
- [SceneBuilder](typealiases/SceneBuilder.md)
This file was generated by [SourceDocs](https://github.com/eneko/SourceDocs)

View File

@ -0,0 +1,30 @@
**CLASS**
# `GTUIApp`
The GTUI application.
## Properties
### `updateHandlers`
The handlers which are called when a state changes.
### `body`
The app's content.
### `sceneStorage`
The scenes that are displayed.
## Methods
### `init(_:body:)`
Initialize the GTUI application.
- Parameters:
- id: The application id.
- body: The application's content.
### `onActivate()`
The entry point of the application.

View File

@ -0,0 +1,17 @@
**CLASS**
# `State.Storage`
A class storing the value.
## Properties
### `value`
The stored value.
## Methods
### `init(value:)`
Initialize the storage.
- Parameters:
- value: The value.

View File

@ -0,0 +1,27 @@
**CLASS**
# `ViewStorage`
Store a rendered view in a view storage.
## Properties
### `view`
The GTUI widget.
### `content`
The view's content.
### `state`
The view's state (used in `VStack`).
## Methods
### `init(_:content:state:)`
Initialize a view storage.
- Parameters:
- view: The GTUI widget.
- content: The view's content.
- state: The view's state.

View File

@ -0,0 +1,22 @@
**CLASS**
# `WindowStorage`
A storage for an app's window.
## Properties
### `window`
The GTUI window.
### `view`
The content's storage.
## Methods
### `init(window:view:)`
Initialize a window storage.
- Parameters:
- window: The GTUI window.
- view: The content's storage.

View File

@ -0,0 +1,14 @@
**ENUM**
# `ArrayBuilder.Component`
A component used in the ``ArrayBuilder``.
## Cases
### `element(_:)`
An element as a component.
### `components(_:)`
An array of components as a component.

View File

@ -0,0 +1,75 @@
**ENUM**
# `ArrayBuilder`
The ``ArrayBuilder`` is a simple result builder that outputs an array of any type.
You can define any array using Swift's DSL:
```swift
@ArrayBuilder<String> var string: [String] {
"Hello, "
if bool {
"world!"
} else {
"colibri!"
}
for x in 0...10 {
"\nIteration Number \(x)"
}
}
```
## Methods
### `buildBlock(_:)`
Build combined results from statement blocks.
- Parameter components: The components.
- Returns: The components in a component.
### `buildExpression(_:)`
Translate an element into an ``ArrayBuilder.Component``.
- Parameter element: The element to translate.
- Returns: A component created from the element.
### `buildExpression(_:)`
Translate an array of elements into an ``ArrayBuilder.Component``.
- Parameter elements: The elements to translate.
- Returns: A component created from the element.
### `buildExpression(_:)`
Fetch a component.
- Parameter component: A component.
- Returns: The component.
### `buildOptional(_:)`
Enables support for `if` statements without an `else`.
- Parameter component: An optional component.
- Returns: A nonoptional component.
### `buildEither(first:)`
Enables support for `if`-`else` and `switch` statements.
- Parameter component: A component.
- Returns: The component.
### `buildEither(second:)`
Enables support for `if`-`else` and `switch` statements.
- Parameter component: A component.
- Returns: The component.
### `buildArray(_:)`
Enables support for `for..in` loops.
- Parameter components: The components as a two dimensional array.
- Returns: The components as a one dimensional array.
### `buildFinalResult(_:)`
Convert a component to an array of elements.
- Parameter component: The component to convert.
- Returns: The generated array of elements.

View File

@ -0,0 +1,14 @@
**ENUM**
# `ViewBuilder.Component`
A component used in the ``ArrayBuilder``.
## Cases
### `element(_:)`
A view as a component.
### `components(_:)`
An array of components as a component.

View File

@ -0,0 +1,54 @@
**ENUM**
# `ViewBuilder`
The ``ViewBuilder`` is a result builder for views.
## Methods
### `buildBlock(_:)`
Build combined results from statement blocks.
- Parameter components: The components.
- Returns: The components in a component.
### `buildExpression(_:)`
Translate an element into a ``ViewBuilder.Component``.
- Parameter element: The element to translate.
- Returns: A component created from the element.
### `buildExpression(_:)`
Translate an array of elements into a ``ViewBuilder.Component``.
- Parameter elements: The elements to translate.
- Returns: A component created from the element.
### `buildExpression(_:)`
Fetch a component.
- Parameter component: A component.
- Returns: The component.
### `buildOptional(_:)`
Enables support for `if` statements without an `else`.
- Parameter component: An optional component.
- Returns: A nonoptional component.
### `buildEither(first:)`
Enables support for `if`-`else` and `switch` statements.
- Parameter component: A component.
- Returns: The component.
### `buildEither(second:)`
Enables support for `if`-`else` and `switch` statements.
- Parameter component: A component.
- Returns: The component.
### `buildFinalResult(_:)`
Convert a component to an array of elements.
- Parameter component: The component to convert.
- Returns: The generated array of elements.

View File

@ -0,0 +1,8 @@
**EXTENSION**
# `App`
## Methods
### `main()`
The application's entry point.

View File

@ -0,0 +1,21 @@
**EXTENSION**
# `Array`
## Methods
### `widget()`
Get a widget from a collection of views.
- Returns: A widget.
### `update(_:)`
Update a collection of views with a collection of view storages.
- Parameters:
- storage: The collection of view storages.
### `checkIndex(_:)`
Check if a given index is valid for the array.
- Parameter index: The index to test.
- Returns: Return whether the index is valid or not.

View File

@ -0,0 +1,11 @@
**EXTENSION**
# `Binding`
## Methods
### `model(_:)`
Share an observable model with the child view.
- Parameters
- model: The observable model.
- Returns: The binding.

View File

@ -0,0 +1,9 @@
**EXTENSION**
# `Box`
## Methods
### `vertical()`
Initialize a vertical `GTUI.Box`.
- Returns: The vertical box.

View File

@ -0,0 +1,20 @@
**EXTENSION**
# `NativeWidgetPeer`
## Methods
### `update(_:)`
A `GTUI.NativeWidgetPeer` is static.
- Parameter storage: The view storage.
### `container()`
A `GTUI.NativeWidgetPeer`'s container is itself.
- Returns: The view storage.
### `modifier(code:)`
Get a modifier stirng.
- Parameter code: The modifier.
- Returns: The string.

View File

@ -0,0 +1,12 @@
**EXTENSION**
# `String`
## Properties
### `mainContent`
A label for main content in a view storage.
### `transition`
A label for the transition data in a GTUI widget's fields.

View File

@ -0,0 +1,71 @@
**EXTENSION**
# `View`
## Methods
### `widget()`
Wrap the view into a widget.
- Returns: The widget.
### `updateStorage(_:)`
Update a storage to a view.
- Parameter storage: The storage.
### `storage()`
Get a storage.
- Returns: The storage.
### `inspect(_:)`
Modify a GTUI widget before being displayed.
- Parameter modify: Modify the widget.
- Returns: A view.
### `padding(_:_:)`
Add padding around a view.
- Parameters:
- padding: The size of the padding.
- edges: The edges which are affected by the padding.
- Returns: A view.
### `hexpand(_:)`
Enable or disable the horizontal expansion.
- Parameter enabled: Whether it is enabled or disabled.
- Returns: A view.
### `vexpand(_:)`
Enable or disable the vertical expansion.
- Parameter enabled: Whether it is enabled or disabled.
- Returns: A view.
### `frame(minWidth:minHeight:)`
Set the view's minimal width or height.
- Parameters:
- minWidth: The minimal width.
- minHeight: The minimal height.
- Returns: A view.
### `frame(maxSize:)`
Set the view's maximal size.
- Parameter maxSize: The maximal size.
- Returns: A view.
### `transition(_:)`
Set the view's transition.
- Parameter transition: The transition.
- Returns: A view.
### `onUpdate(_:)`
Run a function when the view gets an update.
- Parameter onUpdate: The function.
- Returns: A view.

View File

@ -0,0 +1,8 @@
**EXTENSION**
# `Widget`
## Properties
### `view`
A widget's view is empty.

View File

@ -0,0 +1,11 @@
**EXTENSION**
# `WindowScene`
## Methods
### `getWindow(app:)`
Get the `GTUI.Window` with the content.
- Parameters:
- app: The application.
- Returns: The window.

View File

@ -0,0 +1,37 @@
**PROTOCOL**
# `App`
A structure conforming to `App` is the entry point of your app.
```swift
@main
struct Test: App {
let id = "io.github.david-swift.TestApp"
var app: GTUIApp!
var scene: Scene {
WindowScene()
}
}
```
## Properties
### `id`
The app's application ID.
### `scene`
The app's windows.
### `app`
The app.
## Methods
### `init()`
An app has to have an `init()` initializer.

View File

@ -0,0 +1,34 @@
**PROTOCOL**
# `Observable`
A protocol allowing a class to be observed by a view, window or app.
Views, windows and apps will automatically observe all of its children with an observable type.
```swift
@Observable
class ViewState {
var boolean = false
}
@View
struct TestView {
private let state = ViewState()
var view: Body {
// ...
}
}
```
## Properties
### `didChange`
This function gets called when a property changes.
A view will automatically add a function to this variable.

View File

@ -0,0 +1,10 @@
**PROTOCOL**
# `StateProtocol`
An interface for accessing `State` without specifying the generic type.
## Properties
### `value`
The type-erased value.

View File

@ -0,0 +1,21 @@
**PROTOCOL**
# `View`
A structure conforming to `View` is referred to as a view.
It can be part of a body.
```swift
struct Test: View {
var view: Body {
AnotherView()
}
}
```
## Properties
### `view`
The view's content.

View File

@ -0,0 +1,15 @@
**PROTOCOL**
# `Widget`
A widget is a view that know about its GTUI widget.
## Methods
### `container()`
The view storage.
### `update(_:)`
Update the stored content.
- Parameter storage: The storage to update.

View File

@ -0,0 +1,5 @@
**PROTOCOL**
# `WindowScene`
A structure conforming to `WindowScene` can be added to an app's `scene`.

View File

@ -0,0 +1,68 @@
**STRUCT**
# `Binding`
A property wrapper for a property of a view that binds the property of the parent view.
```swift
struct Grandparent: View {
@State private var state = false
var view: Body {
Parent(value: $state)
}
}
struct Parent: View {
@Binding var value: Bool
var view: Body {
Child(value: $value)
}
}
struct Child: View {
@Binding var value: Bool
var view: Body {
// ...
}
}
```
## Properties
### `wrappedValue`
The value.
### `projectedValue`
Get the value as a binding using the `$` prefix.
### `getValue`
The closure for getting the value.
### `setValue`
The closure for settings the value.
## Methods
### `init(get:set:)`
Initialize a property that is bound from a parent view.
- Parameters:
- get: The closure for getting the value.
- set: The closure for setting the value.
### `constant(_:)`
Initialize a property that does not react to changes in the child view.
- Parameters:
- value: The constant value.
- Returns: The binding.

View File

@ -0,0 +1,44 @@
**STRUCT**
# `Button`
A button widget.
## Properties
### `label`
The button's label.
### `icon`
The button's icon.
### `handler`
The button's action handler.
## Methods
### `init(_:icon:handler:)`
Initialize a button.
- Parameters:
- label: The button's label.
- icon: The button's icon.
- handler: The button's action handler.
### `init(_:handler:)`
Initialize a button.
- Parameters:
- label: The buttons label.
- handler: The button's action handler.
### `update(_:)`
Update a button's view storage.
- Parameter storage: The view storage.
### `container()`
Get a button's view storage.
- Returns: The button's view storage.

View File

@ -0,0 +1,60 @@
**STRUCT**
# `EitherView`
An equivalent to GtkStack for two views.
## Properties
### `trueView`
The view that is displayed when `isTrue` is true.
### `falseView`
The view that is displayed when `isTrue` is false.
### `isTrue`
The state.
## Methods
### `init(_:_:else:)`
Initialize an `EitherView`.
- Parameters:
- isTrue: The state.
- _: The view that is presented if `isTrue` is true.
- else: The view that is presented if `isTrue` is false.
### `init(_:_:else:)`
Initialize an `EitherView`.
- Parameters:
- isTrue: The state.
- trueView: The view that is presented if `isTrue` is true.
- falseView: The view that is presented if `isTrue` is false.
### `update(_:)`
Update an `EitherView`'s storage.
- Parameter storage: The view storage.
### `updateContent(_:state:stack:)`
Update the content of a view in the view storage.
- Parameters:
- storage: The view storage.
- state: Whether it is the true or false view.
- stack: The stack.
### `setVisible(_:view:)`
Set the visible content page.
- Parameters:
- stack: The stack.
- view: The visible view.
### `container()`
Get a GtkStack view storage.
- Returns: The view storage.

View File

@ -0,0 +1,52 @@
**STRUCT**
# `HeaderBar`
A header bar widget.
## Properties
### `start`
The start content of the header bar.
### `end`
The end content of the header bar.
### `startID`
The start content's id.
### `endID`
The end content's id.
## Methods
### `init(start:end:)`
Initialize a header bar.
- Parameters:
- start: The start content.
- end: The end content.
### `start(start:)`
Initialize a header bar with only views at the start.
- Parameter start: The views.
- Returns: The header bar.
### `end(end:)`
Initialize a header bar with only views at the end.
- Parameter start: The views.
- Returns: The header bar.
### `update(_:)`
Update a header bar's view storage.
- Parameter storage: The view storage.
### `container()`
Get the container for a header bar.
- Returns: The view storage.

View File

@ -0,0 +1,25 @@
**STRUCT**
# `InspectorWrapper`
A widget which executes a custom code on the GTUI widget when being created.
## Properties
### `modify`
The custom code to edit the widget.
### `content`
The wrapped view.
## Methods
### `container()`
Get the content's container.
- Returns: The content's container.
### `update(_:)`
Update the content.
- Parameter storage: The content's storage.

View File

@ -0,0 +1,8 @@
**STRUCT**
# `SceneStorage.ViewStorage`
## Properties
### `view`
### `content`

View File

@ -0,0 +1,8 @@
**STRUCT**
# `SceneStorage.WindowStorage`
## Properties
### `window`
### `views`

View File

@ -0,0 +1,11 @@
**STRUCT**
# `SceneStorage`
## Properties
### `app`
### `windows`
## Methods
### `init()`

View File

@ -0,0 +1,33 @@
**STRUCT**
# `State`
A property wrapper for properties in a view that should be stored throughout view updates.
## Properties
### `wrappedValue`
Access the stored value. This updates the views when being changed.
### `projectedValue`
Get the value as a binding using the `$` prefix.
### `storage`
The stored value.
### `value`
The value with an erased type.
## Methods
### `init(wrappedValue:)`
Initialize a property representing a state in the view.
- Parameters:
- wrappedValue: The wrapped value.
### `updateViews()`
Update all of the views.

View File

@ -0,0 +1,26 @@
**STRUCT**
# `Text`
A text widget.
## Properties
### `text`
The content.
## Methods
### `init(_:)`
Initialize a text widget.
- Parameter text: The content.
### `update(_:)`
Update the view storage of the text widget.
- Parameter storage: The view storage.
### `container()`
Get the container of the text widget.
- Returns: The view storage.

View File

@ -0,0 +1,25 @@
**STRUCT**
# `UpdateObserver`
A widget which executes a custom code when being updated.
## Properties
### `onUpdate`
The function.
### `content`
The content.
## Methods
### `container()`
Get the content's container.
- Returns: The content's container.
### `update(_:)`
Update the content.
- Parameter storage: The content's storage.

View File

@ -0,0 +1,37 @@
**STRUCT**
# `VStack`
A GtkBox equivalent.
## Properties
### `content`
The content.
### `state`
The state information (from properties with the `State` wrapper).
## Methods
### `init(content:)`
Initialize a `VStack`.
- Parameter content: The view content.
### `init(content:state:)`
Initialize a `VStack`.
- Parameters:
- content: The view content.
- state: The state information.
### `update(_:)`
Update a view storage.
- Parameter storage: The view storage.
### `container()`
Get a view storage.
- Returns: The view storage.

View File

@ -0,0 +1,5 @@
**TYPEALIAS**
# `Body`
`Body` is an array of views.

View File

@ -0,0 +1,5 @@
**TYPEALIAS**
# `Scene`
`Scene` is an array of windows.

View File

@ -0,0 +1,5 @@
**TYPEALIAS**
# `SceneBuilder`
A builder for the `Scene`

View File

@ -0,0 +1,5 @@
**TYPEALIAS**
# `ViewBuilder`
A builder for the `Body`.

BIN
Icons/AdwaitaIcon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

BIN
Icons/AdwaitaIcon.pxd Normal file

Binary file not shown.

BIN
Icons/GitHubBanner.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

BIN
Icons/GitHubBanner.pxd Normal file

Binary file not shown.

BIN
Icons/Screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

675
LICENSE.md Normal file
View File

@ -0,0 +1,675 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

5
Makefile Normal file
View File

@ -0,0 +1,5 @@
docs:
@sourcedocs generate --min-acl private -r --spm-module Adwaita
swiftlint:
@swiftlint --autocorrect

34
Package.swift Normal file
View File

@ -0,0 +1,34 @@
// swift-tools-version: 5.8
//
// Package.swift
// Adwaita
//
// Created by david-swift on 08.06.23.
//
import PackageDescription
/// The Adwaita package.
let package = Package(
name: "Adwaita",
products: [
.library(
name: "Adwaita",
targets: ["Adwaita"]
)
],
dependencies: [
.package(url: "https://github.com/david-swift/SwiftGui", branch: "main")
],
targets: [
.target(
name: "Adwaita",
dependencies: [.product(name: "GTUI", package: "swiftgui")]
),
.executableTarget(
name: "Counter",
dependencies: ["Adwaita"],
path: "Tests"
)
]
)

144
README.md Normal file
View File

@ -0,0 +1,144 @@
<p align="center">
<img width="256" alt="Adwaita Icon" src="Icons/AdwaitaIcon.png">
<h1 align="center">Adwaita</h1>
</p>
<p align="center">
<a href="https://david-swift.gitbook.io/adwaita/">
User Manual
</a>
·
<a href="https://github.com/david-swift/Adwaita">
GitHub
</a>
·
<a href="Documentation/Reference/README.md">
Contributor Docs
</a>
</p>
_Adwaita_ is a framework for creating user interfaces for GNOME with an API similar to SwiftUI.
The following code:
```swift
struct Example: View {
@State private var count = 0
var view: Body {
HeaderBar.start {
Button(icon: .default(icon: .goPrevious)) {
count -= 1
}
Button(icon: .default(icon: .goNext)) {
count += 1
}
}
Text("\(count)")
.padding(50)
}
}
```
Creates a simple counter view:
![Counter Example][image-1]
## Table of Contents
- [Goals][1]
- [Widgets][2]
- [Installation][3]
- [Usage][4]
- [Thanks][5]
## Goals
_Adwaita_s main goal is to provide an easy-to-use interface for creating GNOME apps. The back end should stay as simple as possible, while not limiting the possibilities there are with [Libadwaita][6] and [GTK][7].
If you want to use _Adwaita_ in a project, but there are widgets missing, open an [issue on GitHub][8].
## Widgets
| Name | Description | Widget |
| ---------- | ----------------------------------------------------------------- | ------------ |
| Button | A widget that triggers a function when being clicked. | GtkButton |
| EitherView | A widget that displays one of its child views based on a boolean. | GtkStack |
| HeaderBar | A widget for creating custom title bars for windows. | GtkHeaderBar |
| Text | A widget for displaying a small amount of text. | GtkLabel |
| VStack | A widget which arranges child widgets into a single column. | GtkBox |
### View Modifiers
| Syntax | Description |
| ---------------------------- | -------------------------------------------------------------------------------------- |
| `inspect(_:)` | Edit the underlying [GTUI][9] widget. |
| `padding(_:_:)` | Add empty space around a view. |
| `hexpand(_:)` | Enable or disable the horizontal expansion of a view. |
| `vexpand(_:)` | Enable or disable the vertical expansion of a view. |
| `frame(minWidth:minHeight:)` | Set the views minimal width or height. |
| `frame(maxSize:)` | Set the views maximal size. |
| `transition(_:)` | Assign a transition with the view that is used if it is a direct child of a HeaderBar. |
| `onUpdate(_:)` | Run a function every time a view gets updated. |
## Installation
### Dependencies
If you are using a Linux distribution, install `libadwaita-devel` or `libadwaita` (or something similar, based on the package manager) as well as `gtk4-devel`, `gtk4` or similar.
On macOS, follow these steps:
1. Install [Homebrew][10].
2. Install Libadwaita (and thereby GTK 4):
```
brew install libadwaita
```
### Swift Package
1. Open your Swift package in GNOME Builder, Xcode, or any other IDE.
2. Open the `Package.swift` file.
3. Into the `Package` initializer, under `dependencies`, paste:
```swift
.package(url: "https://github.com/david-swift/Adwaita", from: "0.1.0")
```
## Usage
* [Getting Started][11]
### Basics
* [Creating Views][12]
## Thanks
### Dependencies
- [SwiftGui][13] licensed under the [GPL-3.0 license][14]
### Other Thanks
- The [contributors][15]
- [SwiftLint][16] for checking whether code style conventions are violated
- The programming language [Swift][17]
- [SourceDocs][18] used for generating the [docs][19]
[1]: #Goals
[2]: #Widgets
[3]: #Installation
[4]: #Usage
[5]: #Thanks
[6]: https://gnome.pages.gitlab.gnome.org/libadwaita/doc/1-latest/index.html
[7]: https://docs.gtk.org/gtk4/
[8]: https://github.com/david-swift/Adwaita/issues
[9]: https://github.com/JCWasmx86/SwiftGui
[10]: https://brew.sh
[11]: user-manual/GettingStarted.md
[12]: user-manual/Basics/CreatingViews.md
[13]: https://github.com/JCWasmx86/SwiftGui
[14]: https://github.com/JCWasmx86/SwiftGui/blob/main/COPYING
[15]: Contributors.md
[16]: https://github.com/realm/SwiftLint
[17]: https://github.com/apple/swift
[18]: https://github.com/SourceDocs/SourceDocs
[19]: Documentation/Reference/README.md
[image-1]: Icons/Screenshot.png

12
SUMMARY.md Normal file
View File

@ -0,0 +1,12 @@
# Table of contents
* [Adwaita][1]
* [Getting Started][2]
## Basics
* [Creating Views][3]
[1]: README.md
[2]: user-manual/GettingStarted.md
[3]: user-manual/Basics/CreatingViews.md

View File

@ -0,0 +1,115 @@
//
// ArrayBuilder.swift
// Adwaita
//
// Created by david-swift on 05.08.23.
//
// Thanks to Jaden Geller for the GitHub Gist:
// "ArrayBuilder.swift"
// https://gist.github.com/JadenGeller/c375fc15ad5900a0ddac4ed8ba8307a9
//
import Foundation
/// The ``ArrayBuilder`` is a simple result builder that outputs an array of any type.
///
/// You can define any array using Swift's DSL:
/// ```swift
/// @ArrayBuilder<String> var string: [String] {
/// "Hello, "
/// if bool {
/// "world!"
/// } else {
/// "colibri!"
/// }
/// for x in 0...10 {
/// "\nIteration Number \(x)"
/// }
/// }
/// ```
@resultBuilder
public enum ArrayBuilder<Element> {
/// A component used in the ``ArrayBuilder``.
public enum Component {
/// An element as a component.
case element(_: Element)
/// An array of components as a component.
case components(_: [Self])
}
/// Build combined results from statement blocks.
/// - Parameter components: The components.
/// - Returns: The components in a component.
public static func buildBlock(_ elements: Component...) -> Component {
.components(elements)
}
/// Translate an element into an ``ArrayBuilder.Component``.
/// - Parameter element: The element to translate.
/// - Returns: A component created from the element.
public static func buildExpression(_ element: Element) -> Component {
.element(element)
}
/// Translate an array of elements into an ``ArrayBuilder.Component``.
/// - Parameter elements: The elements to translate.
/// - Returns: A component created from the element.
public static func buildExpression(_ elements: [Element]) -> Component {
var components: [Component] = []
for element in elements {
components.append(.element(element))
}
return .components(components)
}
/// Fetch a component.
/// - Parameter component: A component.
/// - Returns: The component.
public static func buildExpression(_ component: Component) -> Component {
component
}
/// Enables support for `if` statements without an `else`.
/// - Parameter component: An optional component.
/// - Returns: A nonoptional component.
public static func buildOptional(_ component: Component?) -> Component {
component ?? .components([])
}
/// Enables support for `if`-`else` and `switch` statements.
/// - Parameter component: A component.
/// - Returns: The component.
public static func buildEither(first component: Component) -> Component {
component
}
/// Enables support for `if`-`else` and `switch` statements.
/// - Parameter component: A component.
/// - Returns: The component.
public static func buildEither(second component: Component) -> Component {
component
}
/// Enables support for `for..in` loops.
/// - Parameter components: The components as a two dimensional array.
/// - Returns: The components as a one dimensional array.
public static func buildArray(_ components: [Component]) -> Component {
.components(components)
}
/// Convert a component to an array of elements.
/// - Parameter component: The component to convert.
/// - Returns: The generated array of elements.
public static func buildFinalResult(_ component: Component) -> [Element] {
switch component {
case let .element(element):
return [element]
case let .components(components):
return components.flatMap { buildFinalResult($0) }
}
}
}

View File

@ -0,0 +1,87 @@
//
// Binding.swift
// Adwaita
//
// Created by david-swift on 06.08.23.
//
/// A property wrapper for a property of a view that binds the property of the parent view.
///
/// ```swift
/// struct Grandparent: View {
///
/// @State private var state = false
///
/// var view: Body {
/// Parent(value: $state)
/// }
/// }
///
/// struct Parent: View {
///
/// @Binding var value: Bool
///
/// var view: Body {
/// Child(value: $value)
/// }
///
/// }
///
/// struct Child: View {
///
/// @Binding var value: Bool
///
/// var view: Body {
/// // ...
/// }
///
/// }
/// ```
@propertyWrapper
public struct Binding<Value> {
/// The value.
public var wrappedValue: Value {
get {
getValue()
}
nonmutating set {
setValue(newValue)
}
}
/// Get the value as a binding using the `$` prefix.
public var projectedValue: Binding<Value> {
.init {
wrappedValue
} set: { newValue in
wrappedValue = newValue
}
}
/// The closure for getting the value.
private let getValue: () -> Value
/// The closure for settings the value.
private let setValue: (Value) -> Void
/// Initialize a property that is bound from a parent view.
/// - Parameters:
/// - get: The closure for getting the value.
/// - set: The closure for setting the value.
public init(get: @escaping () -> Value, set: @escaping (Value) -> Void) {
self.getValue = get
self.setValue = set
}
/// Initialize a property that does not react to changes in the child view.
/// - Parameters:
/// - value: The constant value.
/// - Returns: The binding.
public static func constant(_ value: Value) -> Binding<Value> {
.init {
value
} set: { _ in
}
}
}

View File

@ -0,0 +1,75 @@
//
// State.swift
// Adwaita
//
// Created by david-swift on 06.08.23.
//
/// A property wrapper for properties in a view that should be stored throughout view updates.
@propertyWrapper
public struct State<Value>: StateProtocol {
/// Access the stored value. This updates the views when being changed.
public var wrappedValue: Value {
get {
storage.value
}
nonmutating set {
storage.value = newValue
Self.updateViews()
}
}
/// Get the value as a binding using the `$` prefix.
public var projectedValue: Binding<Value> {
.init {
wrappedValue
} set: { newValue in
self.wrappedValue = newValue
}
}
/// The stored value.
private let storage: Storage<Value>
/// The value with an erased type.
public var value: Any {
get {
wrappedValue
}
nonmutating set {
if let newValue = newValue as? Value {
storage.value = newValue
}
}
}
/// Initialize a property representing a state in the view.
/// - Parameters:
/// - wrappedValue: The wrapped value.
public init(wrappedValue: Value) {
storage = .init(value: wrappedValue)
}
/// A class storing the value.
class Storage<StoredValue> {
/// The stored value.
var value: StoredValue
/// Initialize the storage.
/// - Parameters:
/// - value: The value.
init(value: StoredValue) {
self.value = value
}
}
/// Update all of the views.
public static func updateViews() {
for handler in GTUIApp.updateHandlers {
handler()
}
}
}

View File

@ -0,0 +1,14 @@
//
// StateProtocol.swift
// Adwaita
//
// Created by david-swift on 09.09.23.
//
/// An interface for accessing `State` without specifying the generic type.
public protocol StateProtocol {
/// The type-erased value.
var value: Any { get nonmutating set }
}

View File

@ -0,0 +1,67 @@
//
// Array.swift
// Adwaita
//
// Created by david-swift on 06.08.23.
//
import GTUI
extension Array where Element == View {
/// Get a widget from a collection of views.
/// - Returns: A widget.
public func widget() -> Widget {
if count == 1, let widget = self[safe: 0]?.widget() {
return widget
} else {
return VStack { self }
}
}
/// Update a collection of views with a collection of view storages.
/// - Parameters:
/// - storage: The collection of view storages.
public func update(_ storage: [ViewStorage]) {
for (index, element) in enumerated() {
if let storage = storage[safe: index] {
element.widget().updateStorage(storage)
}
}
}
}
extension Array {
/// Accesses the element at the specified position safely.
/// - Parameters:
/// - index: The position of the element to access.
///
/// Access and set elements the safe way:
/// ```swift
/// var array = ["Hello", "World"]
/// print(array[safe: 2] ?? "Out of range")
/// ```
public subscript(safe index: Int?) -> Element? {
get {
if let index, checkIndex(index) {
return self[index]
}
return nil
}
set {
if let index, let value = newValue, checkIndex(index) {
self[index] = value
}
}
}
/// Check if a given index is valid for the array.
/// - Parameter index: The index to test.
/// - Returns: Return whether the index is valid or not.
private func checkIndex(_ index: Int) -> Bool {
index < count && index >= 0
}
}

View File

@ -0,0 +1,34 @@
//
// NativeWidgetPeer.swift
// Adwaita
//
// Created by david-swift on 05.08.23.
//
import GTUI
extension NativeWidgetPeer: Widget {
/// A `GTUI.NativeWidgetPeer` is static.
/// - Parameter storage: The view storage.
public func update(_ storage: ViewStorage) { }
/// A `GTUI.NativeWidgetPeer`'s container is itself.
/// - Returns: The view storage.
public func container() -> ViewStorage {
let bold = "\(modifier(code: 1))"
let yellow = 33
let warning = "\(modifier(code: yellow))\(bold)"
let reset = modifier(code: 0)
print("\(warning)warning: \(reset)discouraged use of GTUI widgets (here: \(bold)\(Self.self)\(reset)) in views")
return .init(self)
}
/// Get a modifier stirng.
/// - Parameter code: The modifier.
/// - Returns: The string.
private func modifier(code: Int) -> String {
"\u{001B}[\(code)m"
}
}

View File

@ -0,0 +1,15 @@
//
// String.swift
// Adwaita
//
// Created by david-swift on 09.09.23.
//
extension String {
/// A label for main content in a view storage.
static var mainContent: Self { "main" }
/// A label for the transition data in a GTUI widget's fields.
static var transition: Self { "transition" }
}

View File

@ -0,0 +1,58 @@
//
// App.swift
// Adwaita
//
// Created by david-swift on 05.08.23.
//
import GTUI
/// A structure conforming to `App` is the entry point of your app.
///
/// ```swift
/// @main
/// struct Test: App {
///
/// let id = "io.github.david-swift.TestApp"
/// var app: GTUIApp!
///
/// var scene: Scene {
/// WindowScene()
/// }
///
/// }
/// ```
///
public protocol App {
/// The app's application ID.
var id: String { get }
/// The app's windows.
@SceneBuilder var scene: Scene { get }
// swiftlint:disable implicitly_unwrapped_optional
/// The app.
var app: GTUIApp! { get set }
// swiftlint:enable implicitly_unwrapped_optional
/// An app has to have an `init()` initializer.
init()
}
extension App {
/// The application's entry point.
public static func main() {
var appInstance = self.init()
appInstance.app = GTUIApp(appInstance.id) { appInstance }
GTUIApp.updateHandlers.append {
for (windowIndex, window) in appInstance.scene.enumerated() {
if let stored = appInstance.app.sceneStorage[safe: windowIndex] {
window.widget().updateStorage(stored.view)
}
}
}
appInstance.app.run()
}
}

View File

@ -0,0 +1,42 @@
//
// GTUIApp.swift
// Adwaita
//
// Created by david-swift on 05.08.23.
//
import GTUI
/// The GTUI application.
public class GTUIApp: Application {
/// The handlers which are called when a state changes.
static var updateHandlers: [() -> Void] = []
/// The app's content.
var body: () -> App
/// The scenes that are displayed.
var sceneStorage: [WindowStorage] = []
/// Initialize the GTUI application.
/// - Parameters:
/// - id: The application id.
/// - body: The application's content.
init(_ id: String, body: @escaping () -> App) {
self.body = body
super.init(name: id)
}
/// The entry point of the application.
override public func onActivate() {
let body = body()
for windowScene in body.scene {
let window = GTUI.Window(app: self)
let child = windowScene.storage()
let view = child.view
window.setChild(view)
sceneStorage.append(.init(window: window, view: child))
window.show()
}
}
}

View File

@ -0,0 +1,65 @@
//
// View.swift
// Adwaita
//
// Created by david-swift on 05.08.23.
//
import GTUI
/// A structure conforming to `View` is referred to as a view.
/// It can be part of a body.
///
/// ```swift
/// struct Test: View {
///
/// var view: Body {
/// AnotherView()
/// }
///
/// }
/// ```
///
public protocol View {
/// The view's content.
@ViewBuilder var view: Body { get }
}
extension View {
/// Wrap the view into a widget.
/// - Returns: The widget.
public func widget() -> Widget {
if let peer = self as? Widget {
return peer
} else {
var state: [String: StateProtocol] = [:]
for property in Mirror(reflecting: self).children {
if let label = property.label, let value = property.value as? StateProtocol {
state[label] = value
}
}
return VStack(content: { view }, state: state)
}
}
/// Update a storage to a view.
/// - Parameter storage: The storage.
func updateStorage(_ storage: ViewStorage) {
if let widget = self as? Widget {
widget.update(storage)
}
}
/// Get a storage.
/// - Returns: The storage.
func storage() -> ViewStorage {
widget().container()
}
}
/// `Body` is an array of views.
public typealias Body = [View]

View File

@ -0,0 +1,89 @@
//
// ViewBuilder.swift
// Adwaita
//
// Created by david-swift on 05.08.23.
//
import Foundation
/// The ``ViewBuilder`` is a result builder for views.
@resultBuilder
public enum ViewBuilder {
/// A component used in the ``ArrayBuilder``.
public enum Component {
/// A view as a component.
case element(_: View)
/// An array of components as a component.
case components(_: [Self])
}
/// Build combined results from statement blocks.
/// - Parameter components: The components.
/// - Returns: The components in a component.
public static func buildBlock(_ elements: Component...) -> Component {
.components(elements)
}
/// Translate an element into a ``ViewBuilder.Component``.
/// - Parameter element: The element to translate.
/// - Returns: A component created from the element.
public static func buildExpression(_ element: View) -> Component {
.element(element)
}
/// Translate an array of elements into a ``ViewBuilder.Component``.
/// - Parameter elements: The elements to translate.
/// - Returns: A component created from the element.
public static func buildExpression(_ elements: [View]) -> Component {
var components: [Component] = []
for element in elements {
components.append(.element(element))
}
return .components(components)
}
/// Fetch a component.
/// - Parameter component: A component.
/// - Returns: The component.
public static func buildExpression(_ component: Component) -> Component {
component
}
/// Enables support for `if` statements without an `else`.
/// - Parameter component: An optional component.
/// - Returns: A nonoptional component.
public static func buildOptional(_ component: Component?) -> Component {
component ?? .components([])
}
/// Enables support for `if`-`else` and `switch` statements.
/// - Parameter component: A component.
/// - Returns: The component.
public static func buildEither(first component: Component) -> Component {
.element(EitherView(true, { buildFinalResult(component) }, else: nil))
}
/// Enables support for `if`-`else` and `switch` statements.
/// - Parameter component: A component.
/// - Returns: The component.
public static func buildEither(second component: Component) -> Component {
.element(EitherView(false, nil) { buildFinalResult(component) })
}
/// Convert a component to an array of elements.
/// - Parameter component: The component to convert.
/// - Returns: The generated array of elements.
public static func buildFinalResult(_ component: Component) -> [View] {
switch component {
case let .element(element):
return [element]
case let .components(components):
return components.flatMap { buildFinalResult($0) }
}
}
}

View File

@ -0,0 +1,35 @@
//
// ViewStorage.swift
// Adwaita
//
// Created by david-swift on 31.08.23.
//
import GTUI
/// Store a rendered view in a view storage.
public class ViewStorage {
/// The GTUI widget.
public var view: NativeWidgetPeer
/// The view's content.
public var content: [String: [ViewStorage]]
/// The view's state (used in `VStack`).
public var state: [String: StateProtocol]
/// Initialize a view storage.
/// - Parameters:
/// - view: The GTUI widget.
/// - content: The view's content.
/// - state: The view's state.
public init(
_ view: NativeWidgetPeer,
content: [String: [ViewStorage]] = [:],
state: [String: StateProtocol] = [:]
) {
self.view = view
self.content = content
self.state = state
}
}

View File

@ -0,0 +1,26 @@
//
// Widget.swift
// Adwaita
//
// Created by david-swift on 16.08.23.
//
import GTUI
/// A widget is a view that know about its GTUI widget.
public protocol Widget: View {
/// The view storage.
func container() -> ViewStorage
/// Update the stored content.
/// - Parameter storage: The storage to update.
func update(_ storage: ViewStorage)
}
extension Widget {
/// A widget's view is empty.
public var view: Body { [] }
}

View File

@ -0,0 +1,16 @@
//
// WindowScene.swift
// Adwaita
//
// Created by david-swift on 05.08.23.
//
import GTUI
/// A structure conforming to `WindowScene` can be added to an app's `scene`.
public protocol WindowScene: View { }
/// `Scene` is an array of windows.
public typealias Scene = [WindowScene]
/// A builder for the `Scene`
public typealias SceneBuilder = ArrayBuilder<WindowScene>

View File

@ -0,0 +1,27 @@
//
// SceneStorage.swift
// Adwaita
//
// Created by david-swift on 31.08.23.
//
import GTUI
/// A storage for an app's window.
class WindowStorage {
/// The GTUI window.
var window: Window
/// The content's storage.
var view: ViewStorage
/// Initialize a window storage.
/// - Parameters:
/// - window: The GTUI window.
/// - view: The content's storage.
init(window: Window, view: ViewStorage) {
self.window = window
self.view = view
}
}

View File

@ -0,0 +1,70 @@
//
// Button.swift
// Adwaita
//
// Created by david-swift on 10.09.23.
//
import GTUI
/// A button widget.
public struct Button: Widget {
/// The button's label.
var label: String?
/// The button's icon.
var icon: Icon?
/// The button's action handler.
var handler: () -> Void
// swiftlint:disable function_default_parameter_at_end
/// Initialize a button.
/// - Parameters:
/// - label: The button's label.
/// - icon: The button's icon.
/// - handler: The button's action handler.
public init(_ label: String? = nil, icon: Icon, handler: @escaping () -> Void) {
self.label = label
self.icon = icon
self.handler = handler
}
// swiftlint:enable function_default_parameter_at_end
/// Initialize a button.
/// - Parameters:
/// - label: The buttons label.
/// - handler: The button's action handler.
public init(_ label: String, handler: @escaping () -> Void) {
self.label = label
self.handler = handler
}
/// Update a button's view storage.
/// - Parameter storage: The view storage.
public func update(_ storage: ViewStorage) {
if let button = storage.view as? GTUI.Button {
let content = button.getContent()
if let label {
if icon == nil {
button.setLabel(label)
} else {
content?.setLabel(label)
}
}
if let icon {
content?.setIcon(icon)
}
}
}
/// Get a button's view storage.
/// - Returns: The button's view storage.
public func container() -> ViewStorage {
if let icon {
return .init(GTUI.Button(label, icon: icon).handler(handler))
} else {
return .init(GTUI.Button(label ?? .init()).handler(handler))
}
}
}

View File

@ -0,0 +1,103 @@
//
// EitherView.swift
// Adwaita
//
// Created by david-swift on 22.08.23.
//
import GTUI
/// An equivalent to GtkStack for two views.
public struct EitherView: Widget {
/// The view that is displayed when `isTrue` is true.
var trueView: Body?
/// The view that is displayed when `isTrue` is false.
var falseView: Body?
/// The state.
var isTrue: Bool
/// Initialize an `EitherView`.
/// - Parameters:
/// - isTrue: The state.
/// - _: The view that is presented if `isTrue` is true.
/// - else: The view that is presented if `isTrue` is false.
public init(
_ isTrue: Bool,
@ViewBuilder _ trueView: @escaping () -> Body,
@ViewBuilder else falseView: @escaping () -> Body
) {
self.init(isTrue, .some(trueView), else: .some(falseView))
}
/// Initialize an `EitherView`.
/// - Parameters:
/// - isTrue: The state.
/// - trueView: The view that is presented if `isTrue` is true.
/// - falseView: The view that is presented if `isTrue` is false.
init(_ isTrue: Bool, _ trueView: (() -> Body)? = nil, else falseView: (() -> Body)? = nil) {
self.trueView = trueView?()
self.falseView = falseView?()
self.isTrue = isTrue
}
/// Update an `EitherView`'s storage.
/// - Parameter storage: The view storage.
public func update(_ storage: ViewStorage) {
let stack = storage.view as? Stack
updateContent(storage, state: true, stack: stack)
updateContent(storage, state: false, stack: stack)
if isTrue, let trueView = storage.content["\(true)"]?.last?.view {
setVisible(stack, view: trueView)
} else if !isTrue, let falseView = storage.content["\(false)"]?.last?.view {
setVisible(stack, view: falseView)
}
}
/// Update the content of a view in the view storage.
/// - Parameters:
/// - storage: The view storage.
/// - state: Whether it is the true or false view.
/// - stack: The stack.
private func updateContent(_ storage: ViewStorage, state: Bool, stack: Stack?) {
let activeView = (state ? trueView : falseView)?.widget()
if let view = storage.content["\(state)"]?[safe: 0] {
activeView?.updateStorage(view)
} else if let view = activeView?.storage() {
_ = stack?.append(view.view)
storage.content["\(state)"] = [view]
}
}
/// Set the visible content page.
/// - Parameters:
/// - stack: The stack.
/// - view: The visible view.
private func setVisible(_ stack: Stack?, view: NativeWidgetPeer) {
stack?.setVisible(view, transition: view.fields[.transition] as? Transition)
}
/// Get a GtkStack view storage.
/// - Returns: The view storage.
public func container() -> ViewStorage {
let stack = Stack()
var content: [String: [ViewStorage]] = [:]
if let trueView {
let view = trueView.widget().storage()
_ = stack.append(view.view)
content["\(true)"] = [view]
}
if let falseView {
let view = falseView.widget().storage()
_ = stack.append(view.view)
content["\(false)"] = [view]
}
if isTrue, let trueView = content["\(true)"]?.last?.view {
stack.setVisible(trueView)
} else if let falseView = content["\(false)"]?.last?.view {
stack.setVisible(falseView)
}
return .init(stack, content: content)
}
}

View File

@ -0,0 +1,72 @@
//
// HeaderBar.swift
// Adwaita
//
// Created by david-swift on 23.08.23.
//
import GTUI
/// A header bar widget.
public struct HeaderBar: Widget {
/// The start content of the header bar.
var start: Body
/// The end content of the header bar.
var end: Body
/// The start content's id.
let startID = "start"
/// The end content's id.
let endID = "end"
/// Initialize a header bar.
/// - Parameters:
/// - start: The start content.
/// - end: The end content.
public init(@ViewBuilder start: () -> Body, @ViewBuilder end: () -> Body) {
self.start = start()
self.end = end()
}
/// Initialize a header bar with only views at the start.
/// - Parameter start: The views.
/// - Returns: The header bar.
public static func start(@ViewBuilder start: () -> Body) -> Self {
.init(start: start) { }
}
/// Initialize a header bar with only views at the end.
/// - Parameter start: The views.
/// - Returns: The header bar.
public static func end(@ViewBuilder end: () -> Body) -> Self {
.init(start: { }, end: end)
}
/// Update a header bar's view storage.
/// - Parameter storage: The view storage.
public func update(_ storage: ViewStorage) {
start.update(storage.content[startID] ?? [])
end.update(storage.content[endID] ?? [])
}
/// Get the container for a header bar.
/// - Returns: The view storage.
public func container() -> ViewStorage {
let bar: GTUI.HeaderBar = .init()
var startContent: [ViewStorage] = []
var endContent: [ViewStorage] = []
for element in start {
let element = element.storage()
_ = bar.packStart(element.view)
startContent.append(element)
}
for element in end {
let element = element.storage()
_ = bar.packEnd(element.view)
endContent.append(element)
}
return .init(bar, content: [startID: startContent, endID: endContent])
}
}

View File

@ -0,0 +1,89 @@
//
// InspectorWrapper.swift
// Adwaita
//
// Created by david-swift on 10.09.23.
//
import GTUI
/// A widget which executes a custom code on the GTUI widget when being created.
struct InspectorWrapper: Widget {
/// The custom code to edit the widget.
var modify: (NativeWidgetPeer?) -> Void
/// The wrapped view.
var content: View
/// Get the content's container.
/// - Returns: The content's container.
func container() -> ViewStorage {
let storage = content.storage()
modify(storage.view)
return storage
}
/// Update the content.
/// - Parameter storage: The content's storage.
func update(_ storage: ViewStorage) {
content.updateStorage(storage)
}
}
extension View {
/// Modify a GTUI widget before being displayed.
/// - Parameter modify: Modify the widget.
/// - Returns: A view.
public func inspect(_ modify: @escaping (NativeWidgetPeer?) -> Void) -> View {
InspectorWrapper(modify: modify, content: self)
}
/// Add padding around a view.
/// - Parameters:
/// - padding: The size of the padding.
/// - edges: The edges which are affected by the padding.
/// - Returns: A view.
public func padding(_ padding: Int = 10, _ edges: Set<Edge> = .all) -> View {
inspect { _ = $0?.padding(padding, edges) }
}
/// Enable or disable the horizontal expansion.
/// - Parameter enabled: Whether it is enabled or disabled.
/// - Returns: A view.
public func hexpand(_ enabled: Bool = true) -> View {
inspect { _ = $0?.hexpand() }
}
/// Enable or disable the vertical expansion.
/// - Parameter enabled: Whether it is enabled or disabled.
/// - Returns: A view.
public func vexpand(_ enabled: Bool = true) -> View {
inspect { _ = $0?.vexpand() }
}
/// Set the view's minimal width or height.
/// - Parameters:
/// - minWidth: The minimal width.
/// - minHeight: The minimal height.
/// - Returns: A view.
public func frame(minWidth: Int? = nil, minHeight: Int? = nil) -> View {
inspect { _ = $0?.frame(minWidth: minWidth, minHeight: minHeight) }
}
/// Set the view's maximal size.
/// - Parameter maxSize: The maximal size.
/// - Returns: A view.
public func frame(maxSize: Int? = nil) -> View {
inspect { _ = $0?.frame(maxSize: maxSize) }
}
/// Set the view's transition.
/// - Parameter transition: The transition.
/// - Returns: A view.
public func transition(_ transition: Transition) -> View {
inspect { $0?.fields[.transition] = transition }
}
}

View File

@ -0,0 +1,43 @@
//
// UpdateObserver.swift
// Adwaita
//
// Created by david-swift on 10.09.23.
//
import GTUI
/// A widget which executes a custom code when being updated.
struct UpdateObserver: Widget {
/// The function.
var onUpdate: () -> Void
/// The content.
var content: View
/// Get the content's container.
/// - Returns: The content's container.
func container() -> ViewStorage {
onUpdate()
return content.storage()
}
/// Update the content.
/// - Parameter storage: The content's storage.
func update(_ storage: ViewStorage) {
onUpdate()
content.updateStorage(storage)
}
}
extension View {
/// Run a function when the view gets an update.
/// - Parameter onUpdate: The function.
/// - Returns: A view.
public func onUpdate(_ onUpdate: @escaping () -> Void) -> View {
UpdateObserver(onUpdate: onUpdate, content: self)
}
}

View File

@ -0,0 +1,36 @@
//
// HeaderBar.swift
// Adwaita
//
// Created by david-swift on 23.08.23.
//
import GTUI
/// A text widget.
public struct Text: Widget {
/// The content.
var text: String
/// Initialize a text widget.
/// - Parameter text: The content.
public init(_ text: String) {
self.text = text
}
/// Update the view storage of the text widget.
/// - Parameter storage: The view storage.
public func update(_ storage: ViewStorage) {
if let label = storage.view as? MarkupLabel {
label.setText(text)
}
}
/// Get the container of the text widget.
/// - Returns: The view storage.
public func container() -> ViewStorage {
.init(MarkupLabel(self.text))
}
}

View File

@ -0,0 +1,57 @@
//
// EitherView.swift
// Adwaita
//
// Created by david-swift on 23.08.23.
//
import GTUI
/// A GtkBox equivalent.
public struct VStack: Widget {
/// The content.
var content: () -> Body
/// The state information (from properties with the `State` wrapper).
var state: [String: StateProtocol] = [:]
/// Initialize a `VStack`.
/// - Parameter content: The view content.
public init(@ViewBuilder content: @escaping () -> Body) {
self.content = content
}
/// Initialize a `VStack`.
/// - Parameters:
/// - content: The view content.
/// - state: The state information.
init(content: @escaping () -> Body, state: [String: StateProtocol]) {
self.content = content
self.state = state
}
/// Update a view storage.
/// - Parameter storage: The view storage.
public func update(_ storage: ViewStorage) {
for property in state {
if let value = storage.state[property.key]?.value {
property.value.value = value
}
}
content().update(storage.content[.mainContent] ?? [])
}
/// Get a view storage.
/// - Returns: The view storage.
public func container() -> ViewStorage {
let box: Box = .init(horizontal: false)
var content: [ViewStorage] = []
for element in self.content() {
let widget = element.storage()
_ = box.append(widget.view)
content.append(widget)
}
return .init(box, content: [.mainContent: content], state: state)
}
}

60
Tests/main.swift Normal file
View File

@ -0,0 +1,60 @@
//
// main.swift
// Adwaita
//
// Created by david-swift on 05.08.23.
//
// swiftlint:disable missing_docs implicitly_unwrapped_optional no_magic_numbers
import Adwaita
@main
struct Counter: App {
let id = "io.github.david-swift.Counter"
var app: GTUIApp!
var scene: Scene {
CounterWindow()
}
}
struct CounterWindow: WindowScene {
@State private var count = 0
var view: Body {
HeaderBar.start {
Button(icon: .default(icon: .goPrevious)) {
count -= 1
}
Button(icon: .default(icon: .goNext)) {
count += 1
}
}
description
}
@ViewBuilder private var description: Body {
VStack {
switch count {
case 1:
Text("One")
.transition(.slideUp)
case 0:
Text("Zero")
default:
Text("Hello, world, \(count)!")
}
}
.padding(50)
.onUpdate {
print(count)
}
}
}
// swiftlint:enable missing_docs implicitly_unwrapped_optional no_magic_numbers

View File

@ -0,0 +1,62 @@
# Creating Views
This is a beginner tutorial. We will create a simple “Hello, world!" app using _Adwaita_.
## Create the Swift Package
1. Open your terminal client and navigate to a directory you want to create the package in (e.g. `~/Documents/`).
2. Create a new folder for the package using `mkdir HelloWorld`.
3. Enter the newly created folder using `cd HelloWorld`.
4. Run `swift package init —type executable` for creating a new Swift package.
5. Open the Swift package. If you are using GNOME Builder, click on `Select a Folder…` in the view that appears after opening Builder and open the `HelloWorld` folder.
## Add the Dependency
1. Open the `Package.swift` file.
2. Add the following line of code after `name: “HelloWorld”,`:
```
dependencies: [.package(url: “https://github.com/david-swift/Adwaita”, from: “0.1.0”)],
```
## Create the App
1. Navigate to `Sources/main.swift`.
2. An app that uses the _Adwaita_ framework has a structure that conforms to the `App` protocol. The `scene` property returns one or more windows which provide content for display. An `@main` attribute marks it as the entry point of the app.
Replace `print(“Hello, world!”)` by your first app. We will later define `HelloWindow`:
```swift
@main
struct HelloWorld: App {
let id = "io.github.david-swift.HelloWorld"
var app: GTUIApp!
var scene: Scene {
HelloWindow()
}
}
```
## Create a View
1. Now, we will define `HelloWindow`. `HelloWindow` is a view, that means it conforms to the `View` protocol. As it additionally is a window, well make it conform to the `WindowScene` which automatically adds conformance to `View`.
```swift
struct HelloWindow: WindowScene {
var view: Body {
Text(“Hello, world!")
.padding()
}
}
```
2. Run the executable Swift package (in GNOME Builder, press the play button, on the command line, use `swift run`).
You can see that one important component of a window in GNOME is missing: The header bar.
3. If you add another view inside of the `view` property of `HelloWindow`, the views get aligned vertically:
```swift
struct HelloWindow: WindowScene {
var view: Body {
HeaderBar.empty()
Text(“Hello, world!")
.padding()
}
}
```

View File

@ -0,0 +1,19 @@
# Getting Started
Before you can start using _Adwaita_, youll need to setup some dependencies.
## macOS
1. Install [Homebrew][1].
2. Install Libadwaita (and thereby GTK 4):
```
brew install libadwaita
```
## Linux
Install `libadwaita-devel` or `libadwaita` (or something similar, based on the package manager) as well as `gtk4-devel`, `gtk4` or similar.
## Development
Subtasks is an open source project. Visit the [GitHub repository][2] for bug reports, feature requests, pull requests and more information.
[1]: https://brew.sh
[2]: https://github.com/david-swift/Subtasks-macOS