--
-- demo\rosetta\SierpinskyPentagon.exw
-- ===================================
--
with javascript_semantics
include pGUI.e

Ihandle dlg, canvas
cdCanvas cddbuffer

constant title = "Sierpinski Pentagon",
         scale_factor = 1/(2+cos(2*PI/5)*2),
         side_factor = 1+cos(2*PI/5)*2,
         angles = sq_mul(2*PI/5,tagset(7,3)),
         cosangles = apply(angles,cos),
         sinangles = apply(angles,sin)

integer level = 3

procedure drawPentagon(atom x, y, side, w, h, integer depth)
    if depth=0 then
        cdCanvasBegin(cddbuffer,CD_FILL)
        for i=1 to 5 do
            x += cosangles[i] * side
            y -= sinangles[i] * side
            cdCanvasVertex(cddbuffer, w+x, h-y)
        end for
        cdCanvasEnd(cddbuffer)
    else
        side *= scale_factor
        atom distance = side*side_factor
        for i=1 to 5 do
            x += cosangles[i] * distance
            y -= sinangles[i] * distance
            drawPentagon(x, y, side, w, h, depth-1)
        end for
    end if
end procedure

function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/)
    integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE")
    atom hw = min(w/2,h/2),
         margin = 20,
         radius = hw - 2*margin,
         side = radius * sin(PI/5) * 2
    cdCanvasActivate(cddbuffer)
    cdCanvasClear(cddbuffer)
    drawPentagon(hw, 3*margin, side, w/2-radius-2*margin, h, level)
    cdCanvasFlush(cddbuffer)
    return IUP_DEFAULT
end function

function map_cb(Ihandle ih)
    cdCanvas cdcanvas = cdCreateCanvas(CD_IUP, ih)
    cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
    cdCanvasSetBackground(cddbuffer, CD_PARCHMENT)
    cdCanvasSetForeground(cddbuffer, CD_BLUE)
    return IUP_DEFAULT
end function

procedure set_dlg_title()
    IupSetStrAttribute(dlg, "TITLE", "%s (level %d)",{title,level})
end procedure

function key_cb(Ihandle /*ih*/, atom c)
    if c=K_ESC then return IUP_CLOSE end if
    if find(c,"+-") then
        if c='+' then
            level = min(5,level+1)
        elsif c='-' then
            level = max(0,level-1)
        end if
        set_dlg_title()
        IupRedraw(canvas)
    end if
    return IUP_CONTINUE
end function

procedure main()
    IupOpen()
    canvas = IupCanvas("RASTERSIZE=640x640")
    IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
                             "ACTION", Icallback("redraw_cb")})
    dlg = IupDialog(canvas)
    IupSetCallback(dlg, "KEY_CB", Icallback("key_cb"))
    set_dlg_title()
    IupShow(dlg)
    IupSetAttribute(canvas, "RASTERSIZE", NULL)
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure

main()


float s_angle, scale, margin = 25, total = 4;
float p_size = 700;
float radius = p_size/2-2*margin;
float side = radius * sin(PI/5)*2;

void setup() {
  float temp = width/2;
  size(590, 590);
  background(0, 0, 200);
  stroke(255);
  s_angle = 72*PI/180;
  scale = 1/(2+cos(s_angle)*2);
  for (int i = 0; i < total; i++) {
    background(0, 0, 200);
    drawPentagon(width/2, (height-p_size)/2 + 3*margin, side, total);
  }
}

void drawPentagon(float x, float y, float side, float depth) {
  float angle = 3*s_angle;
  if (depth == 0) {
    for (int i = 0; i < 5; i++) {
      float px = x;
      float py = y;
      x = x+cos(angle)*side;
      y = y-sin(angle)*side;
      line(x, y, px, py);
      angle += s_angle;
    }
  } else {
    side *= scale;
    float distance = side+side*cos(s_angle)*2;
    for (int j = 0; j < 5; j++) {
      x = x+cos(angle)*distance;
      y = y-sin(angle)*distance;
      drawPentagon(x, y, side, depth-1);
      angle += s_angle;
    }
  }
}


main:-
    write_sierpinski_pentagon('sierpinski_pentagon.svg', 600, 5).

write_sierpinski_pentagon(File, Size, Order):-
    open(File, write, Stream),
    format(Stream, "<svg xmlns='http://www.w3.org/2000/svg' width='~d' height='~d'>\n",
       [Size, Size]),
    write(Stream, "<rect width='100%' height='100%' fill='white'/>\n"),
    Margin = 5,
    Radius is Size/2 - 2 * Margin,
    Side is Radius * sin(pi/5) * 2,
    Height is Side * (sin(pi/5) + sin(2 * pi/5)),
    X is Size/2,
    Y is (Size - Height)/2,
    Scale_factor is 1/(2 + cos(2 * pi/5) * 2),
    sierpinski_pentagon(Stream, X, Y, Scale_factor, Side, Order),
    write(Stream, "</svg>\n"),
    close(Stream).

sierpinski_pentagon(Stream, X, Y, _, Side, 1):-
    !,
    write(Stream, "<polygon stroke-width='1' stroke='black' fill='blue' points='"),
    format(Stream, '~g,~g', [X, Y]),
    Angle is 6 * pi/5,
    write_pentagon_points(Stream, Side, Angle, X, Y, 5),
    write(Stream, "'/>\n").
sierpinski_pentagon(Stream, X, Y, Scale_factor, Side, N):-
    Side1 is Side * Scale_factor,
    N1 is N - 1,
    Angle is 6 * pi/5,
    sierpinski_pentagons(Stream, X, Y, Scale_factor, Side1, Angle, N1, 5).

write_pentagon_points(_, _, _, _, _, 0):-!.
write_pentagon_points(Stream, Side, Angle, X, Y, N):-
    N1 is N - 1,
    X1 is X + cos(Angle) * Side,
    Y1 is Y - sin(Angle) * Side,
    Angle1 is Angle + 2 * pi/5,
    format(Stream, ' ~g,~g', [X1, Y1]),
    write_pentagon_points(Stream, Side, Angle1, X1, Y1, N1).

sierpinski_pentagons(_, _, _, _, _, _, _, 0):-!.
sierpinski_pentagons(Stream, X, Y, Scale_factor, Side, Angle, N, I):-
    I1 is I - 1,
    Distance is Side + Side * cos(2 * pi/5) * 2,
    X1 is X + cos(Angle) * Distance,
    Y1 is Y - sin(Angle) * Distance,
    Angle1 is Angle + 2 * pi/5,
    sierpinski_pentagon(Stream, X1, Y1, Scale_factor, Side, N),
    sierpinski_pentagons(Stream, X1, Y1, Scale_factor, Side, Angle1, N, I1).


from turtle import *
import math
speed(0)      # 0 is the fastest speed. Otherwise, 1 (slow) to 10 (fast)
hideturtle()  # hide the default turtle

part_ratio = 2 * math.cos(math.radians(72))
side_ratio = 1 / (part_ratio + 2)

hide_turtles = True   # show/hide turtles as they draw
path_color = "black"  # path color
fill_color = "black"  # fill color

# turtle, size
def pentagon(t, s):
  t.color(path_color, fill_color)
  t.pendown()
  t.right(36)
  t.begin_fill()
  for i in range(5):
    t.forward(s)
    t.right(72)
  t.end_fill()

# iteration, turtle, size
def sierpinski(i, t, s):
  t.setheading(0)
  new_size = s * side_ratio

  if i > 1:
    i -= 1

    # create four more turtles
    for j in range(4):
      t.right(36)
      short = s * side_ratio / part_ratio
      dist = [short, s, s, short][j]

      # spawn a turtle
      spawn = Turtle()
      if hide_turtles:spawn.hideturtle()
      spawn.penup()
      spawn.setposition(t.position())
      spawn.setheading(t.heading())
      spawn.forward(dist)

      # recurse for spawned turtles
      sierpinski(i, spawn, new_size)

    # recurse for parent turtle
    sierpinski(i, t, new_size)

  else:
    # draw a pentagon
    pentagon(t, s)
    # delete turtle
    del t

def main():
  t = Turtle()
  t.hideturtle()
  t.penup()
  screen = t.getscreen()
  y = screen.window_height()
  t.goto(0, y/2-20)

  i = 5       # depth. i >= 1
  size = 300  # side length

  # so the spawned turtles move only the distance to an inner pentagon
  size *= part_ratio

  # begin recursion
  sierpinski(i, t, size)

main()


[ $ "turtleduck.qky" loadfile ] now!

[ [ 1 1
    30 times
       [ tuck + ]
   swap join ] constant
   do ]                 is phi        (       --> n/d )

[ 5 times
    [ 2dup walk
      1 5 turn ]
  2drop ]               is pentagon   ( n/d n -->     )

                forward is pentaflake

[ dup 0 = iff
    [ drop
      ' [ 79 126 229 ] fill
      pentagon ] done
  1 - temp put
  5 times
    [ 2dup 2 1 phi v- v*
      temp share pentaflake
      2dup fly
    1 5 turn ]
  temp release
  2drop ]         resolves pentaflake ( n/d n -->     )

turtle
3 10 turn
300 1 fly
2 5 turn
' [ 79 126 229 ] colour
400 1 5 pentaflake


#lang racket/base
(require racket/draw pict racket/math racket/class)

;; exterior angle
(define 72-degrees (degrees->radians 72))
;; After scaling we'll have 2 sides plus a gap occupying the length
;; of a side before scaling. The gap is the base of an isosceles triangle
;; with a base angle of 72 degrees.
(define scale-factor (/ (+ 2 (* (cos 72-degrees) 2))))
;; Starting at the top of the highest pentagon, calculate
;; the top vertices of the other pentagons by taking the
;; length of the scaled side plus the length of the gap.
(define dist-factor (+ 1 (* (cos 72-degrees) 2)))

;; don't use scale, since it scales brushes too (making lines all tiny)
(define (draw-pentagon x y side depth dc)
  (let recur ((x x) (y y) (side side) (depth depth))
    (cond
      [(zero? depth)
       (define p (new dc-path%))
       (send p move-to x y)
       (for/fold ((x x) (y y) (α (* 3 72-degrees))) ((i 5))
         (send p line-to x y)
         (values (+ x (* side (cos α)))
                 (- y (* side (sin α)))
                 (+ α 72-degrees)))
       (send p close)
       (send dc draw-path p)]
      [else
       (define side/ (* side scale-factor))
       (define dist (* side/ dist-factor))
       ;; The top positions form a virtual pentagon of their own,
       ;; so simply move from one to the other by changing direction.
       (for/fold ((x x) (y y) (α (* 3 72-degrees))) ((i 5))
         (recur x y side/ (sub1 depth))
         (values (+ x (* dist (cos α)))
                 (- y (* dist (sin α)))
                 (+ α 72-degrees)))])))

(define (dc-draw-pentagon depth w h #:margin (margin 4))
  (dc (lambda (dc dx dy)
        (define old-brush (send dc get-brush))
        (send dc set-brush (make-brush #:style 'transparent))
        (draw-pentagon (/ w 2)
                       (* 3 margin)
                       (* (- (/ w 2) (* 2 margin))
                          (sin (/ pi 5)) 2)
                       depth
                       dc)
        (send dc set-brush old-brush))
      w h))

(dc-draw-pentagon 1 120 120)
(dc-draw-pentagon 2 120 120)
(dc-draw-pentagon 3 120 120)
(dc-draw-pentagon 4 120 120)
(dc-draw-pentagon 5 640 640)


constant $sides = 5;
constant order  = 5;
constant $dim   = 250;
constant scaling-factor = ( 3 - 5**.5 ) / 2;
my @orders = ((1 - scaling-factor) * $dim) «*» scaling-factor «**» (^order);

my $fh = open('sierpinski_pentagon.svg', :w);

$fh.say: qq|<svg height="{$dim*2}" width="{$dim*2}" style="fill:blue" version="1.1" xmlns="http://www.w3.org/2000/svg">|;

my @vertices = map { cis( $_ * τ / $sides ) }, ^$sides;

for 0 ..^ $sides ** order -> $i {
   my $vector = [+] @vertices[$i.base($sides).fmt("%{order}d").comb] «*» @orders;
   $fh.say: pgon ((@orders[*-1] * (1 - scaling-factor)) «*» @vertices «+» $vector)».reals».fmt("%0.3f");
};

sub pgon (@q) { qq|<polygon points="{@q}" transform="translate({$dim},{$dim}) rotate(-18)"/>| }

$fh.say: '</svg>';
$fh.close;


THETA = Math::PI * 2 / 5
SCALE_FACTOR = (3 - Math.sqrt(5)) / 2
MARGIN = 20

attr_reader :pentagons, :renderer
def settings
  size(400, 400)
end

def setup
  sketch_title 'Pentaflake'
  radius = width / 2 - 2 * MARGIN
  center = Vec2D.new(radius - 2 * MARGIN, 3 * MARGIN)
  pentaflake = Pentaflake.new(center, radius, 5)
  @pentagons = pentaflake.pentagons
end

def draw
  background(255)
  stroke(0)
  pentagons.each do |penta|
    draw_pentagon(penta)
  end
  no_loop
end

def draw_pentagon(pent)
  points = pent.vertices
  begin_shape
  points.each do |pnt|
    pnt.to_vertex(renderer)
  end
  end_shape(CLOSE)
end

def renderer
  @renderer ||= GfxRender.new(self.g)
end

class Pentaflake
  attr_reader :pentagons

  def initialize(center, radius, depth)
    @pentagons = []
    create_pentagons(center, radius, depth)
  end

  def create_pentagons(center, radius, depth)
    if depth.zero?
      pentagons << Pentagon.new(center, radius)
    else
      radius *= SCALE_FACTOR
      distance = radius * Math.sin(THETA) * 2
      (0..4).each do |idx|
        x = center.x + Math.cos(idx * THETA) * distance
        y = center.y + Math.sin(idx * THETA) * distance
        center = Vec2D.new(x, y)
        create_pentagons(center, radius, depth - 1)
      end
    end
  end
end

class Pentagon
  attr_reader :center, :radius

  def initialize(center, radius)
    @center = center
    @radius = radius
  end

  def vertices
    (0..4).map do |idx|
      center + Vec2D.new(radius * Math.sin(THETA * idx), radius * Math.cos(THETA * idx))
    end
  end
end


// [dependencies]
// svg = "0.8.0"

fn sierpinski_pentagon(
    mut document: svg::Document,
    mut x: f64,
    mut y: f64,
    mut side: f64,
    order: usize,
) -> svg::Document {
    use std::f64::consts::PI;
    use svg::node::element::Polygon;

    let degrees72 = 0.4 * PI;
    let mut angle = 3.0 * degrees72;
    let scale_factor = 1.0 / (2.0 + degrees72.cos() * 2.0);

    if order == 1 {
        let mut points = Vec::new();
        points.push((x, y));
        for _ in 0..5 {
            x += angle.cos() * side;
            y -= angle.sin() * side;
            angle += degrees72;
            points.push((x, y));
        }
        let polygon = Polygon::new()
            .set("fill", "blue")
            .set("stroke", "black")
            .set("stroke-width", "1")
            .set("points", points);
        document = document.add(polygon);
    } else {
        side *= scale_factor;
        let distance = side + side * degrees72.cos() * 2.0;
        for _ in 0..5 {
            x += angle.cos() * distance;
            y -= angle.sin() * distance;
            angle += degrees72;
            document = sierpinski_pentagon(document, x, y, side, order - 1);
        }
    }
    document
}

fn write_sierpinski_pentagon(file: &str, size: usize, order: usize) -> std::io::Result<()> {
    use std::f64::consts::PI;
    use svg::node::element::Rectangle;

    let margin = 5.0;
    let radius = (size as f64) / 2.0 - 2.0 * margin;
    let side = radius * (0.2 * PI).sin() * 2.0;
    let height = side * ((0.2 * PI).sin() + (0.4 * PI).sin());
    let x = (size as f64) / 2.0;
    let y = (size as f64 - height) / 2.0;

    let rect = Rectangle::new()
        .set("width", "100%")
        .set("height", "100%")
        .set("fill", "white");

    let mut document = svg::Document::new()
        .set("width", size)
        .set("height", size)
        .add(rect);

    document = sierpinski_pentagon(document, x, y, side, order);
    svg::save(file, &document)
}

fn main() {
    write_sierpinski_pentagon("sierpinski_pentagon.svg", 600, 5).unwrap();
}


import java.awt._
import java.awt.event.ActionEvent
import java.awt.geom.Path2D

import javax.swing._

import scala.annotation.tailrec
import scala.math.{Pi, cos, sin, sqrt}

object SierpinskiPentagon extends App {
  SwingUtilities.invokeLater(() => {

    class SierpinskiPentagon extends JPanel {

      /* Try to avoid random color values clumping together */

      private var hue = math.random

      // exterior angle
      private val deg072 = 2 * Pi / 5d //toRadians(72)
      /* After scaling we'll have 2 sides plus a gap occupying the length
         of a side before scaling. The gap is the base of an isosceles triangle
         with a base angle of 72 degrees. */
      //private val scaleFactor = 1 / (2 + cos(deg072) * 2)
      private var limit = 0

      private def drawPentagon(g: Graphics2D, x: Double, y: Double, side: Double, depth: Int): Unit = {
        val scaleFactor = 1 / (2 + cos(deg072) * 2)

        if (depth == 0) {
          // draw from the top
          @tailrec
          def iter0(i: Int, x: Double, y: Double, angle: Double, p: Path2D.Double): Path2D.Double = {
            if (i < 0) p
            else {
              p.lineTo(x, y)
              iter0(i - 1, x + cos(angle) * side, y - sin(angle) * side, angle + deg072, p)
            }
          }

          def p1: Path2D.Double = iter0(4, x, y, 3 * deg072, {
            val p = new Path2D.Double
            p.moveTo(x, y)
            p
          })

          def p: Path2D.Double = iter0(4, x, y, 3 * deg072, p1)

          def next: Color = {
            hue = (hue + (sqrt(5) - 1) / 2) % 1
            Color.getHSBColor(hue.toFloat, 1, 1)
          }

          g.setColor(next)
          g.fill(p)
        }
        else {
          val _side = side * scaleFactor
          /* Starting at the top of the highest pentagon, calculate
             the top vertices of the other pentagons by taking the
             length of the scaled side plus the length of the gap. */
          val distance = _side + _side * cos(deg072) * 2
          /* The top positions form a virtual pentagon of their own,
             so simply move from one to the other by changing direction. */

          def iter1(i: Int, x: Double, y: Double, angle: Double): Unit = {
            if (i < 0) ()
            else {
              drawPentagon(g, x, y, _side, depth - 1)
              iter1(i - 1, x + cos(angle) * distance, y - sin(angle) * distance, angle + deg072)
            }
          }

          iter1(4, x + cos(3 * deg072) * distance, y - sin(3 * deg072) * distance, 4 * deg072)
        }
      }

      override def paintComponent(gg: Graphics): Unit = {
        val (g, margin) = (gg.asInstanceOf[Graphics2D], 20)
        val side = (getWidth / 2 - 2 * margin) * sin(Pi / 5) * 2

        super.paintComponent(gg)
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        drawPentagon(g, getWidth / 2, 3 * margin, side, limit)
      }

      new Timer(3000, (_: ActionEvent) => {
        limit += 1
        if (limit >= 5) limit = 0
        repaint()
      }).start()

      setPreferredSize(new Dimension(640, 640))
      setBackground(Color.white)
    }

    val f = new JFrame("Sierpinski Pentagon") {
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
      setResizable(true)
      add(new SierpinskiPentagon, BorderLayout.CENTER)
      pack()
      setLocationRelativeTo(null)
      setVisible(true)
    }
  })

}


define order = 5
define sides = 5
define dim   = 500
define scaling_factor = ((3 - 5**0.5) / 2)
var orders = order.of {|i| ((1-scaling_factor) * dim) * scaling_factor**i }

say <<"STOP";
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg height="#{dim*2}" width="#{dim*2}"
    style="fill:blue" transform="translate(#{dim},#{dim}) rotate(-18)"
    version="1.1" xmlns="http://www.w3.org/2000/svg">
STOP

var vertices = sides.of {|i| Complex(0, i * Number.tau / sides).exp }

for i in ^(sides**order) {
   var vector = ([vertices["%#{order}d" % i.base(sides) -> chars]] »*« orders «+»)
   var points = (vertices »*» orders[-1]*(1-scaling_factor) »+» vector »reals()» «%« '%0.3f')
   say ('<polygon points="' + points.join(' ') + '"/>')
}

say '</svg>'


Private Sub sierpinski(Order_ As Integer, Side As Double)
    Dim Circumradius As Double, Inradius As Double
    Dim Height As Double, Diagonal As Double, HeightDiagonal As Double
    Dim Pi As Double, p(5) As String, Shp As Shape
    Circumradius = Sqr(50 + 10 * Sqr(5)) / 10
    Inradius = Sqr(25 + 10 * Sqr(5)) / 10
    Height = Circumradius + Inradius
    Diagonal = (1 + Sqr(5)) / 2
    HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4
    Pi = WorksheetFunction.Pi
    Ratio = Height / (2 * Height + HeightDiagonal)
    'Get a base figure
    Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _
        2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)
    p(0) = Shp.Name
    Shp.Rotation = 180
    Shp.Line.Weight = 0
    For j = 1 To Order_
        'Place 5 copies of the figure in a circle around it
        For i = 0 To 4
            'Copy the figure
            Set Shp = Shp.Duplicate
            p(i + 1) = Shp.Name
            If i = 0 Then Shp.Rotation = 0
            'Place around in a circle
            Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)
            Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)
            Shp.Visible = msoTrue
        Next i
        'Group the 5 figures
        Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group
        p(0) = Shp.Name
        If j < Order_ Then
            'Shrink the figure
            Shp.ScaleHeight Ratio, False
            Shp.ScaleWidth Ratio, False
            'Flip vertical and place in the center
            Shp.Rotation = 180
            Shp.Left = 2 * Side
            Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side
        End If
    Next j
End Sub

Public Sub main()
    sierpinski Order_:=5, Side:=200
End Sub


import "graphics" for Canvas, Color
import "dome" for Window
import "math" for Math

var Deg72 = 72 * Num.pi / 180  // 72 degrees in radians
var ScaleFactor = 1 / (2 + Math.cos(Deg72) * 2)
var Palette = [Color.red, Color.blue, Color.green, Color.indigo, Color.brown]
var ColorIndex = 0
var OldX = 0
var OldY = 0

class SierpinskiPentagon {
    construct new(width, height) {
        Window.title = "Sierpinksi Pentagon"
        Window.resize(width, height)
        Canvas.resize(width, height)
        _w = width
        _h = height
    }

    init() {
        var order = 5  // can also set this to 1, 2, 3, or 4
        var hw = _w / 2
        var margin = 20
        var radius = hw - 2 * margin
        var side = radius * Math.sin(Num.pi/5) * 2
        drawPentagon(hw, 3 * margin, side, order - 1)
    }

    drawPentagon(x, y, side, depth) {
        var angle = 3 * Deg72
        if (depth == 0) {
            var col = Palette[ColorIndex]
            OldX = x
            OldY = y
            for (i in 0..4) {
                x = x + Math.cos(angle) * side
                y = y - Math.sin(angle) * side
                Canvas.line(OldX, OldY, x, y, col, 2)
                OldX = x
                OldY = y
                angle = angle + Deg72
            }
            ColorIndex = (ColorIndex + 1) % 5
        } else {
            side = side * ScaleFactor
            var dist = side * (1 + Math.cos(Deg72) * 2)
            for (i in 0..4) {
                x = x + Math.cos(angle) * dist
                y = y - Math.sin(angle) * dist
                drawPentagon(x, y, side, depth-1)
                angle = angle + Deg72
            }
        }
    }

    update() {}

    draw(alpha) {}
}

var Game = SierpinskiPentagon.new(640, 640)


const order=5, sides=5, dim=250, scaleFactor=((3.0 - (5.0).pow(0.5))/2);
const tau=(0.0).pi*2; // 2*pi*r
orders:=order.pump(List,fcn(n){ (1.0 - scaleFactor)*dim*scaleFactor.pow(n) });

println(
#<<<
0'|<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg height="%d" width="%d" style="fill:blue" transform="translate(%d,%d) rotate(-18)"
    version="1.1" xmlns="http://www.w3.org/2000/svg">|
#<<<
   .fmt(dim*2,dim*2,dim,dim));

vertices:=sides.pump(List,fcn(s){ (1.0).toRectangular(tau*s/sides) }); // points on unit circle
vx:=vertices.apply('wrap([(a,b)]v,x){ return(a*x,b*x) },  // scaled points
		orders[-1]*(1.0 - scaleFactor));
fmt:="%%0%d.%dB".fmt(sides,order).fmt; //-->%05.5B (leading zeros, 5 places, base 5)
sides.pow(order).pump(Console.println,'wrap(i){
   vector:=fmt(i).pump(List,vertices.get)  // "00012"-->(vertices[0],..,vertices[2])
     .zipWith(fcn([(a,b)]v,x){ return(a*x,b*x) },orders) // ((a,b)...)*x -->((ax,bx)...)
     .reduce(fcn(vsum,v){ vsum[0]+=v[0]; vsum[1]+=v[1]; vsum },L(0.0, 0.0)); //-->(x,y)
   pgon(vx.apply(fcn([(a,b)]v,c,d){ return(a+c,b+d) },vector.xplode()));
});
println("</svg>");  // 3,131 lines

fcn pgon(vertices){  // eg ( ((250,0),(248.595,1.93317),...), len 5
   0'|<polygon points="%s"/>|.fmt(
       vertices.pump(String,fcn(v){ "%.3f %.3f ".fmt(v.xplode()) }) )
}


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program simpleWin64.s   link with X11 library */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/* constantes X11 */
.equ KeyPressed,    2
.equ ButtonPress,   4
.equ ClientMessage, 33
.equ KeyPressMask,  1
.equ ButtonPressMask,     4
.equ ButtonReleaseMask,   8
.equ ExposureMask,        1<<15
.equ StructureNotifyMask, 1<<17
.equ EnterWindowMask,     1<<4
.equ LeaveWindowMask,     1<<5

/*******************************************/
/* Structures                              */
/********************************************/
/* Button structure */
    .struct  0
BT_cbdata:
    .struct BT_cbdata  + 8
BT_adresse:
    .struct BT_adresse + 8
BT_GC:
    .struct BT_GC + 8
BT_Font:
    .struct BT_Font + 8
BT_fin:
/***************************************************/
/* structure XButtonEvent    */
    .struct  0
XBE_type:                          //event type
    .struct XBE_type + 8
XBE_serial:                       // No  last request processed  server */
    .struct XBE_serial + 8
XBE_send_event:                   // true if this came from a SendEvent request */
    .struct XBE_send_event + 8
XBE_display:                      // Display the event was read from
    .struct XBE_display + 8
XBE_window:                       // "event" window it is reported relative to
    .struct XBE_window + 8
XBE_root:                         // root window that the event occurred on
    .struct XBE_root + 8
XBE_subwindow:                    // child window
    .struct XBE_subwindow + 8
XBE_time:                         // milliseconds
    .struct XBE_time + 8
XBE_x:                            // pointer x, y coordinates in event window
    .struct XBE_x + 8
XBE_y:
    .struct XBE_y + 8
XBE_x_root:                       // coordinates relative to root
    .struct XBE_x_root + 8
XBE_y_root:
    .struct XBE_y_root + 8
XBE_state:                        // key or button mask
    .struct XBE_state + 8
XBE_button:                       // detail
    .struct XBE_button + 8
XBE_same_screen:                  // same screen flag
    .struct XBE_same_screen + 8
XBE_fin:
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szRetourligne:      .asciz  "\n"
szMessErreur:       .asciz "Server X11 not found.\n"
szMessErrfen:       .asciz "Error create X11 window.\n"
szMessErrGC:        .asciz "Error create Graphic Context.\n"
szMessErrButton:    .asciz "Error create button.\n"
szMessErrButtonGC:  .asciz "Error create button Graphic Context.\n"
szMessGoodBye:      .asciz "There have been no clicks yet"

szTextButton:       .asciz "Click me"
szMessResult:       .asciz "You clicked me @ times       "

szLibDW:            .asciz "WM_DELETE_WINDOW"      // message close window

/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
.align 4
qDisplay:        .skip 8           // Display address
qDefScreen:      .skip 8           // Default screen address
identWin:        .skip 8           // window ident
qCounterClic:    .skip 8           // counter clic button
sZoneConv:       .skip 24
wmDeleteMessage: .skip 16          // ident close message
stEvent:         .skip 400         // provisional size

stButton:        .skip BT_fin
buffer:          .skip 500

/**********************************************/
/* -- Code section                            */
/**********************************************/
.text
.global main                   // program entry
main:
    mov x0,#0                  // open server X
    bl XOpenDisplay
    cmp x0,#0
    beq erreur
                               //  Ok return Display address
    ldr x1,qAdrqDisplay
    str x0,[x1]                // store Display address for future use
    mov x28,x0                 // and in register 28
                               // load default screen
    ldr x2,[x0,#264]           // at location 264
    ldr x1,qAdrqDefScreen
    str x2,[x1]                //store default_screen
    mov x2,x0
    ldr x0,[x2,#232]           // screen list

                               //screen areas
    ldr x5,[x0,#+88]           // white pixel
    ldr x3,[x0,#+96]           // black pixel
    ldr x4,[x0,#+56]           // bits par pixel
    ldr x1,[x0,#+16]           // root windows
                               // create window x11
    mov x0,x28                 //display
    mov x2,#0                  // position X
    mov x3,#0                  // position Y
    mov x4,600                 // weight
    mov x5,400                 // height
    mov x6,0                   // bordure ???
    ldr x7,0                   // ?
    ldr x8,qBlanc              // background
    str x8,[sp,-16]!           // argument fot stack
    bl XCreateSimpleWindow
    add sp,sp,16               // for stack alignement
    cmp x0,#0                  // error ?
    beq erreurF
    ldr x1,qAdridentWin
    str x0,[x1]                // store window ident for future use
    mov x27,x0                 // and in register 27

                               // Correction of window closing error
    mov x0,x28                 // Display address
    ldr x1,qAdrszLibDW         // atom name address
    mov x2,#1                  // False  create atom if not exist
    bl XInternAtom
    cmp x0,#0
    ble erreurF
    ldr x1,qAdrwmDeleteMessage // address message
    str x0,[x1]
    mov x2,x1                  // address atom create
    mov x0,x28                 // display address
    mov x1,x27                 // window ident
    mov x3,#1                  // number of protocoles
    bl XSetWMProtocols
    cmp x0,#0
    ble erreurF
                               // authorization of seizures
    mov x0,x28                 // display address
    mov x1,x27                 // window ident
    ldr x2,qFenetreMask        // mask
    bl XSelectInput
    cmp x0,#0
    ble 99f
                               // create Graphic Context
    mov x0,x28                 // display address
    mov x1,x27                 // window ident
    bl createGC                // GC address -> x26
    cbz x0,erreurF
                               // create Graphic Context 1
    mov x0,x28                 // display address
    mov x1,x27                 // window ident
    bl createGC1                // GC address -> x25
    cbz x0,erreurF
                               // Display window
    mov x1,x27                 // ident window
    mov x0,x28                 // Display address
    bl XMapWindow

    ldr x0,qAdrszMessGoodBye   // display text
    bl displayText

    bl createButton            // create button on screen
1:                             // events loop
    mov x0,x28                 // Display address
    ldr x1,qAdrstEvent         // events structure address
    bl XNextEvent
    ldr x0,qAdrstEvent         // events structure address
    ldr w0,[x0]                // type in 4 first bytes
    cmp w0,#ClientMessage      // message for close window
    beq 2f                     // yes -> end
    cmp w0,#ButtonPress        // clic mouse button
    beq 3f
                               // other events
    b 1b                       // and loop
2:
    ldr x0,qAdrstEvent         // events structure address
    ldr x1,[x0,56]             // location message code
    ldr x2,qAdrwmDeleteMessage // equal ?
    ldr x2,[x2]
    cmp x1,x2
    bne 1b                     // no loop
    mov x0,0                   // end Ok
    b 100f
    //TODO: close ??

3:
    ldr x0,qAdrstEvent         // events structure address
    bl evtButtonMouse
    b 1b

erreurF:                       // error create window
    ldr x0,qAdrszMessErrfen
    bl affichageMess
    mov x0,1
    b 100f
erreur:                        // error no server x11 active
    ldr x0,qAdrszMessErreur
    bl affichageMess
    mov x0,1
100:                           // program standard end
    mov x8,EXIT
    svc 0
qBlanc:              .quad 0xF0F0F0F0
qAdrqDisplay:        .quad qDisplay
qAdrqDefScreen:      .quad qDefScreen
qAdridentWin:        .quad identWin
qAdrstEvent:         .quad stEvent
qAdrszMessErrfen:    .quad szMessErrfen
qAdrszMessErreur:    .quad szMessErreur
qAdrwmDeleteMessage: .quad wmDeleteMessage
qAdrszLibDW:         .quad szLibDW
qAdrszMessGoodBye:   .quad szMessGoodBye
qFenetreMask:        .quad  KeyPressMask|ButtonPressMask|StructureNotifyMask|ExposureMask|EnterWindowMask
/******************************************************************/
/*     create Graphic Context                                     */
/******************************************************************/
/* x0 contains the Display address */
/* x1 contains the ident Window */
createGC:
    stp x20,lr,[sp,-16]!       // save  registers
    mov x20,x0                 // save display address
    mov x2,#0
    mov x3,#0
    bl XCreateGC
    cbz x0,99f
    mov x26,x0                 // save GC
    mov x0,x20                 // display address
    mov x1,x26
    ldr x2,qRed                // code RGB color
    bl XSetForeground
    cbz x0,99f
    mov x0,x26                 // return GC
    b 100f
99:
    ldr x0,qAdrszMessErrGC
    bl affichageMess
    mov x0,0
100:
    ldp x20,lr,[sp],16         // restaur  2 registers
    ret                        // return to address lr x30
qAdrszMessErrGC:             .quad szMessErrGC
qRed:                        .quad 0xFF0000
qGreen:                      .quad 0xFF00
qBlue:                       .quad 0xFF
qBlack:                      .quad 0x0
/******************************************************************/
/*     create Graphic Context 1                                    */
/******************************************************************/
/* x0 contains the Display address */
/* x1 contains the ident Window */
createGC1:
    stp x20,lr,[sp,-16]!       // save  registers
    mov x20,x0                 // save display address
    mov x2,#0
    mov x3,#0
    bl XCreateGC
    cbz x0,99f
    mov x25,x0                 // save GC
    mov x0,x20                 // display address
    mov x1,x25
    ldr x2,qBlanc              // code RGB color
    bl XSetForeground
    cbz x0,99f
    mov x0,x25                 // return GC1
    b 100f
99:
    ldr x0,qAdrszMessErrGC
    bl affichageMess
    mov x0,0
100:
    ldp x20,lr,[sp],16         // restaur  2 registers
    ret                        // return to address lr x30
/******************************************************************/
/*     create button on screen                                     */
/******************************************************************/
createButton:
    stp x21,lr,[sp,-16]!       // save  registers
                               // create button window
    mov x0,x28                 // display address
    mov x1,x27                 // ident window
    mov x2,80                 // X position
    mov x3,150                 // Y position
    mov x4,60                  // weight
    mov x5,30                  // height
    mov x6,2                   // border
    ldr x7,qBlack
    ldr x8,qBlanc              // background
    str x8,[sp,-16]!           // argument fot stack
    bl XCreateSimpleWindow
    add sp,sp,16               // for stack alignement
    cmp x0,#0                  // error ?
    beq 99f
    ldr x21,qAdrstButton
    str x0,[x21,BT_adresse]    // save ident button
    str xzr,[x21,BT_cbdata]    // for next use

                              // autorisation des saisies
    mov x0,x28                // display address
    ldr x1,[x21,BT_adresse]   // button address
    ldr x2,qButtonMask        // mask
    bl XSelectInput
                              // create Graphic Contexte of button
    mov x0,x28                // display address
    ldr x1,[x21,BT_adresse]   // button ident
    mov x2,#0
    mov x3,#0
    bl XCreateGC
    cmp x0,#0
    beq 98f
    str x0,[x21,BT_GC]        // store GC
                              // display button
    mov x0,x28                // display address
    ldr x1,[x21,BT_adresse]   // button address
    bl XMapWindow
    ldr x5,qAdrszTextButton   // text address
    mov x6,0                  // text size
1:                            // loop compute text size
    ldrb w10,[x5,x6]          // load text byte
    cbz x10,2f                // zero -> end
    add x6,x6,1               // increment size
    b 1b                      // and loop
2:
    mov x0,x28                // display address
    ldr x1,[x21,BT_adresse]   // button address
    ldr x2,[x21,BT_GC]        // GC address
    mov x3,#8                 // position x
    mov x4,#15                // position y
    bl XDrawString

    b 100f
98:
    ldr x0,qAdrszMessErrButtonGC
    bl affichageMess
    b 100f
99:
    ldr x0,qAdrszMessErrButton
    bl affichageMess
100:
    ldp x1,lr,[sp],16      // restaur  2 registers
    ret                    // return to address lr x30
qAdrstButton:           .quad stButton
qAdrszTextButton:       .quad szTextButton
qAdrszMessErrButtonGC:  .quad szMessErrButtonGC
qAdrszMessErrButton:    .quad szMessErrButton
qButtonMask:            .quad  ButtonPressMask|ButtonReleaseMask|StructureNotifyMask|ExposureMask|LeaveWindowMask|EnterWindowMask

/******************************************************************/
/*     display text on screen                                     */
/******************************************************************/
/* x0 contains the address of text */
displayText:
    stp x1,lr,[sp,-16]!    // save  registers
    mov x5,x0              // text address
    mov x6,0               // text size
1:                         // loop compute text size
    ldrb w10,[x5,x6]       // load text byte
    cbz x10,2f             // zero -> end
    add x6,x6,1            // increment size
    b 1b                   // and loop
2:
    mov x0,x28             // display address
    mov x1,x27             // ident window
    mov x2,x26             // GC address
    mov x3,#50             // position x
    mov x4,#100            // position y
    bl XDrawString
100:
    ldp x1,lr,[sp],16      // restaur  2 registers
    ret                    // return to address lr x30
/******************************************************************/
/*     events clic mouse button                                      */
/******************************************************************/
/* x0 contains the address of event */
evtButtonMouse:
    stp x1,lr,[sp,-16]!         // save  registers
    ldr x10,[x0,XBE_window]     //  windows of event
    ldr x11,qAdrstButton        // load button ident
    ldr x12,[x11,BT_adresse]
    cmp x10,x12                 // equal ?
    bne 100f                    // no
    bl eraseText                // yes erase the text
    ldr x10,qAdrqCounterClic    // load counter clic
    ldr x0,[x10]
    add x0,x0,1                 // and increment
    str x0,[x10]
    ldr x1,qAdrsZoneConv        // and decimal conversion
    bl conversion10
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc       // and insert result at @ character
    bl displayText              // and display new text

100:
    ldp x1,lr,[sp],16           // restaur  2 registers
    ret                         // return to address lr x30
qAdrqCounterClic:         .quad qCounterClic
qAdrsZoneConv:            .quad sZoneConv
qAdrszMessResult:         .quad szMessResult
/******************************************************************/
/*     erase text                                      */
/******************************************************************/
eraseText:
    stp x1,lr,[sp,-16]!    // save  registers
    mov x0,x28             // display address
    mov x1,x27             // ident window
    mov x2,x25             // GC1 address
    mov x3,20              // position x
    mov x4,70              // position y
    mov x5,400
    mov x6,50
    bl XFillRectangle
100:
    ldp x1,lr,[sp],16      // restaur  2 registers
    ret                    // return to address lr x30
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


with Gdk.Event;   use Gdk.Event;
with Gtk.Button;  use Gtk.Button;
with Gtk.Label;   use Gtk.Label;
with Gtk.Window;  use Gtk.Window;
with Gtk.Widget;  use Gtk.Widget;
with Gtk.Table;   use Gtk.Table;

with Gtk.Handlers;
with Gtk.Main;

procedure Simple_Windowed_Application is
   Window : Gtk_Window;
   Grid   : Gtk_Table;
   Button : Gtk_Button;
   Label  : Gtk_Label;
   Count  : Natural := 0;

   package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record);
   package Return_Handlers is
      new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean);

   function Delete_Event (Widget : access Gtk_Widget_Record'Class)
      return Boolean is
   begin
      return False;
   end Delete_Event;

   procedure Destroy (Widget : access Gtk_Widget_Record'Class) is
   begin
     Gtk.Main.Main_Quit;
   end Destroy;

   procedure Clicked (Widget : access Gtk_Widget_Record'Class) is
   begin
     Count := Count + 1;
     Set_Text (Label, "The button clicks:" & Natural'Image (Count));
   end Clicked;

begin
   Gtk.Main.Init;
   Gtk.Window.Gtk_New (Window);
   Gtk_New (Grid, 1, 2, False);
   Add (Window, Grid);
   Gtk_New (Label, "There have been no clicks yet");
   Attach (Grid, Label, 0, 1, 0, 1);
   Gtk_New (Button, "Click me");
   Attach (Grid, Button, 0, 1, 1, 2);
   Return_Handlers.Connect
   (  Window,
      "delete_event",
      Return_Handlers.To_Marshaller (Delete_Event'Access)
   );
   Handlers.Connect
   (  Window,
      "destroy",
      Handlers.To_Marshaller (Destroy'Access)
   );
   Handlers.Connect
   (  Button,
      "clicked",
      Handlers.To_Marshaller (Clicked'Access)
   );
   Show_All (Grid);
   Show (Window);

   Gtk.Main.Main;
end Simple_Windowed_Application;


∇ WindowedApplication

⍝ define a form with a label and a button
'Frm'⎕WC'Form' 'Clicks' (40 35) (10 15)
'Lbl'Frm.⎕WC'Label' 'There have been no clicks yet.' (10 10)
'Btn'Frm.⎕WC'Button' 'Click Me' (35 35) (25 25) ('Event' 'Select' 'Click')

⍝ callback function
Frm.Clicks←0
Frm.Click←{
    Clicks+←1
    p0←(1+Clicks=1)⊃'have' 'has'
    p1←(1+Clicks=1)⊃'clicks' 'click'
    Lbl.Value←'There ',p0,' been ',(⍕Clicks),' ',p1,'.'
}

∇


set counter to 0

set dialogReply to display dialog ¬
	"There have been no clicks yet" buttons {"Click Me", "Quit"} ¬
	with title "Simple Window Application"
set theAnswer to button returned of the result
if theAnswer is "Quit" then quit

repeat
	set counter to counter + 1
	set dialogReply to display dialog counter buttons {"Click Me", "Quit"} ¬
		with title "Simple Window Application"
	set theAnswer to button returned of the result
	if theAnswer is "Quit" then exit repeat
end repeat


; Create simple windowed application
   Gui, Add, Text, vTextCtl, There have been no clicks yet ; add a Text-Control
   Gui, Add, Button, gButtonClick xm, click me ; add a Button-Control
   Gui, Show, , Simple windowed application ; show the Window
Return ; end of the auto-execute section

ButtonClick: ; the subroutine executed each time the Button-Control is clicked
   count++ ; increment the click-counting var
   GuiControl, , TextCtl, %count% ; update the Text-Control with the click-counting var
Return ; end of the subroutine

GuiClose: ; the subroutine executed when the Window is closed
   ExitApp ; exit this process
Return


#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#Region ### START Koda GUI section ###
Local $GUI = GUICreate("Clicks", 280, 50, (@DesktopWidth - 280) / 2, (@DesktopHeight - 50) / 2)
Local $lblClicks = GUICtrlCreateLabel("There have been no clicks yet", 0, 0, 278, 20, $SS_CENTER)
Local $btnClicks = GUICtrlCreateButton("CLICK ME", 104, 25, 75, 25)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

Local $counter = 0

While 1
	$nMsg = GUIGetMsg()
	Switch $nMsg
		Case $GUI_EVENT_CLOSE
			Exit

		Case $btnClicks
			$counter += 1
			GUICtrlSetData($lblClicks, "Times clicked: " & $counter)
	EndSwitch
WEnd


#Region  Project Attributes
	#MainFormWidth: 593
	#MainFormHeight: 179
#End Region

Sub Process_Globals
	Private fx As JFX
	Private MainForm As Form
	Private btnClickMe As Button
	Private lblClickCounter As Label
	Private nClicks As Int = 0
	Private aPlurals() As Object = Array As Object(Array As String("has","click"),Array As String("have","clicks"))
End Sub

Sub AppStart (Form1 As Form, Args() As String)
	MainForm = Form1
	MainForm.RootPane.LoadLayout("Layout1") 'Load the layout file.
	MainForm.Show
End Sub

Sub btnClickMe_Action
	nClicks = nClicks + 1
	Dim aPlural() As Object = aPlurals(IIF(nClicks=1,0,1))
	lblClickCounter.Text = "There " & aPlural(0) & " been " & (nClicks) & " " & aPlural(1) & " so far."
End Sub

Sub IIF(test As Boolean, trueVal As Object, falseVal As Object) As Object
	If test Then
		Return trueVal
	Else
		Return falseVal
	End If
End Sub


OPTION GUI TRUE
PRAGMA GUI gtk3

gui = GUIDEFINE(" \
    { type=WINDOW name=window callback=delete-event title=\"Rosetta Code\" width-request=300 } \
    { type=BOX name=box parent=window orientation=GTK_ORIENTATION_VERTICAL } \
    { type=LABEL name=label parent=box height-request=50 label=\"There have been no clicks yet\" } \
    { type=BUTTON name=button parent=box callback=clicked label=\"Click Me\" }")

WHILE TRUE
    SELECT GUIEVENT$(gui)
        CASE "window"
            BREAK
        CASE "button"
            INCR clicked
            CALL GUISET(gui, "label", "label", "Button clicks: " & STR$(clicked))
    ENDSELECT
WEND


      INSTALL @lib$+"WINLIB2"
      INSTALL @lib$+"WINLIB5"

      window% = FN_newdialog("Rosetta Code", 100, 100, 120, 52, 8, 1000)
      PROC_static(window%, "There have been no clicks yet", 100, 10, 10, 100, 14, 0)
      PROC_pushbutton(window%, "Click me", FN_setproc(PROCclick), 40, 30, 40, 16, 0)
      PROC_showdialog(window%)

      REPEAT
        WAIT 1
      UNTIL !window% = 0
      QUIT

      DEF PROCclick
      PRIVATE clicks%
      clicks% += 1
      SYS "SetDlgItemText", !window%, 100, "Number of clicks = " + STR$(clicks%)
      ENDPROC


beads 1 program simple title:'Simple windowed application' //  written by CodingFiend

var g : record  //  global tracked mutable state
	label : str
	nclicks : num

========================
calc main_init  // our one time initialization for the program
	g.label = "There have been no clicks yet"
	g.nclicks = 0

========================
//  In beads you subdivide the screen by slicing it horizontally or vertically
//  so as to gradually break it down into pieces, some of which are drawn
horz slice main_draw  //  our main drawing function
	under
		draw_rect(fill:DARK_SLATE_GRAY) // fill entire screen

	//  slice the screen into 3 horz pieces, leaving 200 pt for our body
	skip 10 al
	add 200 pt main_draw2
	skip 10 al

vert slice main_draw2  //  now take the middle horz slice, and slice it vertically
	skip 10 al
	add 50 pt draw_click_count
	skip 2 al
	add 80 px draw_button
	skip 10 al

========================
draw draw_click_count
	draw_str(g.label, size:0.7, color:WHITE)

========================
draw draw_button
	draw_rect(fill:ORANGE, corner:20 pt, thick:2 pt, color:BROWN)
	draw_str("Click me", size:40, indent:8 pt, color:BLACK)
-------------------
track EV_TAP
	//  update our click count
	inc g.nclicks
	g.label = to_str(g.nclicks)


#include <stdio.h>
#include <gtk/gtk.h>

const gchar *clickme = "Click Me";
guint counter = 0;

#define MAXLEN 64
void clickedme(GtkButton *o, gpointer d)
{
    GtkLabel *l = GTK_LABEL(d);
    char nt[MAXLEN];

    counter++;
    snprintf(nt, MAXLEN, "You clicked me %d times", counter);
    gtk_label_set_text(l, nt);
}

int main(int argc, char **argv)
{
    GtkWindow *win;
    GtkButton *button;
    GtkLabel *label;
    GtkVBox *vbox;

    gtk_init(&argc, &argv);
    win = (GtkWindow*)gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(win, clickme);
    button = (GtkButton*)gtk_button_new_with_label(clickme);
    label = (GtkLabel*)gtk_label_new("There have been no clicks yet");
    gtk_label_set_single_line_mode(label, TRUE);
    vbox = (GtkVBox*)gtk_vbox_new(TRUE, 1);
    gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(label));
    gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(button));
    gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));
    g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL);
    g_signal_connect(G_OBJECT(button), "clicked", (GCallback)clickedme, label);
    gtk_widget_show_all(GTK_WIDGET(win));
    gtk_main();
    return 0;
}


using System.Windows.Forms;

class RosettaForm : Form
{
    RosettaForm()
    {
        var clickCount = 0;

        var label = new Label();
        label.Text = "There have been no clicks yet.";
        label.Dock = DockStyle.Top;
        Controls.Add(label);

        var button = new Button();
        button.Text = "Click Me";
        button.Dock = DockStyle.Bottom;
        button.Click += delegate
                        {
                            clickCount++;
                            label.Text = "Number of clicks: " + clickCount + ".";
                        };
        Controls.Add(button);
    }

    static void Main()
    {
        Application.Run(new RosettaForm());
    }
}


#ifndef CLICKCOUNTER_H
#define CLICKCOUNTER_H

#include <QWidget>
class QLabel ;
class QPushButton ;
class QVBoxLayout ;

class Counter : public QWidget {
    Q_OBJECT
public :
   Counter( QWidget * parent = 0 ) ;
private :
   int number ;
   QLabel *countLabel ;
   QPushButton *clicker ;
   QVBoxLayout *myLayout ;
private slots :
   void countClicks( ) ;
} ;
#endif


(ns counter-window
  (:import (javax.swing JFrame JLabel JButton)))

(defmacro on-action [component event & body]
  `(. ~component addActionListener
      (proxy [java.awt.event.ActionListener] []
        (actionPerformed [~event] [email protected]))))

(defn counter-app []
  (let [counter (atom 0)
        label (JLabel. "There have been no clicks yet")
        button (doto (JButton. "Click me!")
                 (on-action evnt
                   (.setText label
                      (str "Counter: " (swap! counter inc)))))
        panel (doto (JPanel.)
                (.setOpaque true)
                (.add label)
                (.add button))]
    (doto (JFrame. "Counter App")
      (.setContentPane panel)
      (.setSize 300 100)
      (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
      (.setVisible true))))


(defpackage #:rcswa
  (:use #:clim #:clim-lisp))
(in-package #:rcswa)


module winapp ;
import dfl.all ;
import std.string ;

class MainForm: Form {
  Label label ;
  Button button ;
  this() {
    width = 240 ;
    with(label = new Label) {
      text = "There have been no clicks yet" ;
      dock = DockStyle.TOP ;
      parent = this ;
    }
    with(button = new Button) {
      dock = DockStyle.BOTTOM ;
      text = "Click Me" ;
      parent = this ;
      click ~= &onClickButton ;
    }
    height = label.height + button.height + 36 ;
  }
  private void onClickButton(Object sender, EventArgs ea) {
    static int count = 0 ;
    label.text = "You had been clicked me " ~ std.string.toString(++count) ~ " times." ;
  }
}

void main() {
    Application.run(new MainForm);
}


-- begin file --

   Program SingleWinApp ;

   // This is the equivalent of the C #include
   Uses Forms, Windows, Messages, Classes, Graphics, Controls, StdCtrls ;

   type

     // The only reason for this declaration is to allow the connection of the
     // on click method to the forms button object. This class declaration adds
     // a procedure.

     TMainForm class(tform)
       Procedure AddClicks(sender : tObject);
     end;

   // Use these globals.
   var

     MainForm : tForm ;
     aLabel   : tLabel ;
     aButton  : tButton ;
     i        : integer = 0 ;

    // This is the Method call that we connect to the button object
    // to start counting the clicks.
    Procedure tMainForm.AddClicks(sender :tObject)
    begin
      inc(i);
      aLabel.Caption := IntToStr(i) + ' Clicks since startup' ;
    end;

    Begin
      // Do all the behind the scenes stuff that sets up the Windows environment
      Application.Initialize ;

      // Create the form

      // Forms can either be created with an owner, like I have done here, or with
      // the owner set to Nil. In pascal (all versions of Borland) '''NIL''' is a
      // reserved, (the equivalent of '''NULL''' in Ansi C) word and un-sets any pointer
      // variable. Setting the owner to the application object will ensure that the form is
      // freed by the application object when the application shuts down. If I had set
      // the owner to NIL then i would have had to make sure I freed the form explicitly
      // or it would have been orphaned, thus creating a memory leak.

      // I must direct your attention to the CreateNew constructor.  This is
      // a non standard usage.  Normally the constructor Create() will call this
      // as part of the initialization routine for the form. Normally as you drop
      // various components on a form in deign mode, a DFM file is created with
      // all the various initial states of the controls. This bypasses the
      // DFM file altogether although all components AND the form are created
      // with default values. (see the Delphi help file).

      MainForm          := tMainForm.CreateNew(Application);
      MainForm.Parent   := Application ;
      MainForm.Position := poScreenCenter ;
      MainForm.Caption  := 'Single Window Application' ;

      // Create the Label, set its owner as MaiaForm
      aLabel          := tLabel.Create(mainForm);
      aLabel.Parent   := MainForm;
      aLabel.Caption  := IntToStr(i) + ' Clicks since startup' ;
      aLabel.Left     := 20 ;
      aLabel.Top      := MainForm.ClientRect.Bottom div 2 ;

      // Create the button, set its owner to MainForm
      aButton         := tButton.Create(MainForm);
      aButton.Parent  := MainForm ;
      aButton.Caption := 'Click Me!';
      aButton.Left    := (MainForm.ClientRect.Right div 2)-(aButton.Width div 2 );
      aButton.Top     := MainForm.ClientRect.Bottom - aButton.Height - 10 ;
      aButton.OnClick := AddClicks ;

      // Show the main form, Modaly. The ONLY reason to do this is because in this
      // demonstration if you only call the SHOW method, the form will appear and
      // disappear in a split second.
      MainForm.ShowModal ;

      Application.Run ;

   end. // Program


when (currentVat.morphInto("awt")) -> {
    var clicks := 0
    def w := <swing:makeJFrame>("Rosetta Code 'Simple Windowed Application'")
    w.setContentPane(JPanel`
        ${def l := <swing:makeJLabel>("There have been no clicks yet.")} $\
            ${def b := <swing:makeJButton>("Click Me")}
    `)
    b.addActionListener(def _ {
        to actionPerformed(_) {
            clicks += 1
            l.setText(`Number of clicks: $clicks`)
        }
    })
    w.pack()
    w.show()
}


(define (ui-add-button text) ;; helper
    (define b (ui-create-element "button" '((type "button"))))
    (ui-set-html b text)
    (ui-add b))

(define (panel )
    (ui-clear)
    (define *clicks* 0)
    (define text (ui-create-element "span" '((style "font-weight:bold"))))
    (ui-add text)
    (ui-set-html text "No click yet")

    (define btn (ui-add-button "Click-me"))
    (define (count-clicks elem)
        (++ *clicks*)
        (ui-set-html text *clicks*))
    (ui-on-click btn count-clicks)

    (stdout-hide #t)
    (stdin-hide #t)) ;; end panel definition

(panel)


import forms;
import extensions;

public class MainWindow : SDIDialog
{
    Label  lblClicks;
    Button btmClickMe;

    //Store how much clicks the user doed
    int clicksCount;

    constructor new()
       <= new()
    {
        lblClicks := Label.new();
        btmClickMe := Button.new();

        clicksCount := 0;
        self
            .appendControl(lblClicks)
            .appendControl(btmClickMe);

        self.Caption := "Rosseta Code";
        self.setRegion(100, 100, 160, 80);

        lblClicks.Caption := "Clicks: 0";
        lblClicks.setRegion(10, 2, 160, 20);

        btmClickMe.Caption := "Click me";
        btmClickMe.setRegion(7, 20, 140, 30);

        btmClickMe.onClick := (args){ self.onButtonClick(); };
    }

    private onButtonClick()
    {
        clicksCount := clicksCount + 1;

        lblClicks.Caption := "Clicks: " + clicksCount.toString();
    }
}


include EuWinGUI.ew

Window("EuWinGUI - Simple windowed application",100,100,360,100)
constant Button1 = Control(Button,"Click me",250,20,80,25)
constant Label1 = Control(Label,"There have been no clicks yet",10,25,200,18)

integer clicks
clicks = 0

-- Event loop
while 1 do
    WaitEvent()
    if EventOwner = Button1 and Event = Click then
        clicks += 1
        SetText(Label1,sprintf("You clicked me %d times",clicks))
    end if
end while

CloseApp(0)


open System.Windows.Forms

let mutable clickCount = 0

let form = new Form()

let label = new Label(Text = "There have been no clicks yet.", Dock = DockStyle.Top)
form.Controls.Add(label)

let button = new Button(Text = "Click me", Dock = DockStyle.Bottom)
button.Click.Add(fun _ ->
    clickCount <- clickCount+1
    label.Text <- sprintf "Number of clicks: %i." clickCount)
form.Controls.Add(button)

Application.Run(form)


USING: accessors arrays kernel math math.parser namespaces
sequences ui ui.gadgets ui.gadgets.borders ui.gadgets.buttons
ui.gadgets.grids ui.gadgets.labels ui.gadgets.worlds ;
IN: rosetta-code.simple-windowed-application

SYMBOL: n

CONSTANT: on-btn-press [
    parents second n get number>string <label> { 0 1 }
    grid-add drop n inc
]

: build-ui ( -- ) [
    f
    T{ world-attributes { title "Simple windowed application" } }
    clone
    "click me" on-btn-press <border-button> 1array
    "There have been no clicks yet" <label> 1array
    2array <grid>
    { 100 100 } <border>
    >>gadgets
    open-window
] with-ui ;

: main ( -- ) 1 n set build-ui ;

MAIN: main


using fwt
using gfx

class SimpleApplication
{
  public static Void main ()
  {
    Window
    {
      title = "Simple Window Application"
      size = Size(350, 50)
      clicked := 0
      label := Label
      {
        text = "There have been no clicks yet"
      }
      Button
      {
        text = "Click me"
        onAction.add |Event e|
        {
          clicked += 1
          label.text = "There have been $clicked clicks"
        }
      },
      label,
    }.open
  }
}


also minos
text-label ptr click-label
Variable click#  click# off
: click-win ( -- ) screen self window new window with
    X" There have been no clicks yet" text-label new
      dup F bind click-label
    ^ S[ 1 click# +!
         click# @ 0 <# #S s" Number of clicks: " holds #>
         click-label assign ]S X" Click me" button new
    &2 vabox new panel s" Clicks" assign show endwith ;
click-win


#Include "windows.bi"

Dim As HWND Window_Main, Static_Text, Button_Click
Dim As MSG msg
Dim As Integer Num_Click
Dim As String Text

'Create a window with a static text control and a button:
Window_Main = CreateWindow("#32770", "Simple Windowed Application", WS_OVERLAPPEDWINDOW Or WS_VISIBLE, 100, 100, 350, 200, 0, 0, 0, 0)
Static_Text = CreateWindow("STATIC", "There have been no clicks yet", WS_VISIBLE Or WS_CHILD Or WS_BORDER, 10, 30, 300, 20, Window_Main, 0, 0, 0)
Button_Click = CreateWindow("BUTTON", "Click me", WS_VISIBLE Or WS_CHILD, 100, 70, 100, 20, Window_Main, 0, 0, 0)

'Windows message loop:
Num_Click = 0
While GetMessage(@msg, Window_Main, 0, 0)
  TranslateMessage(@msg)
  DispatchMessage(@msg)
  Select Case msg.hwnd
    Case Button_Click
      If msg.message = WM_LBUTTONDOWN Then
        Num_Click = Num_Click + 1
        If Num_Click = 1 Then
          Text = "Button has been clicked once"
        Else
          Text = "Button has been clicked " + Str(Num_Click) + " times"
        End If
	SetWindowText(Static_Text, Text)
      End If
    Case Window_Main
      If msg.message = WM_COMMAND Then End
  End Select
Wend

End


_window = 1

begin enum 1
  _label
  _clickMeBtn
end enum

void local fn BuildWindow
  window _window, @"Simple Windowed Application", (0,0,366,59)

  textlabel _label, @"There have been no clicks yet", (18,23,250,16)

  button _clickMeBtn,,, @"Click Me", (267,13,86,32)
end fn

void local fn ButtonClicked
  static long clickCount = 0

  clickCount++
  textlabel _label, fn StringWithFormat( @"The button has been clicked %ld times", clickCount )
end fn

void local fn DoDialog( ev as long, tag as long )
  select ( ev )
    case _btnClick
      select ( tag )
        case _clickMeBtn : fn ButtonClicked
      end select
  end select
end fn

fn BuildWindow

on dialog fn DoDialog

HandleEvents


iCount As Integer                                                 'Counter of clicks!
hLabel As Label                                                   'We need a Label

Public Sub Form_Open()
Dim hButton As Button                                             'We need a Button

With Me                                                           'Set the Form's Properties..
  .height = 75                                                    'Set the Height
  .Width = 300                                                    'Set the Width
  .Arrangement = Arrange.Vertical                                 'Arrange items vertically
  .Padding = 5                                                    'Border area
  .Title = "Click counter!"                                       'Title displayed on the Form
End With

hlabel = New Label(Me)                                            'Add a Label to the form

With hlabel                                                       'Set the Label's Properties..
  .expand = True                                                  'Expand the Label to fit the Form
  .Text = "There have been no clicks yet"                         'Add Text to the Label
  .Alignment = Align.Center                                       'Center the Text
End With

hButton = New Button(Me) As "Button1"                             'Add a Button to the form as Event "Button1"

With hButton                                                      'Set the Button's Properties..
  .Height = 28                                                    'Set the Height
  .Text = "&Click me"                                             'Add Text (The '&' adds a keyboard shortcut)
End With

End

Public Sub Button1_Click()                                        'When the Button is clicked..

Inc iCount                                                        'Increase the value of iCount
hLabel.text = "The button has been clicked " & iCount & " times"  'Display the amount of clicks"

End


#javaj#

   <frames> main, Simple click counter

   <layout of main>
      PANEL, X
      bClick me, lClicks

#data#

   <NN> 0
   <lClicks> //There have been no clicks yet

#listix#

   <-- bClick me>
      NUM=, NN, NN+1
      -->, lClicks data!,, //@<NN> clicks so far


package main

import (
    "fmt"
    "github.com/mattn/go-gtk/gtk"
)

func main() {
    gtk.Init(nil)
    window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
    window.SetTitle("Click me")
    label := gtk.NewLabel("There have been no clicks yet")
    var clicks int
    button := gtk.NewButtonWithLabel("click me")
    button.Clicked(func() {
        clicks++
        if clicks == 1 {
            label.SetLabel("Button clicked 1 time")
        } else {
            label.SetLabel(fmt.Sprintf("Button clicked %d times",
                clicks))
        }
    })
    vbox := gtk.NewVBox(false, 1)
    vbox.Add(label)
    vbox.Add(button)
    window.Add(vbox)
    window.Connect("destroy", func() {
        gtk.MainQuit()
    })
    window.ShowAll()
    gtk.Main()
}


import groovy.swing.SwingBuilder

count = 0
new SwingBuilder().edt {
  frame(title:'Click frame', pack: true, show: true) {
    vbox {
      countLabel = label("There have been no clicks yet.")
      button('Click Me', actionPerformed: {count++; countLabel.text = "Clicked ${count} time(s)."})
    }
  }
}


import Graphics.UI.Gtk
import Data.IORef

main :: IO ()
main = do
  initGUI
  window <- windowNew
  window `onDestroy` mainQuit
  windowSetTitle window "Simple Windowed App"
  set window [ containerBorderWidth := 10 ]

  hbox <- hBoxNew True 5

  set window [ containerChild := hbox ]

  lab <- labelNew (Just "There have been no clicks yet")
  button <- buttonNewWithLabel "Click me"
  set hbox [ containerChild := lab ]
  set hbox [ containerChild := button ]

  m <- newIORef 0

  onClicked button $ do
    v <- readIORef m
    writeIORef m (v+1)
    set lab [ labelText := "There have been " ++ show (v+1) ++ " clicks" ]

  widgetShowAll window

  mainGUI


 CHARACTER label="There have been no clicks yet"

    DO count = 1, 1E100 ! "forever"
      DLG(Button="Click me", Width=3, TItle=label) ! Width=3 to display full length label
      label = "Clicked " // count // "time(s)"
    ENDDO

 END


import gui
$include "guih.icn"

procedure main()
   SimpleWindow().show_modal()
end

class SimpleWindow : Dialog(label, button, count)
   method component_setup()
      self.set_attribs("size=222,139")
      label := Label()
      label.set_pos("24", "24")
      label.set_internal_alignment("l")
      label.set_label("There have been no clicks yet.")
      self.add(label)
      button := TextButton()
      button.set_pos(24, 53)
      button.set_label("click me")
      button.set_internal_alignment("c")
      button.connect(self, "incr", ACTION_EVENT)
      self.add(button)
   end

   method incr()
       /count := 0
       label.set_label("There have been "||(count+:=1)||" clicks.")
    end

   initially
      self.Dialog.initially()
end


pro counter, ev
  widget_control, ev.top, get_uvalue=tst
  tst[1] = tst[1]+1
  widget_control, tst[0], set_value="Number of clicks: "+string(tst[1],format='(i0)')
  widget_control, ev.top, set_uvalue=tst
end

id = widget_base(title = 'Window Title',column=1)
ld = widget_label(id, value = 'There have been no clicks yet.')
widget_control, /realize, id, set_uvalue=[ld,0]
dummy = widget_button(id,value=' Click Me ',event_pro='counter')
xmanager, "Simple", Id

end


SIMPLEAPP=: noun define
pc simpleApp;
cc inc button;cn "Click me";
cc shownText static;cn "There have been no clicks yet.";
)

simpleApp_run=: verb define
  wd SIMPLEAPP
  simpleApp_accum=: 0   NB. initialize accumulator
  wd 'pshow;'
)

simpleApp_inc_button=: verb define
  wd 'set shownText text ','Button-use count:  ',": simpleApp_accum=: >: simpleApp_accum
)

simpleApp_close=: wd bind 'pclose'
simpleApp_cancel=: simpleApp_close

simpleApp_run''


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class Clicks extends JFrame{
	private long clicks = 0;

	public Clicks(){
		super("Clicks");//set window title
		JLabel label = new JLabel("There have been no clicks yet");
		JButton clicker = new JButton("click me");
		clicker.addActionListener(//listen to the button
			new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					label.setText("There have been " + (++clicks) + " clicks");//change the text
				}
			}
		);
		setLayout(new BorderLayout());//handles placement of components
		add(label,BorderLayout.CENTER);//add the label to the biggest section
		add(clicker,BorderLayout.SOUTH);//put the button underneath it
		label.setPreferredSize(new Dimension(300,100));//nice big label
		label.setHorizontalAlignment(JLabel.CENTER);//text not up against the side
		pack();//fix layout
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//stop the program on "X"
		setVisible(true);//show it
	}
	public static void main(String[] args){
		SwingUtilities.invokeLater( //Swing UI updates should not happen on the main thread
			() -> new Clicks() //call the constructor where all the magic happens
		);
	}
}


import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;

Stage {
   scene: Scene {
      width: 300 height: 200
      content: VBox {
         var clicks: Integer;

         spacing: 10
         content: [
            Label {
               def varText = bind if (clicks == 0) then "no clicks yet" else "{clicks} clicks"
               text : bind "There have been {varText}"
            }
            Button {
               text: "click me"
               onMouseClicked: function(e) { clicks++; }
            }
         ]
      }
   }
}


    <title>Simple Window Application</title>

 &nbsp &nbsp &nbsp &nbsp

    <button type="button" onclick="count_clicks()"> Click me</button>

    Clicks: 0


using Gtk.ShortNames

function clickwindow()
    clicks = 0
    win = Window("Click Counter", 300, 100) |> (Frame() |> (vbox = Box(:v)))
    lab = Label("There have been no clicks yet.")
    but = Button("click me")
    push!(vbox, lab)
    push!(vbox, but)
    set_gtk_property!(vbox, :expand, lab, true)
    set_gtk_property!(vbox, :spacing, 20)
    callback(w) = (clicks += 1; set_gtk_property!(lab, :label, "There have been $clicks button clicks."))
    id = signal_connect(callback, but, :clicked)
    Gtk.showall(win)
    c = Condition()
    endit(w) = notify(c)
    signal_connect(endit, win, :destroy)
    wait(c)
end

clickwindow()


// version 1.0.6

import java.awt.BorderLayout
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.*

class Clicks : JFrame(), ActionListener {
    private var clicks = 0
    private val label: JLabel
    private val clicker: JButton
    private var text: String

    init {
        text = "There have been no clicks yet"
        label = JLabel(text)
        clicker = JButton("click me")
        clicker.addActionListener(this)        // listen to the button
        layout = BorderLayout()                // handles placement of components
        add(label, BorderLayout.CENTER)        // add the label to the biggest section
        add(clicker, BorderLayout.SOUTH)       // put the button underneath it
        setSize(300, 200)                       // stretch out the window
        defaultCloseOperation = EXIT_ON_CLOSE  // stop the program on "X"
        isVisible = true                       // show it
    }

    override fun actionPerformed(arg0: ActionEvent) {
        if (arg0.source == clicker) {           // if they clicked the button
            if (clicks == 0) text = "There has been " + (++clicks) + " click"
            else text = "There have been " + (++clicks) + " clicks"
            label.text = text                  // change the text
        }
    }
}

fun main(args: Array<String>) {
    Clicks()  // call the constructor where all the magic happens
}


1) the label: {div {@ id="label"} There have been no clicks yet }
2) the button: {input {@ type="button" value="click me" onclick="CLICKAPP.inc()" }}
3) the script: {script °° code °°} where code is a single function:

var CLICKAPP = (function() {
  var counter = 0;
  var inc = function() {
      counter++;
      getId('label').innerHTML =
      'There are ' + counter + ' clicks now';
  };
  return {inc:inc}
})();


nomainwin
    button #demo.btn, "Click Me", [btnClick], UL, 20, 50
    statictext #demo.num, "There have been no clicks yet.", 20, 100, 240, 30
    open "Rosetta Task: Simple windowed application" for window as #demo
    #demo "trapclose [quit]"
    nClicks = 0
wait

[quit]
    close #demo
end

[btnClick]
    nClicks = nClicks + 1
    #demo.num "The button has been clicked ";nClicks;" times."
wait


on startMovie

  -- window settings
  _movie.stage.title = "Hello World!"
  _movie.stage.titlebarOptions.visible = TRUE
  _movie.stage.rect = rect(0,0,320, 240)
  _movie.centerStage = 1

  -- create a label (called "field" in Director)
  m = new(#field)
  m.name = "label"
  m.rect = rect(0,0,320,0)
  m.text = "There have been no clicks yet"
  m.alignment = "center"

  -- create sprite, assign field
  _movie.puppetSprite(1, TRUE)
  sprite(1).member = m
  sprite(1).loc = point(0,80)

  -- create a button
  m = new(#button)
  m.rect = rect(0,0,220,0)
  m.text = "click me"
  m.alignment = "center"

  -- create sprite, assign button
  _movie.puppetSprite(2, TRUE)
  sprite(2).member = m
  sprite(2).loc = point(50,105)

  -- create new script at runtime, assign it to button sprite
  m = new(#script)
  m.scriptType = #score
  m.scriptText = "on mouseDown"&RETURN&\
  "  m=member("&QUOTE&"label"&QUOTE&")"&RETURN&\
  "  m.text=string(integer(m.text)+1)"&RETURN&\
  "end"
  sprite(2).scriptInstanceList.add(m.script.new())

  -- force immediate update
  _movie.updateStage()

  -- show the window
  _movie.stage.visible = 1

end


global count
on openCard
   put empty into count
   put "There have been no clicks yet" into field "clicks"
end openCard
on mouseUp
   add 1 to count
   put count into field "clicks"
end mouseUp


to clickwindow
windowCreate "root "clickWin [Click that button!!!] 0 0 100 100 []
Make "i 0
staticCreate "clickWin "clickSt [There have been no clicks yet] 0 0 100 20
buttonCreate "clickWin "clickBtn [click me] 10 20 80 20 ~
	[Make "i :i+1 ~
	ifelse :i=1 [staticUpdate "clickSt (list "clicked :i "time)] ~
	            [staticUpdate "clickSt (list "clicked :i "times)]]
end


require"iuplua"
l = iup.label{title="There have been no clicks yet."}
b = iup.button{title="Click me!"}
clicks = 0
function b:button_cb()
  clicks = clicks + 1
  l.title = "There have been " .. clicks/2 .. " clicks so far." --yes, this is correct.
end
dlg = iup.dialog{iup.vbox{l, b}, title="Simple Windowed Application"}
dlg:show()

if (not iup.MainLoopLevel or iup.MainLoopLevel()==0) then
  iup.MainLoop()
end


Module CheckIt {
      Declare Form1  Form
      Declare Label1 Button Form Form1
      Declare Button1 Button Form Form1
      Method Label1,"move", 2000, 2000, 4000, 600
      Method Button1,"move", 2000, 3000, 4000, 600
      With Label1, "Caption" as caption$, "Locked", true, "Caption" as cap
      With Button1, "Caption", "click me", "Default", True   ' make this the default control
      caption$="There have been no clicks yet"
      m=0
      Function Button1.Click {
                  m++
                  cap=m
      }
      Method Form1, "Show",1
      Declare Form1 Nothing
}
Checkit


DynamicModule[{n = 0},
 CreateDialog[{[email protected]
    [email protected][n == 0, "There have been no clicks yet", n],
   Button["click me", n++]}]]


rollout buttonClick "Button Click"
(
    label l "There have been no clicks yet"
    button clickMe "Click me"
    local clickCount = 0

    on clickMe pressed do
    (
        clickCount += 1
        l.text = ("Number of clicks: " + clickCount as string)
    )
)
createDialog buttonClick


MODULE Click EXPORTS Main;

IMPORT Fmt, TextVBT, ButtonVBT, VBT, Axis, HVSplit, TrestleComm, Trestle;

VAR label := TextVBT.New("There have been no clicks yet.");
    button := ButtonVBT.New(TextVBT.New("Click me!"), Clicked);
    main := HVSplit.Cons(Axis.T.Ver, label, button, adjustable := FALSE);
    count := 0;

PROCEDURE Clicked(<*UNUSED*>button: ButtonVBT.T; <*UNUSED*>READONLY cd: VBT.MouseRec) =
  BEGIN
    INC(count);
    TextVBT.Put(label, "Button pressed: " & Fmt.Int(count));
  END Clicked;

<*FATAL TrestleComm.Failure*>
BEGIN
  Trestle.Install(main);
  Trestle.AwaitDelete(main);
END Click.


import Nanoquery.Util.Windows

// define the necessary objects
$w = new("Window")
$b = new("Button")
$l = new("Label")

$b.setParent($w)
$l.setParent($w)

// define the amount of clicks
$clicks = 0

// a function to update the label
def updateLabel($caller, $event)
        global $clicks
        global $l

        $clicks = $clicks+1
        $l.setText(str($clicks))

        global $clicks = $clicks
end

// prepare the components to be displayed
$w.setSize(200,200)
$b.setText("click me")
$b.setPosition(0,100)
$l.setText("There have been no clicks yet")

// set the button's event handler to the function updateLabel
$b.setHandler($updateLabel)

// show the window
$w.show()


import gtk2

nim_init()

var
  win = windowNew WINDOW_TOPLEVEL
  button = buttonNew "Click me"
  label = labelNew  "There have been no clicks yet"
  vbox = vboxNew(true, 1)
  counter = 0

proc clickedMe(o: var PButton, l: PLabel) =
  inc counter
  l.setText "You clicked me " & $counter & " times"

win.setTitle "Click me"
vbox.add label
vbox.add button
win.add vbox
discard win.signal_connect("delete-event", SignalFunc mainQuit, nil)
discard button.signal_connect("clicked", SignalFunc clickedMe, label)
win.showAll()
main()


#include <Foundation/Foundation.h>
#include <AppKit/AppKit.h>

@interface ClickMe : NSWindow
{
  NSButton *_button;
  NSTextField *_text;
  int _counter;
}
- (void)applicationDidFinishLaunching: (NSNotification *)notification;
- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification;
- (void)advanceCounter: (id)sender;
@end


#directory "+labltk"
#load "labltk.cma"

let () =
  let top = Tk.openTk() in
  Wm.title_set top "Tk-OCaml Example";
  let label = Label.create ~text:"There have been no clicks yet" top in
  let b =
    Button.create
        ~text:"click me"
        ~command:(fun () -> Tk.closeTk (); exit 0)
        top
  in
  Tk.pack [Tk.coe label; Tk.coe b];
  Tk.mainLoop ();
;;


/* REXX ***************************************************************************************
* 18.06.2014 Walter Pachl shortened from Rony Flatscher's bsf4oorexx (see sourceforge) samples
* Look there for ShowCount.rxj
* bsf4oorexx lets the ooRexx program use Java classes
**********************************************************************************************/
userData=.directory~new    -- a directory which will be passed to Rexx with the event

   --  create a framed Java window, set a title text
win=.bsf~new("java.awt.Frame", "Show Count")
   -- Create a Java RexxProxy for controlling the closing of the application
rexxCloseEH =.RexxCloseAppEventHandler~new   -- Rexx event handler
   -- Create Java RexxProxy for the Rexx event handler
rpCloseEH=BsfCreateRexxProxy(rexxCloseEH,,"java.awt.event.WindowListener" )
win~addWindowListener(rpCloseEH) -- add RexxProxy event handler

   -- create a Java push button
but=.bsf~new("java.awt.Button","Press me!")
   -- Create a RexxProxy for the button Rexx event handler
rp=BsfCreateRexxProxy(.RexxShowCountEventHandler~new,userData,"java.awt.event.ActionListener")
but~addActionListener(rp)        -- add RexxProxy event handler

lab=.bsf~new("java.awt.Label")   -- create a Java label,set it to show the text centered
userData~label=lab               -- save label object for later use in event handler
lab~setAlignment(lab~center)     -- set alignment to center
lab~setText("Button was not yet pressed") -- assign initial text to the label

win ~~add("Center",lab) ~~add("South",but) -- add the label and the button to the frame
win ~~pack                       -- now calculate all widget dimensions
call enlargeWidth win,but,120    -- enlarge the width of the frame and the button

win ~~setVisible(.true) ~~toFront   -- make frame visible and move it to the front

userData~i=0                     -- set counter to 0

rexxCloseEH~waitForExit          -- wait until we are allowed to end the program

-- if Java was loaded by Rexx,then terminate Java's RexxEngine to inhibit callbacks from Java
call BSF.terminateRexxEngine

::requires BSF.CLS      -- get Java support

   /* enlarge the width of the frame and of the button without using a layout manager  */
::routine enlargeWidth
  use arg win,but,addToWidth
  winDim=win~getSize            -- get frame's dimension
  winDim~width+=addToWidth      -- increase width
  win~setSize(winDim)           -- set frame's dimension

/* ------------------------------------------------------------------------ */
/* Rexx event handler to set "close app" indicator */
::class RexxCloseAppEventHandler
::method init                   -- constructor
  expose closeApp
  closeApp  = .false            -- if set to .true, then it is safe to close the app

::attribute closeApp            -- indicates whether app should be closed

::method unknown                -- intercept unhandled events,do nothing

::method windowClosing          -- event method (from WindowListener)
  expose closeApp
  closeApp=.true                -- indicate that the app should close

::method waitForExit            -- method blocks until attribute is set to .true
  expose closeApp
  guard on when closeApp=.true

/* ------------------------------------------------------------------------ */
/* Rexx event handler to process tab changes */
::class RexxShowCountEventHandler
::method actionPerformed
  use arg eventObject,slotDir
  call showCount slotDir~userData

/* ------------------------------------------------------------------------ */
::routine ShowCount             -- increment counter and show text
   use arg userData
   userData~i+=1                -- increment counter in directory object
   Select                       -- construct text part
     When userData~i=1 Then how_often='once'
     When userData~i=2 Then how_often='twice'
     When userData~i=3 Then how_often='three times'
     Otherwise how_often=userData~i 'times'
   End
   userData~label~setText("Button was pressed" how_often) -- display text


functor
import
   Application
   QTk at 'x-oz://system/wp/QTk.ozf'
define
   Count = {NewCell 0}
   Label
   GUI = td(action:proc {$} {Application.exit 0} end %% exit on close
	    label(text:"There have been no clicks yet." handle:Label)
	    button(text:"Click Me"
		   action:proc {$}
			     Count := @Count + 1
			     {Label set(text:"Number of clicks: "#@Count#".")}
			  end
		  ))
   Window = {QTk.build GUI}
   {Window show}
end


Program SimpleWindowApplication;

uses
  SysUtils,
  glib2,
  Gtk2;

const
  clickme = 'Click Me';
  MAXLEN = 64;

var
  counter: integer = 0;

procedure clickedme(o: PGtkButton; d: pointer); cdecl;
  var
    nt: Pchar;
    l: PGtkLabel;
  begin
    l := Gtk_LABEL(d);
    inc(counter);
    nt := Pchar('You clicked me ' + inttostr(counter) + ' times');
    Gtk_label_set_text(l, nt);
  end;

var
  win:     PGtkWindow;
  button:  PGtkButton;
  Mylabel: PGtkLabel;
  vbox:    PGtkVBox;

begin
  Gtk_init(@argc, @argv);
  win := PGtkWindow(Gtk_window_new(Gtk_WINDOW_TOPLEVEL));
  Gtk_window_set_title(win, clickme);
  button := PGtkButton(Gtk_button_new_with_label(clickme));
  Mylabel := PGtkLabel(Gtk_label_new('There have been no clicks yet'));
  Gtk_label_set_single_line_mode(Mylabel, TRUE);
  vbox := PGtkVBox(Gtk_vbox_new(TRUE, 1));
  Gtk_container_add(Gtk_CONTAINER(vbox), Gtk_WIDGET(Mylabel));
  Gtk_container_add(Gtk_CONTAINER(vbox), Gtk_WIDGET(button));
  Gtk_container_add(Gtk_CONTAINER(win), Gtk_WIDGET(vbox));
  g_signal_connect(G_OBJECT(win), 'delete-event', TGCallBack(@Gtk_main_quit), NULL);
  g_signal_connect(G_OBJECT(button), 'clicked', TGCallBack(@clickedme), Mylabel);
  Gtk_widget_show_all(Gtk_WIDGET(win));
  Gtk_main();
end.


use Tk;

$main = MainWindow->new;
$l = $main->Label('-text' => 'There have been no clicks yet.')->pack;
$count = 0;
$main->Button(
  -text => ' Click Me ',
  -command => sub { $l->configure(-text => 'Number of clicks: '.(++$count).'.'); },
)->pack;
MainLoop();


-- demo\rosetta\Simple_window.exw
with javascript_semantics
include pGUI.e

Ihandle dlg, lbl, btn, vbox
integer clicks = 0

function click_cb(Ihandle /*btn*/)
    clicks += 1
    IupSetStrAttribute(lbl,"TITLE","clicked %d times",{clicks})
    return IUP_DEFAULT;
end function

IupOpen()
lbl = IupLabel("There have been no clicks yet")
btn = IupButton("Click me", Icallback("click_cb"))
vbox = IupVbox({lbl, IupHbox({IupFill(),btn,IupFill()})})
dlg = IupDialog(vbox,"MARGIN=10x10, GAP=10, RASTERSIZE=400x0")
IupSetAttribute(dlg, "TITLE", "Simple windowed application")
IupShow(dlg)
if platform()!=JS then
    IupMainLoop()
    IupClose()
end if


#!/usr/bin/picolisp /usr/lib/picolisp/lib.l

(load "@ext.l" "@lib/http.l" "@lib/xhtml.l" "@lib/form.l")

(zero *Count)

(de start ()
   (app)
   (action
      (html 0 "Clicks" NIL NIL
         (form NIL
            (gui '(+Init +TextField) "There have been no clicks yet")
            (----)
            (gui '(+JS +Button) "click me"
               '(set> (field -1)
                  (pack "Clicked " (inc '*Count) " times") ) ) ) ) ) )

(server 8080 "!start")
(wait)


GTK2.Widget mainwindow,clickcnt,clicker;
int clicks;

void click()
{
        clickcnt->set_text("Clicks: "+(++clicks));
}

int main()
{
        GTK2.setup_gtk();
        mainwindow=GTK2.Window(GTK2.WindowToplevel);
        mainwindow->set_title("Click counter");
        mainwindow->add(GTK2.Vbox(0,10)
                ->add(clickcnt=GTK2.Label("There have been no clicks yet"))
                ->add(clicker=GTK2.Button("Click me"))
        )->show_all();
        mainwindow->signal_connect("delete_event",lambda() {exit(0);});
        clicker->signal_connect("clicked",click);
        return -1;
}


$Label1  = [System.Windows.Forms.Label]@{
            Text = 'There have been no clicks yet'
            Size = '200, 20' }
$Button1 = [System.Windows.Forms.Button]@{
            Text = 'Click me'
            Location = '0, 20' }

$Button1.Add_Click(
    {
    $Script:Clicks++
    If ( $Clicks -eq 1 ) { $Label1.Text = "There has been 1 click" }
    Else                 { $Label1.Text = "There have been $Clicks clicks" }
    } )

$Form1 = New-Object System.Windows.Forms.Form
$Form1.Controls.AddRange( @( $Label1, $Button1 ) )

$Clicks = 0

$Result = $Form1.ShowDialog()


:- dynamic click/1.

dialog('Simple windowed application',
       [ object        :=
	   Simple_windowed_application,
	 parts         :=
	   [ Simple_windowed_application :=
	       dialog('Simple windowed application'),
	     Name                       :=
	       label(name, 'There have been no clicks yet'),
	     BtnClick                     :=
	       button(button)
	   ],
	 modifications :=
	   [ BtnClick := [ label := 'Click me !'
		       ]
	   ],
	 layout        :=
	   [ area(Name,
		  area(40, 20, 200, 18)),
	     area(BtnClick,
		  area(90, 60, 80, 24))
	   ],
	 behaviour :=
	 [
	  BtnClick := [message := message(@prolog, btnclick, Name)]
	 ]
       ]).

btnclick(Label) :-
	retract(click(V)),
	V1 is V+1,
	assert(click(V1)),
	sformat(A, '~w click(s)', [V1]),
	send(Label, selection, A).

simple_windowed :-
	retractall(click(_)),
	assert(click(0)),
	make_dialog(D, 'Simple windowed application'),
	send(D, open).


Define window_0
Define window_0_Text_0, window_0_Button_1
Define clicks, txt$, flags

flags = #PB_Window_SystemMenu | #PB_Window_SizeGadget | #PB_Window_ScreenCentered
window_0 = OpenWindow(#PB_Any, 408, 104, 280, 45, "Simple windowed application", flags)
If window_0
  SmartWindowRefresh(window_0, #True)
  window_0_Text_0 = TextGadget(#PB_Any, 5, 5, 165, 20, "There have been no clicks yet")
  window_0_Button_1 = ButtonGadget(#PB_Any, 190, 10, 85, 30, "Click me")

  Repeat
    Select WaitWindowEvent()
      Case #PB_Event_Gadget
        Select EventGadget()
          Case window_0_Text_0
          Case window_0_Button_1
            clicks + 1
            txt$ = "You Clicked " + Str(clicks) + " time"
            If clicks > 1: txt$ + "s": EndIf
            SetGadgetText(window_0_Text_0, txt$)
        EndSelect
      Case #PB_Event_CloseWindow
        End
    EndSelect
  ForEver
EndIf


from functools import partial
import tkinter as tk

def on_click(label: tk.Label,
             counter: tk.IntVar) -> None:
    counter.set(counter.get() + 1)
    label["text"] = f"Number of clicks: {counter.get()}"

def main():
    window = tk.Tk()
    window.geometry("200x50+100+100")
    label = tk.Label(master=window,
                     text="There have been no clicks yet")
    label.pack()
    counter = tk.IntVar()
    update_counter = partial(on_click,
                             label=label,
                             counter=counter)
    button = tk.Button(master=window,
                       text="click me",
                       command=update_counter)
    button.pack()
    window.mainloop()

if __name__ == '__main__':
    main()


library(gWidgets)
library(gWidgetstcltk)
win <- gwindow()
lab <- glabel("There have been no clicks yet", container=win)
btn <- gbutton("click me", container=win, handle=function(h, ...)
   {
      val <- as.numeric(svalue(lab))
      svalue(lab) <- ifelse(is.na(val) ,"1", as.character(val + 1))
   }
)


#lang racket/gui

(define frame (new frame% [label "There have been no clicks yet"]))

(define num-clicks 0)
(define (cb obj me)
  (set! num-clicks (add1 num-clicks))
  (send frame set-label (format "~a" num-clicks)))

(new button% [parent frame] [label "Click me"] [callback cb])
(send frame show #t)


use GTK::Simple;
use GTK::Simple::App;

my GTK::Simple::App $app .= new(title => 'Simple Windowed Application');

$app.size-request(350, 100);

$app.set-content(
    GTK::Simple::VBox.new(
        my $label  = GTK::Simple::Label.new( text  => 'There have been no clicks yet'),
        my $button = GTK::Simple::Button.new(label => 'click me'),
    )
);

$app.border-width = 40;

$button.clicked.tap: {
    state $clicks += 1;
    $label.text = "There has been $clicks click{ 's' if $clicks != 1 }";
}

$app.run;


V sqrt3_2 = sqrt(3) / 2

F sierpinski_arrowhead_next(points)
   V result = [(0.0, 0.0)] * (3 * (points.len - 1) + 1)
   V j = 0
   L(i) 0 .< points.len - 1
      V (x0, y0) = points[i]
      V (x1, y1) = points[i + 1]
      V dx = x1 - x0
      result[j] = (x0, y0)
      I y0 == y1
         V d = abs(dx * :sqrt3_2 / 2)
         result[j + 1] = (x0 + dx / 4, y0 - d)
         result[j + 2] = (x1 - dx / 4, y0 - d)
      E I y1 < y0
         result[j + 1] = (x1, y0)
         result[j + 2] = (x1 + dx / 2, (y0 + y1) / 2)
      E
         result[j + 1] = (x0 - dx / 2, (y0 + y1) / 2)
         result[j + 2] = (x0, y1)
      j += 3
   result[j] = points.last
   R result

V size = 600
V iterations = 8
V outfile = File(‘sierpinski_arrowhead.svg’, ‘w’)

outfile.write(‘<svg xmlns='http://www.w3.org/2000/svg' width='’size‘' height='’size"'>\n")
outfile.write("<rect width='100%' height='100%' fill='white'/>\n")
outfile.write(‘<path stroke-width='1' stroke='black' fill='none' d='’)
V margin = 20.0
V side = size - 2 * margin
V x = margin
V y = 0.5 * size + 0.5 * sqrt3_2 * side
V points = [(x, y), (x + side, y)]
L 0 .< iterations
   points = sierpinski_arrowhead_next(points)
L(point) points
   outfile.write(I L.index == 0 {‘M’} E ‘L’)
   outfile.write(point.x‘,’point.y"\n")
outfile.write("'/>\n</svg>\n")


DECLARE SUB buttonClick

CREATE form AS QForm
    Center
    Height = 120
    Width = 300

    CREATE text AS QLabel
        Caption = "There have been no clicks yet."
        Left = 30: Top = 20
    END CREATE

    CREATE button1 AS QButton
        Caption = "Click me"
        Left = 100: Top = 50: Height = 25: Width = 100
        OnClick = buttonClick
    END CREATE
END CREATE

SUB buttonClick
    STATIC count AS Integer
    count = count+1
    text.Caption = "Clicked " + STR$(count) + " times."
END SUB

form.ShowModal


rebol [
	Title: "Simple Windowed Application"
	URL: http://rosettacode.org/wiki/Simple_Windowed_Application
]

clicks: 0

; Simple GUI's in REBOL can be defined with 'layout', a
; special-purpose language (dialect, in REBOL-speak) for specifying
; interfaces. In the example below, I describe a gradient background
; with a text label and a button. The block in the button section
; details what should happen when it's clicked on -- increment the
; number of clicks and update the label text.

; The 'view' function paints the layout on the screen and listens for
; events.

view layout [
	backdrop effect [gradient 0x1 black coal]

	label: vtext "There have been no clicks yet."

	button maroon "click me" [
		clicks: clicks + 1
		set-face label reform ["clicks:" clicks]
	]
]


Red[]

clicks: 0

view [
    t: text "There have been no clicks yet" return
    button "click me" [
        clicks: clicks + 1
        t/data: rejoin ["clicks: " clicks]
    ]
]


Load "guilib.ring"

MyApp = New qApp {
        num = 0
        win1 = new qWidget() {
               setwindowtitle("Hello World")
               setGeometry(100,100,370,250)

               btn1 = new qpushbutton(win1) {
                    setGeometry(150,200,100,30)
                    settext("click me")
                    setclickevent("clickme()")}

                    Lineedit1 = new qlineedit(win1) {
                                setGeometry(10,100,350,30)}
        show()}
        Exec()}

func clickme
     num += 1
     lineedit1.settext( "you clicked me " + num + " times")


require 'tk'
str = TkVariable.new("no clicks yet")
count = 0
root = TkRoot.new
TkLabel.new(root, "textvariable" => str).pack
TkButton.new(root) do
  text "click me"
  command {str.value = count += 1}
  pack
end
Tk.mainloop


with Ada.Command_Line;
with Ada.Numerics.Generic_Elementary_Functions;
with Ada.Text_IO;
with PDF_Out;

procedure Arrowhead_Curve is

   package Real_Math is
     new Ada.Numerics.Generic_Elementary_Functions (PDF_Out.Real);
   use Real_Math, PDF_Out, Ada.Command_Line, Ada.Text_IO;

   subtype Angle_Deg  is Real;
   type    Order_Type is range 0 .. 7;

   Purple : constant Color_Type := (0.7, 0.0, 0.5);
   Length : constant Real       := 340.0;
   Corner : constant Point      := (120.0, 480.0);

   Order     : Order_Type;
   Current   : Point      := (0.0, 0.0);
   Direction : Angle_Deg  := Angle_Deg'(0.0);
   Doc       : PDF_Out_File;

   procedure Curve (Order : Order_Type; Length : Real; Angle : Angle_Deg) is
   begin
      if Order = 0 then
         Current := Current + Length * Point'(Cos (Direction, 360.0),
                                              Sin (Direction, 360.0));
         Doc.Line (Corner + Current);
      else
         Curve (Order - 1, Length / 2.0, -Angle);  Direction := Direction + Angle;
         Curve (Order - 1, Length / 2.0,  Angle);  Direction := Direction + Angle;
         Curve (Order - 1, Length / 2.0, -Angle);
      end if;
   end Curve;

begin
   if Argument_Count /= 1 then
      Put_Line ("arrowhead_curve <order>");
      Put_Line ("  <order>   0 .. 7");
      Put_Line ("open sierpinski-arrowhead-curve.pdf to view ouput");
      return;
   end if;
   Order := Order_Type'Value (Argument (1));

   Doc.Create ("sierpinski-arrowhead-curve.pdf");
   Doc.Page_Setup (A4_Portrait);
   Doc.Margins (Margins_Type'(Left   => Cm_2_5,
                              others => One_cm));
   Doc.Stroking_Color (Purple);
   Doc.Line_Width (2.0);
   Doc.Move (Corner);
   if Order mod 2 = 0 then
      Direction := 0.0;
      Curve (Order, Length, 60.0);
   else
      Direction := 60.0;
      Curve (Order, Length, -60.0);
   end if;
   Doc.Finish_Path (Close_Path => False,
                    Rendering  => Stroke,
                    Rule       => Nonzero_Winding_Number);
   Doc.Close;
end Arrowhead_Curve;