### ----------------------------------------------------
### -- Gnome::Gtk3
### -- Licenses: Artistic-2.0
### -- Authors: Marcel Timmerman
### -- File: Design-docs/Design.md
### ----------------------------------------------------
### -- Chunk 1 of 2
[toc]

# Nice to know (Lizmat's blog)

Robert Alen Zimmerman: Bob Dylan
Farrokh Bulsara: Freddy Mercury
Stefani Germanotta: Lady Gaga

Anna Bullock: Tina Turner


## rename files
rename -o .pm6 .rakumod *.pm6
rename -o .t .rakutest *.t

# Command line
Recognized options by GTK
See https://www.systutorials.com/docs/linux/man/7-gtk-options/

# Circular dependencies
* Solved by using `require`. This will compile imported modules at a later moment.
* It also does not have to be two-sided, i.e. not in both referring modules.
* As a side effect, I think this late binding is useful when a routine is not needed much and therefore not always need to import a module. Used in Gdk Visual which is referenced by Screen to get visuals. In this case, a `try` is not needed because the module exists.
  ```
  method get-screen ( --> Any ) {
    require ::('Gnome::Gdk3::Screen');
    ::('Gnome::Gdk3::Screen').new(
      :native-object(gdk_visual_get_screen(self._get-native-object-no-reffing))
    )
  }
  ```

# Stack info
```
say Backtrace.new.nice;
```

# Catching exeptions
in callbacks the errors sometime fail to throw properly so insert next code to
trap it.
```
CATCH { default { .message.note; .backtrace.concise.note } }
```

```
CONTROL { when CX::Warn {  note .gist; .resume; } }
```
# Web site start

```
bundle exec jekyll serve
```
## Web site config
```plantuml
scale 0.8
```

# Replace text in atom (with regex and case sensitive)
## Replace 'returns' for '-->'
search: `\)\s+returns\s+([A-Za-z0-9_\[\]-]+)`
replace `--> $1 )`

## Replace Since version messages
search: `\s*Since:\s+\d+\.\d+`
replace: ``

## Replace text bracketed function calls
search: `\[\[([\w\-\_\d]+)\]\]`
replace: `C<$1()>`

# Benchmarking result notes
* Always use normal arguments in the method which substitutes a native call search. Do not use slurpy arguments and flatten them in the call to the native sub.
* Call subs directly when there are no arguments or arguments that do not need some conversion like `Str` or `Int`. Also, the call is made on a subroutine of a leaf class. That means that casting is not necessary.
* Call sub via TopLevelSupportClass helper for casting using :sub-class('gtk-name').

# Installing on windows
## Testing on Appveyor
* Links
  * https://www.appveyor.com/docs/build-configuration/
  * https://www.gtk.org/docs/installations/windows
  * https://www.archlinux.org/pacman/pacman.8.html
* Using Visual studio 2019 image
  * has git.
  * has perl.
  * has MSYS2 installed in directory C:\msys64.
  * has curl.
* Search path with SafeDllSearchMode enabled (default)
  * The directory from which the application loaded.
  * The system directory. Use the GetSystemDirectory function to get the path of this directory.
  * The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
  * The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  * The current directory.
  * The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.
* Install GTK
  * `bash -lc "pacman -S --noconfirm mingw-w64-x86_64-gtk3"`
  * `bash -lc "pacman -S --noconfirm mingw-w64-x86_64-toolchain base-devel"`
* Install Raku
  * `choco install rakudostar`

# Native function signature subset

The subset GSourceFunc defined below
```
subset GSourceFunc of Callable where .signature ~~ :( gpointer $d --> gboolean );
```
makes the native sub signature easier to read
```
sub g_timeout_add (
  guint $interval, GSourceFunc $function, gpointer $data --> guint
) is native(&glib-lib)
  { * }
```
instead of
```
sub g_timeout_add (
  guint $interval, Callable $function ( gpointer $d --> gboolean ),
  gpointer $data --> guint
) is native(&glib-lib)
  { * }
```
Besides that, the name is kept the same as is used in the C-Source and documentation of Gnome.

# Native sub search
```
  SomeModule.some-sub()
  Gnome::GObject::Object.FALLBACK()
    translate some-sub -> some_sub
    SomeModule._fallback
      try some-sub or Gxyz_somemodule_some_sub => sub address
      callsame() if no address until one is found
    Substitute native objects for Raku objects in argument list
    Cast first argument when sub is found in another class

    Gnome::N::X.test-call()
```

# Example code to make downloadable archives

* Tar `tar cvfz todo-viewer.tgz --exclude '.precomp' todo-viewer/`
* Zip `zip -r todo-viewer.zip todo-viewer --exclude '*.precomp*'`

# Codes used in source modules to mark what is tested or not

The codes will show what is tested or not in the source code. The developer can than see what is tested and what is not. The code always start with `#T` followed with a letter for each type or action;
  * `L` module load
  * `M` method
  * `S` signal
  * `P` for properties
  * `E` for enums
  * `T` for structures
Then a colon ':' with a hex digit to show if it is tested or not;
  * 0 not tested
  * 1 tested in test script for this module
  * 2 tested elsewhere in test scripts for this package
  * 4 used elsewhere in test scripts or used programs
It is binary, so combinations are possible. 2 and 4 is not easy to find out. Then another colon followed with the name of the module, method, signal or type. E.g. `#TL:1:Gnome::Gtk3::Widget` or `#TM:0:gtk_widget_get_path`. When 2 and 4 are set, or combinations thereof, another column might follow to show the source. There might be more than one. E.g. `TM:3:gtk_color_chooser_add_palette:ColorChooserWidget`. There can be another column with a file- or package name when it is known where it is tested or used.

Absence of codes means that a particular item is not tested.

# Proto use with multi sub
Need a proto because otherwise the signature.parms will
become Mu in Gnome::N::test-call()
```
proto gtk_builder_add_from_file ( N-GObject, Str, |) { * }
multi sub gtk_builder_add_from_file (
  N-GObject $builder, Str $filename, Any $error
  --> uint32
) { ... }

multi ...
```

# Modules using interfaces

The GTK interfaces are implemented using a Raku role.

Interfaces sometimes specify signals. Define the use of it like so in the module using the interface;
```
method _xyz_interface_add_signal_types ( Str $class-name ) {
  self.add-signal-types( $class-name,
    :w0< … signal names … >
    :w1< … signal names … >,
    …
  );
}
```
and call this from the interface using class like so;
```
unit class xyz-module;
also does xyz-interface;
…

submethod BUILD ( *%options ) {
  # add signal info in the form of group<signal-name>.
  # groups are e.g. signal, event, nativeobject etc
  unless $signals-added {
    $signals-added = True;

    self.add-signal-types( $?CLASS.^name,
      :w0< … signal names … >,
      :w1< … signal names … >,
      …
    );

    self._xyz_interface_add_signal_types($?CLASS.^name);
  }
  …
```

```plantuml
'scale 0.7
skinparam packageStyle rectangle
skinparam stereotypeCBackgroundColor #80ffff
set namespaceSeparator ::
hide empty members

'class definitions
class Gnome::N::TopLevelClassSupport < Catch all class >

Interface Gnome::GObject::Signal <Interface>
class Gnome::GObject::Signal <<(R,#80ffff)>>

Interface Gnome::Gtk3::Buildable <Interface>
class Gnome::Gtk3::Buildable <<(R,#80ffff)>>


'class connections
Gnome::N::TopLevelClassSupport <|-- Gnome::GObject::Object
Gnome::GObject::Object.|> Gnome::GObject::Signal

Gnome::GObject::Object <|-- Gnome::GObject::InitialyUnowned
Gnome::GObject::InitialyUnowned <|-- Gnome::Gtk3::Widget
Gnome::Gtk3::Widget .|> Gnome::Gtk3::Buildable

```
Below is a tree of modules. The letters are explained at the bottom and are linked to the name of the interface module, e.g. `b` is for the `Buildable` class.

```
Tree of Gtk C structures                              Interface use
----------------------------------------------------- ------------------------
GObject                                               
├── GInitiallyUnowned
│   ├── GtkWidget                                     b
│   │   ├── GtkContainer                              b
│   │   │   ├── GtkBin                                b
│   │   │   │   ├── GtkWindow                         b
│   │   │   │   │   ├── GtkDialog                     b
│   │   │   │   │   │   ├── GtkAboutDialog            b
│   │   │   │   │   │   ├── GtkAppChooserDialog       b,ap
│   │   │   │   │   │   ├── GtkColorChooserDialog     b,cc
│   │   │   │   │   │   ├─✗ GtkColorSelectionDialog   b
│   │   │   │   │   │   ├── GtkFileChooserDialog      b,fic
│   │   │   │   │   │   ├── GtkFontChooserDialog      b,foc
│   │   │   │   │   │   ├─✗ GtkFontSelectionDialog    b
│   │   │   │   │   │   ├── GtkMessageDialog          b
│   │   │   │   │   │   ├── GtkPageSetupUnixDialog    b
│   │   │   │   │   │   ├── GtkPrintUnixDialog        b
│   │   │   │   │   │   ╰── GtkRecentChooserDialog    b,rc
│   │   │   │   │   ├── GtkApplicationWindow          b
│   │   │   │   │   ├── GtkAssistant                  b
│   │   │   │   │   ├── GtkOffscreenWindow            b
│   │   │   │   │   ├── GtkPlug                       b
│   │   │   │   │   ╰── GtkShortcutsWindow            b
│   │   │   │   ├── GtkActionBar                      b
│   │   │   │   ├─✗ GtkAlignment                      b
│   │   │   │   ├── GtkComboBox                       b,cl,ce
│   │   │   │   │   ├── GtkAppChooserButton           b,ap,cl,ce
│   │   │   │   │   ╰── GtkComboBoxText               b,cl,ce
│   │   │   │   ├── GtkFrame                          b
│   │   │   │   │   ╰── GtkAspectFrame                b
│   │   │   │   ├── GtkButton                         b,ac
│   │   │   │   │   ├── GtkToggleButton               b,ac
│   │   │   │   │   │   ├── GtkCheckButton            b,ac
│   │   │   │   │   │   │   ╰── GtkRadioButton        b,ac
│   │   │   │   │   │   ╰── GtkMenuButton             b,ac
│   │   │   │   │   ├── GtkColorButton                b,ac,cc
│   │   │   │   │   ├── GtkFontButton                 b,ac,foc
│   │   │   │   │   ├── GtkLinkButton                 b,ac
│   │   │   │   │   ├── GtkLockButton                 b,ac
│   │   │   │   │   ├── GtkModelButton                b,ac
│   │   │   │   │   ╰── GtkScaleButton                b,o,ac
│   │   │   │   │       ╰── GtkVolumeButton           b,o,ac
│   │   │   │   ├── GtkMenuItem                       b,ac
│   │   │   │   │   ├── GtkCheckMenuItem              b,ac
│   │   │   │   │   │   ╰── GtkRadioMenuItem          b,ac
│   │   │   │   │   ├─✗ GtkImageMenuItem              b,ac
│   │   │   │   │   ├── GtkSeparatorMenuItem          b,ac
│   │   │   │   │   ╰─✗ GtkTearoffMenuItem            b,ac
│   │   │   │   ├── GtkEventBox                       b
│   │   │   │   ├── GtkExpander                       b
│   │   │   │   ├── GtkFlowBoxChild                   b
│   │   │   │   ├── GtkHandleBox                      b
│   │   │   │   ├── GtkListBoxRow                     b,ac
│   │   │   │   ├── GtkToolItem                       b
│   │   │   │   │   ├── GtkToolButton                 b,ac
│   │   │   │   │   │   ├── GtkMenuToolButton         b,ac
│   │   │   │   │   │   ╰── GtkToggleToolButton       b,ac
│   │   │   │   │   │       ╰── GtkRadioToolButton    b,ac
│   │   │   │   │   ╰── GtkSeparatorToolItem          b
│   │   │   │   ├── GtkOverlay                        b
│   │   │   │   ├── GtkScrolledWindow                 b
│   │   │   │   │   ╰── GtkPlacesSidebar              b
│   │   │   │   ├── GtkPopover                        b
│   │   │   │   │   ╰── GtkPopoverMenu                b
│   │   │   │   ├── GtkRevealer                       b
│   │   │   │   ├── GtkSearchBar                      b
│   │   │   │   ├── GtkStackSidebar                   b
│   │   │   │   ╰── GtkViewport                       b,s
│   │   │   ├── GtkBox                                b,o
│   │   │   │   ├── GtkAppChooserWidget               b,o,ap
│   │   │   │   ├── GtkButtonBox                      b,o
│   │   │   │   │   ├─✗ GtkHButtonBox                 b,o
│   │   │   │   │   ╰─✗ GtkVButtonBox                 b,o
│   │   │   │   ├── GtkColorChooserWidget             b,o,cc
│   │   │   │   ├─✗ GtkColorSelection                 b,o
│   │   │   │   ├── GtkFileChooserButton              b,o,fic
│   │   │   │   ├── GtkFileChooserWidget              b,o,fic
│   │   │   │   ├── GtkFontChooserWidget              b,o,foc
│   │   │   │   ├─✗ GtkFontSelection                  b,o
│   │   │   │   ├─✗ GtkHBox                           b,o
│   │   │   │   ├── GtkInfoBar                        b,o
│   │   │   │   ├── GtkRecentChooserWidget            b,o,rc
│   │   │   │   ├── GtkShortcutsSection               b,o
│   │   │   │   ├── GtkShortcutsGroup                 b,o
│   │   │   │   ├── GtkShortcutsShortcut              b,o
│   │   │   │   ├── GtkStackSwitcher                  b,o
│   │   │   │   ├── GtkStatusbar                      b,o
│   │   │   │   ╰─✗ GtkVBox                           b,o
│   │   │   ├── GtkFixed                              b
│   │   │   ├── GtkFlowBox                            b,o
│   │   │   ├── GtkGrid                               b,o
│   │   │   ├── GtkHeaderBar                          b
│   │   │   ├── GtkPaned                              b,o
│   │   │   │   ├─✗ GtkHPaned                         b,o
│   │   │   │   ╰─✗ GtkVPaned                         b,o
│   │   │   ├── GtkIconView                           b,cl,s
│   │   │   ├── GtkLayout                             b,s
│   │   │   ├── GtkListBox                            b
│   │   │   ├── GtkMenuShell                          b
│   │   │   │   ├── GtkMenuBar                        b
│   │   │   │   ╰── GtkMenu                           b
│   │   │   │       ╰── GtkRecentChooserMenu          b,rc
│   │   │   ├── GtkNotebook                           b
│   │   │   ├── GtkSocket                             b
│   │   │   ├── GtkStack                              b
│   │   │   ├─✗ GtkTable                              b
│   │   │   ├── GtkTextView                           b,s
│   │   │   ├── GtkToolbar                            b,o,tsh
│   │   │   ├── GtkToolItemGroup                      b,tsh
│   │   │   ├── GtkToolPalette                        b,o,s
│   │   │   ╰── GtkTreeView                           b,s
│   │   ├─✗ GtkMisc                                   b
│   │   │   ├── GtkLabel                              b
│   │   │   │   ╰── GtkAccelLabel                     b
│   │   │   ├─✗ GtkArrow                              b
│   │   │   ╰── GtkImage                              b
│   │   ├── GtkCalendar                               b
│   │   ├── GtkCellView                               b,o,cl
│   │   ├── GtkDrawingArea                            b
│   │   ├── GtkEntry                                  b,ce,e
│   │   │   ├── GtkSearchEntry                        b,ce,e
│   │   │   ╰── GtkSpinButton                         b,o,ce,e
│   │   ├── GtkGLArea                                 b
│   │   ├── GtkRange                                  b,o
│   │   │   ├── GtkScale                              b,o
│   │   │   │   ├─✗ GtkHScale                         b,o
│   │   │   │   ╰─✗ GtkVScale                         b,o
│   │   │   ╰── GtkScrollbar                          b,o
│   │   │       ├─✗ GtkHScrollbar                     b,o
│   │   │       ╰─✗ GtkVScrollbar                     b,o
│   │   ├── GtkSeparator                              b,o
│   │   │   ├─✗ GtkHSeparator                         b,o
│   │   │   ╰─✗ GtkVSeparator                         b,o
│   │   ├─✗ GtkHSV                                    b
│   │   ├─✗ GtkInvisible                              b
│   │   ├── GtkProgressBar                            b,o
│   │   ├── GtkSpinner                                b
│   │   ├── GtkSwitch                                 b,ac
│   │   ╰── GtkLevelBar                               b,o
│   ├── GtkAdjustment
│   ├── GtkCellArea                                   b,cl
│   │   ╰── GtkCellAreaBox                            b,o,cl
│   ├── GtkCellRenderer                               
│   │   ├── GtkCellRendererText                       
│   │   │   ├── GtkCellRendererAccel                  
│   │   │   ├── GtkCellRendererCombo                  
│   │   │   ╰── GtkCellRendererSpin                   
│   │   ├── GtkCellRendererPixbuf                     
│   │   ├── GtkCellRendererProgress                   o
│   │   ├── GtkCellRendererSpinner                    
│   │   ╰── GtkCellRendererToggle                     
│   ├── GtkFileFilter                                 b
│   ├── GtkTreeViewColumn                             b,cl
│   ╰── GtkRecentFilter                               b
├── GtkAccelGroup
├── GtkAccelMap
├── AtkObject
│   ╰── GtkAccessible
├─✗ GtkAction                                         b
│   ├─✗ GtkToggleAction                               b
│   │   ╰─✗ GtkRadioAction                            b
│   ╰─✗ GtkRecentAction                               b,rc
├─✗ GtkActionGroup                                    b
├── GApplication                                      
│   ╰── GtkApplication                                
├── GtkBuilder                                        
├── GtkCellAreaContext
├── GtkClipboard
├── GtkCssProvider                                    sp
├── GtkEntryBuffer                                    
├── GtkEntryCompletion                                b,cl
├── GtkEventController
│   ├── GtkEventControllerKey
│   ├── GtkEventControllerMotion
│   ├── GtkEventControllerScroll
│   ├── GtkGesture
│   │   ├── GtkGestureSingle
│   │   │   ├── GtkGestureDrag
│   │   │   │   ╰── GtkGesturePan
│   │   │   ├── GtkGestureLongPress
│   │   │   ├── GtkGestureMultiPress
│   │   │   ├── GtkGestureStylus
│   │   │   ╰── GtkGestureSwipe
│   │   ├── GtkGestureRotate
│   │   ╰── GtkGestureZoom
│   ╰── GtkPadController
├── GtkIconFactory                                    b
├── GtkIconTheme
├── GtkIMContext
│   ├── GtkIMContextSimple
│   ╰── GtkIMMulticontext
├── GtkListStore                                      b,tm,tds,tdd,ts
├── GMountOperation                                   
│   ╰── GtkMountOperation                             
├── GEmblemedIcon                                     
│   ╰─✗ GtkNumerableIcon                              
├── GtkPageSetup
├── GtkPrinter
├── GtkPrintContext
├── GtkPrintJob
├── GtkPrintOperation                                 pop
├── GtkPrintSettings
├── GtkRcStyle
├── GtkRecentManager
├── GtkSettings                                       sp
├── GtkSizeGroup                                      b
├─✗ GtkStatusIcon                                     
├─✗ GtkStyle                                          
├── GtkStyleContext                                   
├── GtkTextBuffer                                     
├── GtkTextChildAnchor
├── GtkTextMark
├── GtkTextTag                                        
├── GtkTextTagTable                                   b
├─✗ GtkThemingEngine                                  
├── GtkTreeModelFilter                                tm,tds
├── GtkTreeModelSort                                  tm,tds,ts
├── GtkTreeSelection
├── GtkTreeStore                                      b,tm,tds,tdd,ts
├─✗ GtkUIManager                                      b
├── GtkWindowGroup
├── GtkTooltip
╰── GtkPrintBackend

GInterface                                            
├── GtkBuildable                                      b
├── GtkActionable                                     ac
├─✗ GtkActivatable                                    
├── GtkAppChooser                                     ap
├── GtkCellLayout                                     cl
├── GtkCellEditable                                   ce
├── GtkOrientable                                     o
├── GtkColorChooser                                   cc
├── GtkStyleProvider                                  sp
├── GtkEditable                                       e
├── GtkFileChooser                                    fic
├── GtkFontChooser                                    foc
├── GtkScrollable                                     s
├── GtkTreeModel                                      tm
├── GtkTreeDragSource                                 tds
├── GtkTreeDragDest                                   tdd
├── GtkTreeSortable                                   ts
├── GtkPrintOperationPreview                          pop
├── GtkRecentChooser                                  rc
╰── GtkToolShell                                      tsh
```


After plotting the dependencies on **GtkBuildable**, it looks as if the class can be inherited by the highest class where it is needed, such as **Widget** and all child widgets will then have the methods available of that interface. After plotting all interface modules in above chart, the conclusion taken above is correct.
Also the interface module will have a role type.

## What happens in Application

![](../docs/content-docs/reference/Gtk3/plantuml/Application.svg)

https://discourse.gnome.org/t/gio-application-commandline-does-trigger-activate-signal/2988
https://wiki.gnome.org/HowDoI/GtkApplication/CommandLine

* `local`; the current process is running in direct response to the invocation
* `remote`; some other process forwarded the commandline to this process.
<br/>

* start application (primary = local)
  * application initialize
  * register application
    * fires event `startup`
  * return user

* ~~add options and option groups using `g_application_add_main_option_entries()`~~

* run application
  * set arguments from `@ARGS`, argumentlist is not modified
  * create object `GApplicationCommandLine` from arguments
  * parse commandline arguments
    * fires event `handle-local-options`
      * ~~process options from VariantDict~~
      * returns 0 (=success) or > 0 (=failure) to stop or continue with -1
    * fires event `command-line`
      * if flag G_APPLICATION_HANDLES_COMMAND_LINE is set
      * after `handle-local-options` continues (-1)
      * if remote
        * process remote arguments
        * do tasks. can be something in the GUI, open file or whatever.
        * send message if needed
        * set exit code. unix success exit is 0.
        * clear remote arguments object. Secondary instance finishes when
          this is cleaned up, otherwise it is kep alive.
      * if local
        * process arguments
        * do tasks.
        * if ok
          * Initialize. Explicitly call `g_application_activate()` which fires event `activate`.
        * not ok
          * send message if needed
          * set exit code and exit.
  * implicitly call `g_application_activate()` when G_APPLICATION_HANDLES_COMMAND_LINE is not set.
    * fires event `activate`
* exit code is returned from `run()` and can be given to `exit()` to stop the application.


Experiments have shown that, when the `G_APPLICATION_HANDLES_COMMAND_LINE` flag is set, the `command-line` signal is fired after handling the `handle-local-options` event, which is according the documentation. The thing is that normally without this flag, the activation signal is fired and the GUI can be build. This is not happening after `command-line` is finished and returned. There are several reasons for that;

* The primary must be able to return to the commandline after processing its arguments and options when there are errors or when no other tasks need to be done.
* This happens also on behalf of the remote instance on the primary. The argument ~~leftovers~~ are sent to the primary and processed. The primary uses `.get-arguments()` to get them. A `.print()` or `.printerr()` displays messages in the proper instance. (methods are from **Gnome::Gio::ApplicationCommandLine**).
* The primary instance will be kept alive when the 'use count' is not zero. THis is accomplished using `.hold()`. This is not interesting, although the primary stays alive and responds to the secondary processes.
* The documentation also states that the use count increases after setting the main window. So calling `.activate()` will also fire the `activate` signal and the handler may start building the GUI and by setting the main window, increases the use count.


## Structure of modules, plan B

```plantuml
'skinparam packageStyle rectangle
skinparam stereotypeCBackgroundColor #80ffff
'set namespaceSeparator ::
hide empty members

scale 0.8

class TopLevelClassSupport < Catch all class > {
  has Any $!n-native-object
  has Bool $.is-valid = False

  has Int $!class-gtype
  has Str $!class-name
  has Str $!class-name-of-sub

  my Bool $gui-initialized = False

  new()

  BUILD()

  FALLBACK()
  _fallback()

  _get-native-object()
  set-native-object()

  {abstract} native-object-ref()
  {abstract} native-object-unref()
  clear-object()
  DESTROY()

  _set-class-info()
  _set-class-name-of-sub()
  _get-class-name-of-sub()
  get-class-gtype()
}

note left of TopLevelClassSupport
  <b>$!n-native-object</b> is where the native object
  is stored. It is used by the toplevel class and its
  descendent classes. The type is always the same as
  set by all classes inheriting from the same toplevel
  class.

  <b>$.is-valid</b> is a readable variable and is checked
  to see if $!n-native-object is valid.

  <b>$!class-gtype</b>, <b>$!class-name</b> and
  <b>$!class-name-of-sub</b> are used to keep track
  of native class types and names.

  '<b>$gui-initialized</b> is used to check on native
  'initialization. It is defined that it is global to all
  'of the TopLevelClassSupport classes.
  --
  'Method <b>new()</b> is defined to cleanup the native object
  'in case of an assignement like <b><i>$c .= new(...);</i></b>.
  'The native object, if any, must be cleared first.

  <b>BUILD()</b> must check for <b>$gui-initialized</b>
  and also handle the <b>:native-object</b> option

  <b>FALLBACK</b> is called when a method is not available
  in the classes. It starts a search for a native sub with
  the method name in the tree using <b>_fallback()</b>. The
  search starts at the lowest child _fallback() working up
  to the top level class.

  The search will end with this <b>_fallback()</b>.

  <b>_get-native-object()</b> and <b>set-native-object()</b>
  get and set the native object. They also handle
  referencing.
  '{abstract} native-object-ref()
  '{abstract} native-object-unref()
  'clear-object()
  '_set-class-info()
  '_set-class-name-of-sub()
  '_get-class-name-of-sub()
  'get-class-gtype()
end note


class SomeFooClassTop {
  BUILD()
  _fallback()
  native-object-ref()
  native-object-unref()
}

note left of SomeFooClassTop
  <b>BUILD()</b> handles this classes options
  to create a specialized native object. It
  uses <b>set-native-object()</b> to store it.

  <b>_fallback()</b> is passed through to search
  for native subs defined in this class. Use <b>callsame()</b>
  when no sub is found.

  <b>native-object-ref()</b> and <b>native-object-unref()</b>
  are implementations of the abstract methods of
  its parent.
end note

note left of SomeFooClass
  <b>BUILD()</b> and <b>set-native-object()</b> do the same
  as above.

  <b>_fallback()</b> does the same as in its parent
end note

class SomeFooClass {
  BUILD()
  _fallback()
}

class UserClass << (C, #00ffff) user class >> {
  new()
  BUILD()
}

note left of UserClass
  With the <b>new()</b> method, the user is able to inject
  options to control parent classes to create a native
  object on behalf of this user class. Later this
  classes <b>BUILD()</b> method can modify it.

  <b>BUILD()</b> is for processing the users object options
  and/or to modify the native object created by one of
  the parents
end note

interface SomeFooInterface < Interface >
Interface  SomeFooInterface<Interface>
class SomeFooInterface <<(R,#80ffff)>>

note top of SomeFooInterface
  There wil be no <b>new()</b>, <b>BUILD()</b>
  or any use of storage of native
  objects.

  <b>_interface()</b> has the same task
  as the <b>_fallback()</b> method in
  normal classes.
end note

'Connections of classes and interfaces

TopLevelClassSupport <|-- SomeFooClassTop
SomeFooClassTop <|-- SomeFooClass
SomeFooClass <|-- UserClass

'TopLevelInterfaceSupport <|-- SomeFooInterface
SomeFooClass .|> SomeFooInterface
```

## Definitions of interfaces and class inheritance

### Interfaces

**Interfaces** define a common contract. Such as an interface called IAnimal, where all animals share functions such as Eat(), Move(), Attack() etc. While all of them share the same functions, all or most of them have a different way (implementation) of achieving it. **Interfaces** are for **_can do_** or **_can be treated as_** type of relationships. In Raku this is called a role.

### Classes
**Abstract** ( as well as **concrete** ) classes are for **_is a_** kind of relationship. **Abstract or concrete classes** define a common implementation and optionally common contracts. For example a simple Calculator could qualify as an abstract class which implements all the basic logical and bitwise operators and then gets extended by ScientificCalculator, GraphicalCalculator and so on.

Look at these examples:

class Bird **_is an_** Animal **_can do_** Flight;
class Plane **_is a_** Vehicle **can do_** Flight, **_can be treated as_** AccountableAsset;
class Mosquito **_is an_** Animal **_can do_** Flight;
class Horse **_is an_** Animal;
class RaceHorse **_is a_** Horse **_can be treated as_** AccountableAsset;
class Pegasus **is a** Horse **_can do_** Flight;

Bird, Mosquito and Horse are Animals. They are related. They inherit common methods from Animal like eat(), metabolize() and reproduce(). Maybe they override these methods, adding a little extra to them, but they take advantage of the default behavior implemented in Animal like metabolizeGlucose().

Plane is not related to Bird, Mosquito or Horse.

Flight is implemented by dissimilar, unrelated classes, like Bird and Plane.

AccountableAsset is also implemented by dissimilar, unrelated classes, like Plane and RaceHorse.

Horse doesn't implement Flight.

As you can see classes (abstract or concrete) helps you build a hierarchies, letting you inhering code from the upper levels to the lower levels of the hierarchy. In theory the lower you are in the hierarchy, the more specialized your behavior is, but you don't have to worry about a lot of things that are already taken care of.

Interfaces, in the other hand, create no hierarchy, but they can help homogenize certain behaviors across hierarchies so you can abstract them from the hierarchy in certain contexts.

For example you can have a program sum the value of a group of AccountableAssets regardless of their being RaceHorses or Planes.


# Creation subroutines
A widget, e.g. Button is created using the BUILD Api of perl like so
```
my Gnome::Gtk3::Button $b .= new(:label('start'));
```
Under the hood it calls `gtk_button_new_with_label('start')`. These subs cannot be called directly if one wants to do that, because the subs are searched for and to do that the class must be instantiated.

```
my Gnome::Gtk3::Button $b .= new;
$b .= new(:widget($b.new-with-label('start'));
```
This is messy. so to do it directly, these subs should be exported and then can be used like; (note that a full name must be used now!)
```
my Gnome::Gtk3::Button $b .= new(:native-object(gtk_button_new_with_label('start')));
```
This is just an example how it could be done, however, implementations will provide the proper `.new()` with the proper options.


# Variable argument lists
This is work of Elizabeth (lizmat)

```
# mail example variable lists
# Vittore Scolari
sub pera-int-f(Str $format, *@args) {
    state $ptr = cglobal(Str, "printf", Pointer);
    my $signature = Signature.new(
        params => (
            Parameter.new(type => Str),
            |(@args.map: { Parameter.new(type => .WHAT) })
        ),

        returns => int32
    );

    my &f = nativecast($signature