import "io" for Stdin, Stdout
import "/str" for Char

var hle
var lowest = 1
var highest = 20
var guess = 10
System.print("Please choose a number between 1 and 20 but don't tell me what it is yet\n")

while (true) {
    System.print("My guess is %(guess)")
    while (true) {
        System.write("Is this higher/lower than or equal to your chosen number h/l/e : ")
        Stdout.flush()
        hle = Char.lower(Stdin.readLine())
        if (hle == "l" && guess == highest) {
            System.print("It can't be more than %(highest), try again")
            hle = "i" // signifies invalid
        } else if (hle == "h" && guess == lowest) {
            System.print("It can't be less than %(lowest), try again")
            hle  = "i"
        }
        if ("hle".contains(hle)) break
    }
    if (hle == "e") {
        System.print("Good, thanks for playing the game with me!")
        break
    }
    if (hle == "h") {
        if (highest > guess - 1) highest = guess - 1
    } else {
        if (lowest < guess + 1) lowest = guess + 1
    }
    guess = ((lowest + highest)/2).floor
}


include c:\cxpl\codes;  \intrinsic 'code' declarations
int Hi, Lo, Guess;
[Text(0, "Think of a number between 1 and 100 then press a key.");
if ChIn(1) then [];
Lo:= 1;  Hi:= 101;
loop    [Guess:= (Lo+Hi)/2;
        Text(0, "^M^JIs it ");  IntOut(0, Guess);
        Text(0, " (Y = yes, H = too high, L = too low)? ");
        case ChIn(1) of
          ^L,^l: Lo:= Guess;
          ^H,^h: Hi:= Guess;
          ^Y,^y: quit
        other   ChOut(0, 7\bel\);
        ];
Text(0, "^M^JYippee!");
]


println("Pick a number between 0 and 100 and remember it.");
low,high,g := 0,100, 20;
while(True){
   r:=ask("I guess %d; is that high, low or =? ".fmt(g)).strip().toLower();
   if(r=="="){ println("Yea!"); break; }
   if(r[0]=="h") high=g-1 else low=g+1;
   if(low==high){ println("Yea! the number is ",low); break; }
   if(low>high){ println("I'm confused!"); break; }
   g=(low + high)/2;
}


10 LET min=1: LET max=100
20 PRINT "Think of a number between ";min;" and ";max
30 PRINT "I will try to guess your number."
40 LET guess=INT ((min+max)/2)
50 PRINT "My guess is ";guess
60 INPUT "Is it higuer than, lower than or equal to your number? ";a$
65 LET a$=a$(1)
70 IF a$="L" OR a$="l" THEN LET min=guess+1: GO TO 40
80 IF a$="H" OR a$="h" THEN LET max=guess-1: GO TO 40
90 IF a$="E" OR a$="e" THEN PRINT "Goodbye.": STOP
100 PRINT "Sorry, I didn't understand your answer.": GO TO 60


&НаСервере
Процедура ДобавитьЭлементы()

	КЧ = Новый КвалификаторыЧисла(12,2);

	Массив = Новый Массив;
	Массив.Добавить(Тип("Число"));
	ОписаниеТиповЧ = Новый ОписаниеТипов(Массив, , ,КЧ);

	НовыйРеквизит = Новый РеквизитФормы("ВводимоеЧисло", Новый ОписаниеТипов(Массив, , ,КЧ));;

	МассивР = Новый Массив;
	МассивР.Добавить(НовыйРеквизит);
	ИзменитьРеквизиты(МассивР);

	ПолеВвода = Элементы.Добавить("ПолеВвода", Тип("ПолеФормы"));
	ПолеВвода.ПутьКДанным = "ВводимоеЧисло";
	ПолеВвода.вид = ВидПоляФормы.ПолеВвода;

	КомандаИнкримент = Команды.Добавить("Инкримент");
	КомандаРандом 	 = КОманды.Добавить("Рандом");

	КнопкаИнкримент = Элементы.Добавить("КнопкаИнкримент", Тип("КнопкаФормы"));
	КнопкаИнкримент.ИмяКоманды = "Инкримент";
	КнопкаРандом = Элементы.Добавить("КнопкаРандом", Тип("КнопкаФормы"));
	КнопкаРандом.ИмяКоманды = "Рандом";

	КомандаИнкримент.Действие = "Инкримент";
	КомандаРандом.Действие = "Рандом";

КонецПроцедуры

&НаКлиенте
Процедура Инкримент(Команда)

	ЭтотОбъект.ВводимоеЧисло = ЭтотОбъект.ВводимоеЧисло + 1;

КонецПроцедуры

&НаКлиенте
Процедура Рандом(Команда)

	ОписаниеОповещения = Новый ОписаниеОповещения("РандомПослеВыбора", ЭтотОбъект);

	ПоказатьВопрос(ОписаниеОповещения, "Установить случайное число?", РежимДиалогаВопрос.ДаНет);

КонецПроцедуры

&НаКлиенте
Процедура РандомПослеВыбора(РезультатВопроса, ДополнительныеПараметры) Экспорт

	Если РезультатВопроса = КодВозвратаДиалога.Да Тогда
		ГСЧ = Новый ГенераторСлучайныхЧисел();
		ЭтотОбъект.ВводимоеЧисло = ГСЧ.СлучайноеЧисло(0, 999999);
	КонецЕсли;

КонецПроцедуры


with Ada.Numerics.Discrete_Random;
with Ada.Strings.Fixed;
with Gtk.Main;
with Gtk.Handlers;
with Gtk.Button;
with Gtk.Window;
with Gtk.GEntry;
with Gtk.Editable;
with Gtk.Box;
with Gtk.Widget;
with Glib.Values;
with Gtkada.Dialogs;

procedure Interaction is

   The_Value : Natural := 0;

   package Natural_Random is new Ada.Numerics.Discrete_Random (Natural);
   RNG : Natural_Random.Generator;

   Main_Window      : Gtk.Window.Gtk_Window;
   Content          : Gtk.Box.Gtk_Vbox;
   Increment_Button : Gtk.Button.Gtk_Button;
   Random_Button    : Gtk.Button.Gtk_Button;
   Entry_Field      : Gtk.GEntry.Gtk_Entry;

   package Entry_Callbacks is new Gtk.Handlers.Callback
     (Gtk.GEntry.Gtk_Entry_Record);

   package Button_Callbacks is new Gtk.Handlers.Callback
     (Gtk.Button.Gtk_Button_Record);

   package Window_Callbacks is new Gtk.Handlers.Return_Callback
     (Gtk.Window.Gtk_Window_Record, Boolean);

   --  update displayed text
   procedure Update_Entry is
   begin
      Gtk.GEntry.Set_Text
        (The_Entry => Entry_Field,
         Text      =>
           Ada.Strings.Fixed.Trim
             (Source => Natural'Image (The_Value),
              Side   => Ada.Strings.Both));
   end Update_Entry;

   --  read from text entry
   procedure Update_Value is
   begin
      The_Value := Natural'Value (Gtk.GEntry.Get_Text (Entry_Field));
   exception
      when Constraint_Error =>
         The_Value := 0;
   end Update_Value;

   --  make sure that only numbers are entered
   procedure On_Insert_Text
     (Object : access Gtk.GEntry.Gtk_Entry_Record'Class;
      Params : Glib.Values.GValues)
   is
      Length : constant Glib.Gint :=
        Glib.Values.Get_Int (Glib.Values.Nth (Params, 2));
      Text   : constant String    :=
        Glib.Values.Get_String (Glib.Values.Nth (Params, 1), Length);
   begin
      declare
         Number : Natural;
      begin
         Number := Natural'Value (Text);
      exception
         when Constraint_Error =>
            --  refuse values that are not parsable
            Gtk.Handlers.Emit_Stop_By_Name
              (Object => Object,
               Name   => Gtk.Editable.Signal_Insert_Text);
      end;
   end On_Insert_Text;

   --  Callback for click event
   procedure On_Increment_Click
     (Object : access Gtk.Button.Gtk_Button_Record'Class)
   is
   begin
      Update_Value;
      The_Value := The_Value + 1;
      Update_Entry;
   end On_Increment_Click;

   --  Callback for click event
   procedure On_Random_Click
     (Object : access Gtk.Button.Gtk_Button_Record'Class)
   is
      use type Gtkada.Dialogs.Message_Dialog_Buttons;
   begin
      if Gtkada.Dialogs.Message_Dialog
        (Msg            => "Really reset to random value?",
         Dialog_Type    => Gtkada.Dialogs.Confirmation,
         Buttons        => Gtkada.Dialogs.Button_Yes or
           Gtkada.Dialogs.Button_No,
         Default_Button => Gtkada.Dialogs.Button_Yes) =
        Gtkada.Dialogs.Button_Yes
      then
         The_Value := Natural_Random.Random (RNG);
         Update_Entry;
      end if;
   end On_Random_Click;

   --  Callback for delete event
   function On_Main_Window_Delete
     (Object : access Gtk.Window.Gtk_Window_Record'Class)
      return   Boolean
   is
   begin
      Gtk.Main.Main_Quit;
      return True;
   end On_Main_Window_Delete;

begin
   --  initialize random number generator
   Natural_Random.Reset (RNG);

   Gtk.Main.Init;

   Gtk.GEntry.Gtk_New (Widget => Entry_Field);
   Update_Entry;
   Entry_Callbacks.Connect
     (Widget => Entry_Field,
      Name   => Gtk.Editable.Signal_Insert_Text,
      Cb     => On_Insert_Text'Access);

   Gtk.Button.Gtk_New (Button => Increment_Button, Label => "Increment");
   Gtk.Button.Gtk_New (Button => Random_Button, Label => "Random");

   Button_Callbacks.Connect
     (Widget => Increment_Button,
      Name   => Gtk.Button.Signal_Clicked,
      Marsh  => Button_Callbacks.To_Marshaller (On_Increment_Click'Access));
   Button_Callbacks.Connect
     (Widget => Random_Button,
      Name   => Gtk.Button.Signal_Clicked,
      Marsh  => Button_Callbacks.To_Marshaller (On_Random_Click'Access));

   Gtk.Box.Gtk_New_Vbox (Box => Content);
   Gtk.Box.Add (Container => Content, Widget => Entry_Field);
   Gtk.Box.Add (Container => Content, Widget => Increment_Button);
   Gtk.Box.Add (Container => Content, Widget => Random_Button);

   Gtk.Window.Gtk_New (Window => Main_Window);
   Gtk.Window.Add (Container => Main_Window, Widget => Content);

   Window_Callbacks.Connect
     (Widget => Main_Window,
      Name   => Gtk.Widget.Signal_Delete_Event,
      Cb     => On_Main_Window_Delete'Access);
   Gtk.Window.Show_All (Widget => Main_Window);

   Gtk.Main.Main;
end Interaction;


GUI, add, Edit,Number w50 vUserInput gMakeSure, 0          ; Number Specifies Numbers-only, but other characters can still be pasted in,
						 ; Making our own check necessary. (MakeSure)

GUI, add, Button, gIncrement, Increment 	 ; Instead of an increment button, the UpDown control could be used, but this was not specified.
GUI, add, Button, gRando, Random
Gui, Show, W200 y200, Title			 ; Shows the GUI with a width and height of 200px
return 						 ; End Auto-Execute Section

Increment:
Gui, Submit, NoHide
; The above line assigns all variables associated with controls to the state of that control, but leaves the GUI visible.
If UserInput is not Number
{
	MsgBox, %userInput% is not a number.
	GUIControl,,UserInput, 0 ; Reset the Edit control to 0
}
Else
{
	UserInput++
	GUIControl,, UserInput, %UserInput% ; Sets the value of the Edit control
}
return

Rando:
MsgBox, 4, Title, Are you sure you want to randomize? ; Specify your own title. 4 means YesNo
IfMsgBox, Yes
{
	Random, UserInput, 1, 999		      ; random number from 1-999
	GUIControl,, UserInput, %UserInput%	      ; Sets the value of the Edit control
}
return

MakeSure:
Gui, Submit, NoHide
If UserInput is not Number
{
	If (UserInput<>"")
	{
	Msgbox Error! Numbers Only!
	GUIControl,, UserInput, 0
	}
}
return

GUIClose:
ExitApp  ; Makes sure the script exits when the window is closed,
	 ; Otherwise the script is persistent because it contains
	 ; a timer.


OPTION GUI TRUE
PRAGMA GUI gtk3

DECLARE (*show)() = gtk_widget_show_all TYPE void
DECLARE (*hide)() = gtk_widget_hide TYPE void

gui = GUIDEFINE(" \
    { type=WINDOW name=window callback=delete-event title=\"Rosetta Code\" width-request=200 } \
    { type=BOX name=box parent=window orientation=GTK_ORIENTATION_VERTICAL } \
    { type=SPIN_BUTTON name=spin parent=box numeric=TRUE } \
    { type=BUTTON_BOX name=bbox parent=box } \
    { type=BUTTON name=increment parent=bbox callback=clicked label=\"Increment\" } \
    { type=BUTTON name=random parent=bbox callback=clicked label=\"Random\" } \
    { type=MESSAGE_DIALOG name=confirm callback=delete-event callback=response,yesno message-type=GTK_MESSAGE_WARNING buttons=GTK_BUTTONS_YES_NO title=\"Warning\" text=\"Get random number?\" }")

CALL GUISET(gui, "spin", "adjustment", gtk_adjustment_new(0, 0, MAXNUM(float), 1, 1, 0))

DECLARE answer TYPE int*
DECLARE input TYPE FLOATING

WHILE TRUE
    event$ = GUIEVENT$(gui, TRUE)
    SELECT TOKEN$(event$, 1)
        CASE "window"
            BREAK
        CASE "increment"
            CALL GUIGET(gui, "spin", "value", &input)
            CALL GUISET(gui, "spin", "value", input+1)
        CASE "random"
            CALL GUIFN(gui, "confirm", show)
        CASE "yesno"
            answer = (intptr_t)DEC(TOKEN$(event$, 2))
            IF *answer = GTK_RESPONSE_YES THEN CALL GUISET(gui, "spin", "value", RANDOM(MAXNUM(float)))
            CALL GUIFN(gui, "confirm", hide)
    ENDSELECT
WEND


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

      IDYES = 6
      ES_NUMBER = 8192
      MB_YESNO = 4

      form% = FN_newdialog("Rosetta Code", 100, 100, 100, 52, 8, 1000)
      PROC_static(form%, "Value:", 100, 10, 10, 24, 14, 0)
      PROC_editbox(form%, "0", 101, 40, 8, 52, 14, ES_NUMBER)
      PROC_pushbutton(form%, "Increment", FN_setproc(PROCinc), 7, 30, 40, 16, 0)
      PROC_pushbutton(form%, "Random", FN_setproc(PROCrandom), 52, 30, 40, 16, 0)
      PROC_showdialog(form%)

      REPEAT
        WAIT 1
      UNTIL !form% = 0
      QUIT

      DEF PROCinc
      LOCAL number%
      SYS "GetDlgItemInt", !form%, 101, 0, 1 TO number%
      SYS "SetDlgItemInt", !form%, 101, number% + 1, 1
      ENDPROC

      DEF PROCrandom
      LOCAL reply%
      SYS "MessageBox", !form%, "Set to a random value?", "Confirm", MB_YESNO TO reply%
      IF reply% = IDYES THEN SYS "SetDlgItemInt", !form%, 101, RND(10000), 1
      ENDPROC


using System;
using System.ComponentModel;
using System.Windows.Forms;

class RosettaInteractionForm : Form
{
    // Model used for DataBinding.
    // Notifies bound controls about Value changes.
    class NumberModel: INotifyPropertyChanged
    {

        Random rnd = new Random();

        // initialize event with empty delegate to avoid checks on null
        public event PropertyChangedEventHandler PropertyChanged = delegate {};

        int _value;
        public int Value
        {
            get { return _value; }
            set
            {
                _value = value;
                // Notify bound control about value change
                PropertyChanged(this, new PropertyChangedEventArgs("Value"));
            }
        }

        public void ResetToRandom(){
            Value = rnd.Next(5000);
        }
    }

    NumberModel model = new NumberModel{ Value = 0};

    RosettaInteractionForm()
    {
        //MaskedTextBox is a TextBox variety with built-in input validation
        var tbNumber = new MaskedTextBox
                        {
                            Mask="0000",            // allow 4 decimal digits only
                            ResetOnSpace = false,   // don't enter spaces
                            Dock = DockStyle.Top    // place at the top of form
                        };
        // bound TextBox.Text to NumberModel.Value;
        tbNumber.DataBindings.Add("Text", model, "Value");

        var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom};
        btIncrement.Click += delegate
                        {
                            model.Value++;
                        };
        var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom};
        btDecrement.Click += delegate
                        {
                            model.Value--;
                        };
        var btRandom = new Button{ Text="Reset to Random", Dock = DockStyle.Bottom };
        btRandom.Click += delegate
                        {
                            if (MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                model.ResetToRandom();
                        };
        Controls.Add(tbNumber);
        Controls.Add(btIncrement);
        Controls.Add(btDecrement);
        Controls.Add(btRandom);
    }
    static void Main()
    {
        Application.Run(new RosettaInteractionForm());
    }
}


;; Using the LTK library...

(defun gui-test ()
  "the main window for the input test"
  (ltk:with-ltk ()
    (ltk:wm-title ltk:*tk* "GUI Test")
    (ltk:bind ltk:*tk* "<Alt-q>" (lambda (evt)
				   (declare (ignore evt))
				   (setf ltk:*exit-mainloop* t)))
    (let* (;; Initializing random generator
	   (*random-state* (make-random-state t))
	   ;; Creating widgets
	   (the-input (make-instance 'ltk:entry
				     :text "0"
				     :validate :key))
	   (f (make-instance 'ltk:frame))
	   (btn1 (make-instance 'ltk:button :text "random" :master f))
	   (btn2 (make-instance 'ltk:button :text "increment" :master f)))
      ;; Associating actions with widgets
      (ltk:bind btn1 "<Button-1>"
		(lambda (evt)
		  (declare (ignore evt))
		  (when (ltk:ask-yesno "Really reset to random?" :title "Question")
		    (setf (ltk:text the-input) (write-to-string (random 10000))))))
      (ltk:bind btn2 "<Button-1>"
		(lambda (evt)
		  (declare (ignore evt))
		  (setf (ltk:text the-input)
			(write-to-string (1+ (parse-integer (ltk:text the-input)))))))
      (ltk:format-wish "~A configure -validatecommand {string is int %P}"
		       (ltk:widget-path the-input))
      (ltk:focus the-input)
      ;; Placing widgets on the window
      (ltk:pack the-input :side :top)
      (ltk:pack f :side :bottom)
      (ltk:pack btn1 :side :left)
      (ltk:pack btn2 :side :right))))

(gui-test)


(require 'interface)

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

(define (panel )
    (ui-clear)
    (info-text "My rosetta application" "blue")

;; input field (checked for numeric)
    (define f-input (ui-create-element "input" '((type number))))
    (ui-set-value f-input 0)
    (ui-add f-input)
    (ui-on-focus  f-input (lambda(e) (info-text "")))

;; Increment button
    (define btn-inc (ui-add-button "Increment"))
    (define (increment elem)
        (define val (ui-get-numvalue f-input))
        (if val ;; checked legal numeric
                (ui-set-value f-input (1+ val))
                (info-text  "Need a number" "red")))
    (ui-on-click btn-inc increment)
    (ui-add btn-inc)

    (define btn-random (ui-add-button "Random"))
    (define (set-random elem)
        (when (confirm "Really random?")
              (ui-set-value f-input (random-prime 1000000))))
    (ui-on-click btn-random set-random)

    (ui-focus btn-inc)
    (stdout-hide #t)
    (stdin-hide #t)) ;; end panel

(panel)


import forms;
import extensions;

public class MainWindow : SDIDialog
{
    Button btmIncrement;
    Button btmRandom;
    Edit   txtNumber;

    constructor new()
        <= new()
    {
        btmIncrement := Button.new();
        btmRandom    := Button.new();
        txtNumber    := Edit.new();

        self
            .appendControl:btmIncrement
            .appendControl:btmRandom
            .appendControl:txtNumber;

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

        txtNumber.setRegion(7, 7, 140, 25);
        txtNumber.Caption := "0";

        btmIncrement.setRegion(7, 35, 140, 25);
        btmIncrement.Caption := "Increment";
        btmIncrement.onClick := (args){ self.onButtonIncrementClick() };

        btmRandom.setRegion(7, 65, 140, 25);
        btmRandom.Caption := "Random";
        btmRandom.onClick := (args){ self.onButtonRandomClick() };
    }

    private onButtonIncrementClick()
    {
        var number := txtNumber.Value.toInt();

        number := number + 1;
        self.changeTextBoxValue(number)
    }

    private onButtonRandomClick()
    {
        if(messageDialog.showQuestion("Inf", "Really reset to random value?"))
        {
            self.changeTextBoxValue(randomGenerator.eval(99999999))
        }
    }

    private changeTextBoxValue(number)
    {
        txtNumber.Caption := number.toString()
    }
}


include GtkEngine.e -- see OpenEuphoria.org

constant -- interface
    win = create(GtkWindow,"title=GUI Component Interaction;size=200x100;border=10;$destroy=Quit"),
    pan = create(GtkBox,"orientation=vertical;spacing=10"),
    inp = create(GtkEntry,"name=Input;text=0;$activate=Validate"),
    box = create(GtkButtonBox),
    btn1 = create(GtkButton,"gtk-add#_Increment","Increment"),
    btn2 = create(GtkButton,"gtk-help#_Random","Random")

add(win,pan)
add(pan,inp)
add(box,{btn1,btn2})
pack(pan,-box)

show_all(win)
main()

-----------------------------
global function Validate() -- warns about invalid entry, does not prevent it;
-----------------------------
if not t_digit(trim_head(get("Input.text"),"- ")) then
    return Warn(win,"Validate","This is not a valid number","Try again!")
end if
return 1
end function

---------------------------
global function Increment()
---------------------------
set("Input.value",get("Input.value")+1)
return 1
end function

------------------------
global function Random()
------------------------
if Question(win,"Random","Click OK for a random number",,GTK_BUTTONS_OK_CANCEL) = MB_OK then
    set("Input.value",rand(1000))
end if
return 1
end function


// GUI component interaction. Nigel Galloway: June 13th., 2020
let n=new System.Windows.Forms.Form(Size=new System.Drawing.Size(250,150))
let i=new System.Windows.Forms.TextBox(Location=new System.Drawing.Point(30,30),Text="0")
let g=new System.Windows.Forms.Label(Location=new System.Drawing.Point(135,33),Text="Value")
let e=new System.Windows.Forms.Button(Location=new System.Drawing.Point(30,70),Text="Increment")
let l=new System.Windows.Forms.Button(Location=new System.Drawing.Point(135,70),Text="Random")
n.Controls.AddRange([|i;g;e;l|])
let rand=new System.Random()
i.Leave.AddHandler(new System.EventHandler(fun _ _->i.Text<-try string(int(i.Text)) with |_->"0"))
e.Click.AddHandler(new System.EventHandler(fun _ _->i.Text<-(string(int(i.Text)+1))))
l.Click.AddHandler(new System.EventHandler(fun _ _->i.Text<-(string(rand.Next()))))
System.Windows.Forms.Application.Run(n)


using fwt
using gfx

class GuiComponent
{
  public static Void main ()
  {
    Window
    {
      title = "Rosetta Code: Gui component"
      size = Size(350, 200)
      textField := Text
      {
        onModify.add |Event e|
        {
          Text thisText := e.widget
          if (thisText.text != "") // if nonempty string
          {
            try (thisText.text.toInt) // try converting to int
            catch thisText.text = ""  // clear field if does not work
          }
        }
      }
      GridPane
      {
        numCols = 1
        textField,
        Button
        {
          text = "increment"
          onAction.add |Event e|
          { // make sure there is a number to increment, else set field to 0
            if (textField.text == "")
            {
              textField.text = "0"
            }
            else
            {
              try
              {
                Int x := textField.text.toInt
                textField.text = (x+1).toStr
              }
              catch
              {
                textField.text = "0"
              }
            }
          }
        },
        Button
        {
          text = "random"
          onAction.add |Event e|
          {
            if (Dialog.openQuestion(e.window, "Make number random?", null, Dialog.yesNo) == Dialog.yes)
            {
              textField.text = Int.random(1..10000).toStr
            }
          }
        },
      },
    }.open
  }
}


#Include "windows.bi"

Dim As HWND Window_Main, Edit_Number, Button_Inc, Button_Rnd
Dim As MSG msg
Dim As Integer n
Dim As String text

'Create a window with an input field and two buttons:
Window_Main = CreateWindow("#32770", "GUI Component Interaction", WS_OVERLAPPEDWINDOW Or WS_VISIBLE, 100, 100, 250, 200, 0, 0, 0, 0)
Var Static_Number = CreateWindow("STATIC", "Value:", WS_VISIBLE Or WS_CHILD, 10, 10, 100, 20, Window_Main, 0, 0, 0)
Edit_Number = CreateWindow("EDIT", "0", WS_BORDER Or WS_VISIBLE Or WS_CHILD Or ES_AUTOHSCROLL Or ES_Number, 110, 10, 100, 20, Window_Main, 0, 0, 0)
Button_Inc = CreateWindow("BUTTON", "Increment", WS_VISIBLE Or WS_CHILD, 110, 40, 100, 20, Window_Main, 0, 0, 0)
Button_Rnd = CreateWindow("BUTTON", "Random", WS_VISIBLE Or WS_CHILD, 110, 70, 100, 20, Window_Main, 0, 0, 0)

'Windows message loop:
While GetMessage(@msg, Window_Main, 0, 0)
  TranslateMessage(@msg)
  DispatchMessage(@msg)
  Select Case msg.hwnd
    Case Button_Inc
      If msg.message = WM_LBUTTONDOWN Then
	'Increment value:
	text = Space(GetWindowTextLength(Edit_Number) + 1) 'Buffer for the text
	GetWindowText(Edit_Number, text, Len(text))
	n = Val(text)
	SetWindowText(Edit_Number, Str(n + 1))
      End If
    Case Button_Rnd
      If msg.message = WM_LBUTTONDOWN THEN
	'Random value (max. 100000):
	If MessageBox(0, "Set input field to random value?", "Please confirm", MB_ICONQUESTION Or MB_YESNO) = IDYES Then
	  n = 100000 * RND
	  SetWindowText(Edit_Number, Str(n))
	End If
      End If
    Case Window_Main
      If msg.message = WM_COMMAND Then End
  End Select
Wend

End


hValueBox As ValueBox                                             'We need a ValueBox

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

With Me                                                           'Set the Form's Properties..
  .height = 95                                                    'Set the Height
  .Width = 350                                                    'Set the Width
  .Arrangement = Arrange.Vertical                                 'Arrange items vertically
  .Padding = 5                                                    'Border area
  .Title = "GUI component interaction"                            'Title displayed on the Form
End With

hValueBox = New ValueBox(Me)                                      'Add a ValueBox to the Form

With hValueBox                                                    'Set the ValueBox's Properties..
  .Expand = True                                                  'Expand the ValueBox
  .Value = 0                                                      'Set it's value to 0
End With

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

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

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

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

End

Public Sub ButtonInc_Click()                                      'When the 'Increment' Button is clicked..

hValueBox.Value += 1                                              'Increase the Value in the ValueBox by 1

End

Public Sub ButtonRand_Click()                                     'When the 'Random' Button is clicked..
Dim siRand As Short                                               'To store random number
Dim byAnswer As Byte                                              'To store the answer to the MessageBox question

siRand = Rand(1, 32767)                                           'Create a 'Random' mnumber

byAnswer = Message.Question("Would you like to set the ValueBox to " & siRand & "?", "Yes", "No") ' Ask if the number is OK
If byAnswer = 1 Then                                              'If the user says 'Yes' then
  hValueBox.Value = siRand                                        'Display the 'Random' number in the ValueBox
Else                                                              'ELSE
  hValueBox.Value = 0                                             'Set the ValueBox Value to 0
End If

End


package main

import (
    "github.com/gotk3/gotk3/gtk"
    "log"
    "math/rand"
    "strconv"
    "time"
)

func validateInput(window *gtk.Window, str string) (int64, bool) {
    i, err := strconv.ParseInt(str, 10, 64)
    if err != nil {
        dialog := gtk.MessageDialogNew(
            window,
            gtk.DIALOG_MODAL,
            gtk.MESSAGE_ERROR,
            gtk.BUTTONS_OK,
            "Invalid value",
        )
        dialog.Run()
        dialog.Destroy()
        return 0, false
    }
    return i, true
}

func check(err error, msg string) {
    if err != nil {
        log.Fatal(msg, err)
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    gtk.Init(nil)

    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
    check(err, "Unable to create window:")
    window.SetTitle("Rosetta Code")
    window.SetPosition(gtk.WIN_POS_CENTER)
    window.Connect("destroy", func() {
        gtk.MainQuit()
    })

    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
    check(err, "Unable to create box:")
    box.SetBorderWidth(1)

    label, err := gtk.LabelNew("Value:")
    check(err, "Unable to create label:")

    entry, err := gtk.EntryNew()
    check(err, "Unable to create entry:")
    entry.SetText("0") // initialize to zero
    entry.Connect("activate", func() {
        // read and validate the entered value
        str, _ := entry.GetText()
        validateInput(window, str)
    })

    // button to increment
    ib, err := gtk.ButtonNewWithLabel("Increment")
    check(err, "Unable to create increment button:")
    ib.Connect("clicked", func() {
        // read and validate the entered value
        str, _ := entry.GetText()
        if i, ok := validateInput(window, str); ok {
            entry.SetText(strconv.FormatInt(i+1, 10))
        }
    })

    // button to put in a random value if confirmed
    rb, err := gtk.ButtonNewWithLabel("Random")
    check(err, "Unable to create random button:")
    rb.Connect("clicked", func() {
        dialog := gtk.MessageDialogNew(
            window,
            gtk.DIALOG_MODAL,
            gtk.MESSAGE_QUESTION,
            gtk.BUTTONS_YES_NO,
            "Set random value",
        )
        answer := dialog.Run()
        dialog.Destroy()
        if answer == gtk.RESPONSE_YES {
            entry.SetText(strconv.Itoa(rand.Intn(10000)))
        }
    })

    box.PackStart(label, false, false, 2)
    box.PackStart(entry, false, false, 2)
    box.PackStart(ib, false, false, 2)
    box.PackStart(rb, false, false, 2)
    window.Add(box)

    window.ShowAll()
    gtk.Main()
}


import Graphics.UI.WX
import System.Random

main :: IO ()
main = start $ do
    frm   <- frame [text := "Interact"]
    fld   <- textEntry frm [text := "0", on keyboard := checkKeys]
    inc   <- button frm [text := "increment", on command := increment fld]
    ran   <- button frm [text := "random", on command := (randReplace fld frm)]
    set frm [layout := margin 5 $ floatCentre $ column 2
            [centre $ widget fld, row 2 [widget inc, widget ran]]]

increment :: Textual w => w -> IO ()
increment field = do
    val <- get field text
    when ((not . null) val) $ set field [text := show $ 1 + read val]

checkKeys :: EventKey -> IO ()
checkKeys (EventKey key _ _) =
    when (elem (show key) $ "Backspace" : map show [0..9]) propagateEvent

randReplace :: Textual w => w -> Window a -> IO ()
randReplace field frame = do
    answer <- confirmDialog frame "Random" "Generate a random number?" True
    when answer $ getStdRandom (randomR (1,100)) >>= \num ->
                  set field [text := show (num :: Int)]


import gui
$include "guih.icn"

# Provides a basic message dialog
class MessageDialog : Dialog (message)
  method component_setup ()
    label := Label ("label="||message, "pos=20,20")
    add (label)
    button := TextButton("label=OK", "pos=100,60")
    button.connect (self, "dispose", ACTION_EVENT)
    add (button)

    connect (self, "dispose", CLOSE_BUTTON_EVENT)
    attrib ("size=200,100", "bg=light gray")
  end

  initially (message)
    self.Dialog.initially()
    self.message := message
end

# Provides a basic yes/no question dialog
class QuestionDialog : Dialog (answer, message)
  method answered_yes ()
    return answer == "yes"
  end

  method answer_yes ()
    answer := "yes"
    dispose ()
  end

  method answer_no ()
    answer := "no"
    dispose ()
  end

  method component_setup ()
    label := Label ("label="||message, "pos=20,20")
    add (label)
    buttonYes := TextButton("label=Yes", "pos=40,60")
    buttonYes.connect (self, "answer_yes", ACTION_EVENT)
    add (buttonYes)
    buttonNo := TextButton("label=No", "pos=120,60")
    buttonNo.connect (self, "answer_no", ACTION_EVENT)
    add (buttonNo)

    connect (self, "dispose", CLOSE_BUTTON_EVENT)
    attrib ("size=200,100", "bg=light gray")
  end

  initially (message)
    self.Dialog.initially()
    self.answer := "no"
    self.message := message
end

# The main window, displays the different components
class WindowApp : Dialog (field, value)
  method increment ()
    value +:= 1
    field.set_contents (string(value))
  end

  method random ()
    query := QuestionDialog ("Set to random?")
    query.show_modal ()
    if query.answered_yes () then {
      value := ?100
      field.set_contents (string(value))
    }
  end

  method handle_text_field ()
    if not(integer(field.get_contents ()))
      then {
        warning := MessageDialog ("Not a number")
        warning.show_modal ()
        field.set_contents (string(value))
      }
      else {
        value := integer(field.get_contents ())
      }
  end

  method component_setup ()
    value := 0
    field := TextField("contents="||value, "pos=20,20", "size=150")
    field.connect (self, "handle_text_field", TEXTFIELD_CHANGED_EVENT)
    add (field)
    button1 := TextButton("label=Increment", "pos=20,60", "size=70")
    button1.connect (self, "increment", ACTION_EVENT)
    add (button1)
    button2 := TextButton("label=Random", "pos=100,60", "size=70")
    button2.connect (self, "random", ACTION_EVENT)
    add (button2)

    connect (self, "dispose", CLOSE_BUTTON_EVENT)
    attrib ("size=200,100", "bg=light gray")
  end
end

# create and show the window
procedure main ()
  w := WindowApp ()
  w.show_modal ()
end


INTERACT=: noun define
pc interact;
cc Value edit center;
cc increment button;cn "Increment";
cc random button;cn "Random";
pas 6 6;pcenter;
)

interact_run=: verb define
 wd INTERACT
 wd 'set Value text 0;'
 wd 'pshow;'
)

interact_cancel=: interact_close=: verb define
 wd'pclose'
)

interact_Value_button=: verb define
 wd 'set Value text ' , ": {. 0 ". Value
)

interact_increment_button=: verb define
 wd 'set Value text ' , ": 1 + {. 0 ". Value
)

interact_random_button=: verb define
 if. 2 = 2 3 wdquery 'Confirm';'Reset to random number?' do.
  wd 'set Value text ' , ": ?100
 end.
)


import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Interact extends JFrame{
	final JTextField numberField;
	final JButton incButton, randButton;

	public Interact(){
		//stop the GUI threads when the user hits the X button
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		numberField = new JTextField();
		incButton = new JButton("Increment");
		randButton = new JButton("Random");

		numberField.setText("0");//start at 0

		//listen for button presses in the text field
		numberField.addKeyListener(new KeyListener(){
			@Override
			public void keyTyped(KeyEvent e) {
				//if the entered character is not a digit
				if(!Character.isDigit(e.getKeyChar())){
					//eat the event (i.e. stop it from being processed)
					e.consume();
				}
			}
			@Override
			public void keyReleased(KeyEvent e){}
			@Override
			public void keyPressed(KeyEvent e){}
		});

		//listen for button clicks on the increment button
		incButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				String text = numberField.getText();
				if(text.isEmpty()){
					numberField.setText("1");
				}else{
					numberField.setText((Long.valueOf(text) + 1) + "");
				}
			}
		});

		//listen for button clicks on the random button
		randButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				//show a dialog and if they answer "Yes"
				if(JOptionPane.showConfirmDialog(null, "Are you sure?") ==
					JOptionPane.YES_OPTION){
					//set the text field text to a random positive long
					numberField.setText(Long.toString((long)(Math.random()
							* Long.MAX_VALUE)));
				}
			}
		});

		//arrange the components in a grid with 2 rows and 1 column
		setLayout(new GridLayout(2, 1));

		//a secondary panel for arranging both buttons in one grid space in the window
		JPanel buttonPanel = new JPanel();

		//the buttons are in a grid with 1 row and 2 columns
		buttonPanel.setLayout(new GridLayout(1, 2));
		//add the buttons
		buttonPanel.add(incButton);
		buttonPanel.add(randButton);

		//put the number field on top of the buttons
		add(numberField);
		add(buttonPanel);
		//size the window appropriately
		pack();

	}

	public static void main(String[] args){
		new Interact().setVisible(true);
	}
}


#=
The task: For a minimal "application", write a program that
presents a form with three components to the user: A numeric input
field ("Value") and two buttons ("increment" and "random").
=#

using Tk

w = Toplevel("Component Interaction Example")
fr = Frame(w)
pack(fr, expand=true, fill="both")

value = Entry(fr, "")
increment = Button(fr, "Increment")
random = Button(fr, "Random")

formlayout(value, "Value:")
formlayout(increment, " ")
formlayout(random, " ")

set_value(value, "0") ## The field is initialized to zero.

incrementvalue(s) = (val = parse(Int, get_value(value)); set_value(value, string(val + 1)))
bind(increment, "command", incrementvalue)

function validate_command(path, P)
    try
        length(P) > 0 && parse(Float64, P)
        tcl("expr", "TRUE")
    catch e
        tcl("expr", "FALSE")
    end
end
function invalid_command(path, W)
    println("Invalid value")
    tcl(W, "delete", "@0", "end")
end

"""
    Pressing the "random" button presents a confirmation dialog and
    resets the field's value to a random value if the answer is "Yes".
"""
function randval(s)
    out = Messagebox(w, title="Randomize input", detail="Select a new random number?")
    if out == "ok"
        new_value = rand(collect(1:99))
        set_value(value, string(new_value))
    end
end
bind(random, "command", randval)

while true sleep(1); end


import java.awt.GridLayout
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.KeyEvent
import java.awt.event.KeyListener
import javax.swing.*

class Interact : JFrame() {
    val numberField = JTextField()
    val incButton = JButton("Increment")
    val randButton = JButton("Random")
    val buttonPanel = JPanel()

    init {
        defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        numberField.text = "0"

        numberField.addKeyListener(object : KeyListener {
            override fun keyTyped(e : KeyEvent) : Unit {
                if (!Character.isDigit(e.keyChar)) e.consume()
            }
            override fun keyReleased(e : KeyEvent?) {}
            override fun keyPressed(e : KeyEvent) {}
        })

        incButton.addActionListener {
            val num = (numberField.text ?: "").toDouble()
            numberField.text = (num + 1).toString()
        }

        randButton.addActionListener(object : ActionListener {
            fun proceedOrNot() = JOptionPane.showConfirmDialog(randButton, "Are you sure?")
            override fun actionPerformed(e : ActionEvent) {
                if(proceedOrNot() == JOptionPane.YES_OPTION)
                    numberField.text = (Math.random() * Long.MAX_VALUE).toString()
            }
        })

        layout = GridLayout(2, 1)
        buttonPanel.layout = GridLayout(1, 2)
        buttonPanel.add(incButton)
        buttonPanel.add(randButton)
        add(numberField)
        add(buttonPanel)
        pack()
    }
}

fun main(args : Array<String>) {
    Interact().isVisible = true
}


{input {@ id="input" type="text" value="0"}}
{input {@ type="button" value="increment"
          onclick="document.getElementById('input').value =
                   parseInt( document.getElementById('input').value ) + 1;"}}
{input {@ type="button" value="random"
          onclick="if (confirm( 'yes?' ))
                       document.getElementById('input').value =
                       Math.round(Math.random()*100);"}}


nomainwin
    textbox #demo.val, 20, 50, 90, 24
    button #demo.inc, "Increment", [btnIncrement], UL, 20, 90, 90, 24
    button #demo.rnd, "Random", [btnRandom], UL, 20, 120, 90, 24
    open "Rosetta Task: GUI component interaction" for window as #demo
    #demo "trapclose [quit]"
    validNum$ = "0123456789."
    #demo.val 0
wait

[quit]
    close #demo
end

[btnIncrement]
    #demo.val "!contents? nVal$"
    nVal$ = trim$(nVal$)
    if left$(nVal$, 1) = "-" then
        neg = 1
        nVal$ = mid$(nVal$, 2)
    else
        neg = 0
    end if
    validNum = 1
    nDecs = 0
    for i = 1 to len(nVal$)
        if instr(validNum$, mid$(nVal$, i, 1)) = 0 then
            validNum = 0
        end if
        if mid$(nVal$, i, 1) = "." then
            nDecs = nDecs + 1
        end if
    next i
    if nDecs > 1 then
        validNum = 0
    end if
    if neg = 1 then
        nVal$ = "-";nVal$
    end if
    if validNum = 0 then
        notice nVal$;" does not appear to be a valid number.  " + _
            "(Commas are not allowed.)"
    else
        nVal = val(nVal$)
        nVal = nVal + 1
    end if
    #demo.val nVal
wait

[btnRandom]
    confirm "Reset value to random number";yn$
    if yn$ = "yes" then
        nVal = int(rnd(1) * 100) + 1
        #demo.val nVal
    end if
wait


Module CheckIt {
      Declare form1 form
      Declare textbox1 textbox form form1
      Declare buttonInc Button form form1
      Declare buttonRND Button form form1
      Method textbox1, "move", 2000,2000,4000,600
      Method buttonInc, "move", 2000,3000,2000,600
      Method buttonRND, "move", 4000,3000,2000,600
      With form1, "Title", "Rosetta Code: GUI component interaction"
      With textbox1,"vartext" as textbox1.value$, "Prompt", "Value:", "ShowAlways", true
      With buttonInc,"Caption","Increment"
      With buttonRND,"Caption","Random"
      textbox1.value$="0"
      Function Local1(new Feed$) {
            \\ this Function can be used from other Integer
            \\ this$ and thispos, exist just before the call of this Function
            local sgn$
            if feed$="" and this$="-" then thispos-- :  exit
            if left$(this$,1)="-" then sgn$="-": this$=mid$(this$, 2)
            if this$<>Trim$(this$)  then  this$=Feed$ :  thispos-- : exit
            If Trim$(this$)="" then this$="0" : thispos=2 : exit
            if instr(this$,"+")>0 and sgn$="-" then this$=filter$(this$, "+") : sgn$=""
            if instr(this$,"-")>0  and sgn$="" then this$=filter$(this$, "-") : sgn$="-"
            if filter$(this$,"0123456789")<>"" then this$=Feed$ :  thispos-- : exit
            if len(this$)>1 then While  left$(this$,1)="0" {this$=mid$(this$, 2)}
            this$=sgn$+this$
            if this$="-0" then this$="-" : thispos=2
        }
      Function TextBox1.ValidString {
                  \\ this Function called direct from textbox
                  Read  New &this$, &thispos
                  Call Local local1(textbox1.value$)
      }
      Function buttonInc.Click {
               textbox1.value$=str$(val(textbox1.value$)+1, "")
      }
      Function buttonRND.Click {
            If  AsK$("Change Value with random number", "Question", "Yes", "No")="Yes" Then {
                      textbox1.value$=str$(Random(0, 10000), "")
                      After 100 {Try {Method textbox1,"GetFocus"}}
            }
      }
      \\ open modal
      Method form1, "show", 1
      Declare form1 nothing
}
Checkit


Manipulate[Null, {{value, 0}, InputField[Dynamic[value], Number] &},
 [email protected]{Button["increment", value++],
   Button["random",
    If[DialogInput[
      [email protected]{"Are you sure?",
        [email protected]{Button["Yes", DialogReturn[True]],
          Button["No", DialogReturn[False]]}}],
     value = [email protected]], Method -> "Queued"]}]


import
  gtk2, glib2, strutils, random

var valu: int = 0

proc thisDestroy(widget: PWidget, data: Pgpointer) {.cdecl.} =
  main_quit()

randomize()
nim_init()
var win = window_new(gtk2.WINDOW_TOPLEVEL)
var content = vbox_new(true,10)
var hbox1 = hbox_new(true,10)
var hbox2 = hbox_new(false,1)
var lbl = label_new("Value:")
var entry_fld = entry_new()
entry_fld.set_text("0")
var btn_quit = button_new("Quit")
var btn_inc = button_new("Increment")
var btn_rnd = button_new("Random")
add(hbox2,lbl)
add(hbox2,entry_fld)
add(hbox1,btn_inc)
add(hbox1,btn_rnd)
pack_start(content, hbox2, true, true, 0)
pack_start(content, hbox1, true, true, 0)
pack_start(content, btn_quit, true, true, 0)
set_border_width(win, 5)
add(win, content)

proc on_question_clicked: bool =
  var dialog = win.message_dialog_new(0, MESSAGE_QUESTION,
    BUTTONS_YES_NO, "Use a Random number?")
  var response = dialog.run()
  result = response == RESPONSE_YES
  dialog.destroy()

proc thisInc(widget: PWidget, data: Pgpointer){.cdecl.} =
  inc(valu)
  entry_fld.set_text($valu)

proc thisRnd(widget: PWidget, data: Pgpointer){.cdecl.} =
  if on_question_clicked():
    valu = rand(20)
    entry_fld.set_text($valu)

proc thisTextChanged(widget: PWidget, data: Pgpointer) {.cdecl.} =
  try:
    valu = parseInt($entry_fld.get_text())
  except ValueError:
    entry_fld.set_text($valu)

discard signal_connect(win, "destroy", SIGNAL_FUNC(thisDestroy), nil)
discard signal_connect(btn_quit, "clicked", SIGNAL_FUNC(thisDestroy), nil)
discard signal_connect(btn_inc, "clicked", SIGNAL_FUNC(thisInc), nil)
discard signal_connect(btn_rnd, "clicked", SIGNAL_FUNC(thisRnd), nil)
discard signal_connect(entry_fld, "changed", SIGNAL_FUNC(thisTextChanged), nil)

win.show_all()
main()


declare
  [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}

  proc {Main}
     MaxValue = 1000
     NumberWidget
     GUI = lr(
              numberentry(init:1 min:0 max:MaxValue handle:NumberWidget)
              button(text:"Increase"
                     action:proc {$}
                               OldVal = {NumberWidget get($)}
                            in
                               {NumberWidget set(OldVal+1)}
                            end)
              button(text:"Random"
                     action:proc {$}
                               if {Ask "Reset to random?"} then
                                  Rnd = {OS.rand} * MaxValue div {OS.randLimits _}
                               in
                                  {NumberWidget set(Rnd)}
                               end
                            end)
              )
     Window = {QTk.build GUI}
  in
     {Window show}
  end

  fun {Ask Msg}
     Result
     Box = {QTk.build
            td(message(init:Msg)
               lr(button(text:"Yes" action:proc {$} Result=true  {Box close} end)
                  button(text:"No"  action:proc {$} Result=false {Box close} end)
                 ))}
  in
     {Box show}
     {Box wait}
     Result
  end
in
  {Main}


#!/usr/bin/perl

use strict;
use warnings;
use Tk;
use Tk::Dialog;
use Tk::LabFrame;

my $value = 0;

my $mw = MainWindow->new;
$mw->title( 'GUI component interaction' );
my $lf = $mw->LabFrame( -label => 'Value' )->pack(-fill => 'x',-expand => 1);
$lf->Entry( -width => 10, -textvariable => \$value,
  -validate => 'key', -validatecommand => sub { $_[0] =~ /^\d{1,9}\z/ },
  )->pack(-fill => 'x', -expand => 1);
$mw->Button( -text => 'increment', -command => sub { $value++ },
  )->pack( -side => 'left' );
$mw->Button( -text => 'random', -command => sub {
  $mw->Dialog(
    -text => 'Change to a random value?',
    -title => 'Confirm',
    -buttons => [ qw(Yes No) ]
    )->Show eq 'Yes' and $value = int rand 1e9; }
  )->pack( -side => 'right' );

MainLoop;


include pGUI.e

Ihandle txt, increment, random, hbx, vbx, dlg

function action_cb(Ihandle /*ih*/, integer ch)
    if not find(ch,"0123456789-") then return IUP_IGNORE end if
    return IUP_CONTINUE
end function

function increment_cb(Ihandle /*ih*/)
    integer v = IupGetInt(txt,"VALUE")+1
    IupSetInt(txt,"VALUE",v)
    return IUP_CONTINUE
end function

function random_cb(Ihandle /*ih*/)
    if IupAlarm("Confirm","Replace wth random value?","Yes","No")=1 then
        IupSetInt(txt,"VALUE",rand(1000))
    end if
    return IUP_CONTINUE
end function

IupOpen()
txt = IupText(Icallback("action_cb"),"EXPAND=YES")
increment = IupButton("increment",Icallback("increment_cb"))
random = IupButton("random",Icallback("random_cb"))
hbx = IupHbox({increment,random},"MARGIN=0x10, GAP=20")
vbx = IupVbox({txt,hbx},"MARGIN=40x20")
dlg = IupDialog(vbx)
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")

(de start ()
   (and (app) (zero *Number))
   (action
      (html 0 "Increment" "@lib.css" NIL
         (form NIL
            (gui '(+Var +NumField) '*Number 20 "Value")
            (gui '(+JS +Button) "increment"
               '(inc '*Number) )
            (gui '(+Button) "random"
               '(ask "Reset to a random value?"
                  (setq *Number (rand)) ) ) ) ) ) )

(server 8080 "!start")
(wait)


[xml]$XML = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        Title="Rosetta Code" WindowStartupLocation = "CenterScreen" Height="100" Width="210" ResizeMode="NoResize">

    <Grid Background="#FFC1C3CB">
        <Label Name="Label_Value" Content="Value" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="70"/>
        <TextBox Name="TextBox_Value" HorizontalAlignment="Left" Height="23" Margin="90,10,0,0" TextWrapping="Wrap" Text="0" VerticalAlignment="Top" Width="100"/>
        <Button Name="Button_Random" Content="Random" HorizontalAlignment="Left" Margin="10,41,0,0" VerticalAlignment="Top" Width="70" Height="23"/>
        <Button Name="Button_Increment" Content="Increment" HorizontalAlignment="Left" Margin="90,41,0,0" VerticalAlignment="Top" Width="100" Height="23"/>
    </Grid>
</Window>
"@

$XMLReader = New-Object System.Xml.XmlNodeReader $XML
$XMLForm = [Windows.Markup.XamlReader]::Load($XMLReader)
$buttonIncrement = $XMLForm.FindName('Button_Increment')
$buttonRandom = $XMLForm.FindName('Button_Random')
$textBoxValue = $XMLForm.FindName('TextBox_Value')

$buttonRandom.add_click({
    $textBoxValue.Text = Get-Random -Minimum 0 -Maximum 10000
})
$buttonIncrement.add_click({++[Int]$textBoxValue.Text})

$XMLForm.ShowDialog() | Out-Null


dialog('GUI_Interaction',
       [ object        :=
	   GUI_Interaction,
	 parts         :=
	   [ GUI_Interaction :=
	       dialog('Rosetta Code'),
	     Input_field     :=
	       text_item(input_field),
	     Increment       :=
	       button(increment),
	     Random          :=
	       button(random)
	   ],
	 modifications :=
	   [ Input_field := [ label  := 'Value :',
			      length := 28
			    ]
	   ],
	 layout        :=
	   [ area(Input_field,
		  area(54, 24, 251, 24)),
	     area(Increment,
		  area(54, 90, 80, 24)),
	     area(Random,
		  area(230, 90, 80, 24))
	   ],
	 behaviour     :=

	   [
	     Increment := [
			 message := message(@prolog,
					    increment,
					    Input_field )
		       ],
	     Random := [
			 message := message(@prolog,
					    my_random,
					    Input_field)
			  ],
	     Input_field := [
			 message := message(@prolog,
					    input,
					    GUI_Interaction,
					    Increment,
					    @receiver,
					    @arg1)
			  ]
	   ]

       ]).

gui_component :-
	make_dialog(S, 'GUI_Interaction'),
	send(S, open).

increment(Input) :-
	get(Input, selection, V),
	atom_number(V, Val),
	Val1 is Val + 1,
	send(Input, selection, Val1).

my_random(Input) :-
        new(D, dialog('GUI Interaction')),
        send(D, append(label(lbl,'Confirm your choice !'))),
        send(D, append(button(ok, message(D, return, ok)))),
        send(D, append(button(cancel, message(D, return, ko)))),
        send(D, default_button(ok)),
        get(D, confirm, Rval),
        free(D),
        (   Rval = ok
	->  X is random(10000),
	    send(Input, selection, X)
	).

input(Gui, Btn, Input, Selection) :-
	catch( (term_to_atom(T, Selection), number(T), send(Gui, focus, Btn)),
	       _,
	       (   send(@display, inform, 'Please type a number !'),
		   send(Input,clear))).


Enumeration
  #StringGadget
  #Increment
  #Random
EndEnumeration

If OpenWindow(0,#PB_Ignore,#PB_Ignore,180,50,"PB-GUI",#PB_Window_SystemMenu)
  StringGadget(#StringGadget,5,5,170,20,"",#PB_String_Numeric)
  ButtonGadget(#Increment,5,25,80,20, "Increment")
  ButtonGadget(#Random,  90,25,80,20, "Random")
  Repeat
    Event=WaitWindowEvent()
    If Event=#PB_Event_Gadget
      Select EventGadget()
        Case #Increment
          CurrentVal=Val(GetGadgetText(#StringGadget))
          SetGadgetText(#StringGadget,Str(CurrentVal+1))
        Case #Random
          Flag=#PB_MessageRequester_YesNo
          Answer=MessageRequester("Randomize","Are you sure?",Flag)
          If Answer=#PB_MessageRequester_Yes
            SetGadgetText(#StringGadget,Str(Random(#MAXLONG)))
          EndIf
      EndSelect
    EndIf
  Until Event=#PB_Event_CloseWindow
  CloseWindow(0)
EndIf


import random, tkMessageBox
from Tkinter import *
window = Tk()
window.geometry("300x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
def increase():
    s.set(int(s.get())+1)
def rand():
    if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
        s.set(random.randrange(0,5000))
def update(e):
    if not e.char.isdigit():
        tkMessageBox.showerror('Error', 'Invalid input !')
        return "break"
e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind('<Key>', update)
b1 = Button(text="Increase", command=increase, **options )
b1.grid(column=1, row=0, **options)
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()


library(gWidgets)
options(guiToolkit="RGtk2") ## using gWidgtsRGtk2

w <- gwindow("Interaction")

g <- ggroup(cont=w, horizontal=FALSE)
e <- gedit(0, cont=g, coerce.with=as.numeric)
bg <- ggroup(cont=g)

inc_btn <- gbutton("increment", cont=bg)
rdm_btn <- gbutton("random", cont=bg)

addHandlerChanged(e, handler=function(h,...) {
  val <- svalue(e)
  if(is.na(val))
    galert("You need to enter a number", parent=w)
})

addHandlerChanged(inc_btn, handler=function(h,...) {
  val <- svalue(e)
  if(is.na(val))
    galert("Can't increment if not a number", parent=w)
  else
    svalue(e) <- val + 1
})

addHandlerChanged(rdm_btn, handler=function(h,...) {
  if(gconfirm("Really replace value?"))
    svalue(e) <- sample(1:1000, 1)
})


#lang racket/gui

(define frame (new frame% [label "Interaction Demo"]))

(define inp
  (new text-field% [label "Value"] [parent frame] [init-value "0"]
       [callback
        (λ(f ev)
          (define v (send f get-value))
          (unless (string->number v)
            (send f set-value (regexp-replace* #rx"[^0-9]+" v ""))))]))

(define buttons (new horizontal-pane% [parent frame]))
(define inc-b
  (new button% [parent buttons] [label "Increment"]
       [callback (λ (b e) (let* ([v (string->number (send inp get-value))]
                                 [v (number->string (add1 v))])
                            (send inp set-value v)))]))
(define rand-b
  (new button% [parent buttons] [label "Random"]
       [callback (λ (b e) (when (message-box "Confirm" "Are you sure?"
                                             frame '(yes-no))
                            (send inp set-value (~a (random 10000)))))]))

(send frame show #t)


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

my GTK::Simple::App $app .= new(title => 'GUI component interaction');

$app.set-content(
    my $box = GTK::Simple::VBox.new(
        my $value     = GTK::Simple::Entry.new(text => '0'),
        my $increment = GTK::Simple::Button.new(label => 'Increment'),
        my $random    = GTK::Simple::Button.new(label => 'Random'),
    )
);

$app.size-request(400, 100);
$app.border-width = 20;
$box.spacing = 10;

$value.changed.tap: {
    ($value.text ||= '0') ~~ s:g/<-[0..9]>//;
}

$increment.clicked.tap: {
    my $val = $value.text; $val += 1; $value.text = $val.Str
}

$random.clicked.tap: {
    # Dirty hack to work around the fact that GTK::Simple doesn't provide
    # access to GTK message dialogs yet :P
    if run «zenity --question --text "Reset to random value?"» {
        $value.text = (^100).pick.Str
    }
}

$app.run;


Load "guilib.ring"

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

               btn1 = new qpushbutton(win1) {
                      setGeometry(200,200,100,30)
                      settext("Random")
                      setclickevent("Rand()")}

               btn2 = new qpushbutton(win1) {
                      setGeometry(50,200,100,30)
                      settext("Increment")
                      setclickevent("Increment()")}

               lineedit1 = new qlineedit(win1) {
                           setGeometry(10,100,350,30)}
               show()}
exec()}

func Rand
     num = string(random(10000))
     lineedit1.settext(num)

func Increment
     lineedit1{ num = text()}
     num = string(number(num)+1)
     lineedit1.settext(num)


Shoes.app(title: "GUI component interaction") do
  stack do
    textbox = edit_line

    textbox.change do
      textbox.text = textbox.text.gsub(/[^\d]/, '') and alert "Input must be a number!" if textbox.text !~ /^\d*$/
    end

    flow do
      button "Increment" do
        textbox.text = textbox.text.to_i + 1
      end

      button "Random" do
        textbox.text = rand 5000 if confirm "Do you want a random number?"
      end
    end
  end
end


dim dd$(5)                 ' drop down box
for i = 1 to 5
 dd$(i) = "Drop ";i
next i
value$ = "1234"
notes$ = "Rosetta Code
is good"

bf$	= ""

[screen]
cls
html bf$;"
"
html "
Rosetta Code

"
html "Value:	"
     textbox #val,value$,5
html "

Radio	"
     radiogroup #rdo,"1,2,3,4,5",rdo$
                #rdo horizontal(1)
html "

Drop Down	"
     listbox #dd,dd$(),1

html "

Notes	"
     textarea 	#notes,notes$,25,3
html "

"
     button #inc, "Increment", [incr]
     button #rnd, "Random", [rand]
     button #ex, "Exit", [exit]
html "

"
wait

[incr]
value	= val(#val contents$())
value$  = str$(value + 1)
goto [screen]

[rand]
value$ = str$(int(rnd(1) * 10000))
goto [screen]

[exit]
print "Bye"
end


import scala.swing._
import scala.swing.Swing._
import scala.swing.event._

object Interact extends SimpleSwingApplication {
  def top = new MainFrame {
    title = "Rosetta Code >>> Task: component interaction | Language: Scala"

    val numberField = new TextField {
      text = "0" // start at 0
      horizontalAlignment = Alignment.Right
    }

    val incButton = new Button { text = "Increment" }
    val randButton = new Button { text = "Random" }

    // arrange buttons in a grid with 1 row, 2 columns
    val buttonPanel = new GridPanel(1, 2) {
      contents ++= List(incButton, randButton)
    }

    // arrange text field and button panel in a grid with 2 row, 1 column
    contents = new GridPanel(2, 1) { contents ++= List(numberField, buttonPanel) }

    // listen for keys pressed in numberField and button clicks
    listenTo(numberField.keys, incButton, randButton)
    reactions += {
      case kt: KeyTyped if (!kt.char.isDigit) => // if the entered char isn't a digit …
        kt.consume // … eat the event (i.e. stop it from being processed)
      case ButtonClicked(`incButton`) =>
        if (numberField.text.isEmpty) numberField.text = "0"
        // we use BigInt to avoid long overflow/number format exception
        numberField.text = (BigInt(numberField.text) + 1).toString
      case ButtonClicked(`randButton`) =>
        import Dialog._
        numberField.text = showOptions(buttonPanel, message = "Are you sure?",
          title = "Choose an option!", entries = List("Yes", "No", "Cancel"),
          initial = 2) match {
            case Result.Yes => (Long.MaxValue * math.random).toLong.toString
            case _          => numberField.text
          }
    }
    centerOnScreen()
  }
}


|top input vh incButton rndButton|

vh := ValueHolder with:0.

top := StandardSystemView label:'Rosetta GUI interaction'.
top extent:300@100.
top add:((Label label:'Value:') origin: 0 @ 10 corner: 100 @ 40).
top add:(input := EditField origin: 102 @ 10 corner: 1.0 @ 40).
input model:(TypeConverter onNumberValue:vh).
input acceptOnLostFocus:true; acceptOnReturn:true.

top add:((incButton := Button label:'Inc') origin: 10 @ 50 corner: 100 @ 80).
top add:((rndButton := Button label:'Rnd') origin: 110 @ 50 corner: 210 @ 80).

incButton action:[ vh value: (vh value + 1) ].
rndButton action:[ vh value: Random nextInteger ].

top open


package require Tk

###--- Our data Model! ---###
# A single variable will do just fine
set field 0

###--- Lay out the GUI components in our View ---###
# We use the Ttk widget set here; it looks much better on Windows and OSX

# First, a quick hack to make things look even nicer
place [ttk::frame .bg] -relwidth 1 -relheight 1

# A labelled frame containing an entry field constrained to use numbers
pack [ttk::labelframe .val -text "Value"]
pack [ttk::entry .val.ue -textvariable field \
	-validate key -invalidcommand bell \
	-validatecommand {string is integer %P}]
# Now, a pair of buttons
pack [ttk::button .inc -text "increment" -command step]
pack [ttk::button .rnd -text "random" -command random]

###--- Now we define the behaviors, the Controller ---###
# How to respond to a click on the "increment" button
proc step {} {
    global field
    incr field
}
# How to respond to a click on the "random" button
proc random {} {
    global field
    if {[tk_messageBox -type yesno -parent . \
	    -message "Reset to random?"] eq "yes"} {
	set field [expr {int(rand() * 5000)}]
    }
}


bool validate_input(Gtk.Window window, string str){
    int64 val;
    bool ret = int64.try_parse(str,out val);;

    if(!ret){
        var dialog = new Gtk.MessageDialog(window,
       	                                   Gtk.DialogFlags.MODAL,
       	                                   Gtk.MessageType.ERROR,
       	                                   Gtk.ButtonsType.OK,
       	                                   "Invalid value");
        dialog.run();
        dialog.destroy();
    }
    return ret;
}

int main (string[] args) {
    Gtk.init (ref args);

    var window = new Gtk.Window();
    window.title = "Rosetta Code";
    window.window_position = Gtk.WindowPosition.CENTER;
    window.destroy.connect(Gtk.main_quit);
    window.set_default_size(0,0);

    var box = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 1);
    box.set_border_width(1);

    var label = new Gtk.Label ("Value:");

    var entry = new Gtk.Entry();
    entry.set_text("0");   //initialize to zero
    entry.activate.connect (() => {
        // read and validate the entered value
        validate_input(window, entry.get_text());
    });

    // button to increment
    var ib = new Gtk.Button.with_label("increment");
    ib.clicked.connect(() => {
        // read and validate the entered value
        var str = entry.get_text();
        if(validate_input(window, str)){
            entry.set_text((int.parse(str)+1).to_string());
        }
    });

    // button to put in a random value if confirmed
    var rb = new Gtk.Button.with_label("random");
    rb.clicked.connect (() => {
        var dialog = new Gtk.MessageDialog(window,
        	                               Gtk.DialogFlags.MODAL,
        	                               Gtk.MessageType.QUESTION,
        	                               Gtk.ButtonsType.YES_NO,
        	                               "set random value");
        var answer = dialog.run();
        dialog.destroy();
        if(answer == Gtk.ResponseType.YES){
            entry.set_text(Random.int_range(0,10000).to_string());
        }
    });

    box.pack_start(label, false, false, 2);
    box.pack_start(entry, false, false, 2);
    box.pack_start(ib, false, false, 2);
    box.pack_start(rb, false, false, 2);

    window.add(box);

    window.show_all();

    Gtk.main ();
    return 0;
}


VERSION 5.00
Begin VB.Form Form1
   Caption         =   "Form1"
   ClientHeight    =   2265
   ClientLeft      =   60
   ClientTop       =   600
   ClientWidth     =   2175
   LinkTopic       =   "Form1"
   ScaleHeight     =   2265
   ScaleWidth      =   2175
   StartUpPosition =   3  'Windows Default
   Begin VB.CommandButton cmdRnd
      Caption         =   "Random"
      Height          =   495
      Left            =   120
      TabIndex        =   2
      Top             =   1680
      Width           =   1215
   End
   Begin VB.CommandButton cmdInc
      Caption         =   "Increment"
      Height          =   495
      Left            =   120
      TabIndex        =   1
      Top             =   1080
      Width           =   1215
   End
   Begin VB.TextBox txtValue
      Height          =   495
      Left            =   120
      TabIndex        =   0
      Text            =   "0"
      Top             =   240
      Width           =   1215
   End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'-----user-written code begins here; everything above this line is hidden in the IDE-----
Private Sub Form_Load()
    Randomize Timer
End Sub

Private Sub cmdRnd_Click()
    If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11)
End Sub

Private Sub cmdInc_Click()
    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1
End Sub

Private Sub txtValue_KeyPress(KeyAscii As Integer)
    Select Case KeyAscii
        Case 8, 43, 45, 48 To 57
            'backspace, +, -, or number
        Case Else
            KeyAscii = 0
    End Select
End Sub


@1Rosetta code program.
@aPROGRAM guicomponent CONTEXT VOID USE standard
BEGIN
@<Included [email protected]>
@<Modes in the outer [email protected]>
@<Names in the outer [email protected]>
@<Callback [email protected]>
@<Other [email protected]>
@<Main [email protected]>
END
FINISH

@ This file contains all the macros for the Xforms library procedures.
Only macros which are called will actually generate code.

@[email protected]>

@ Initialise the Xforms library, create the form, set the value in the
input field, show the form and hand control to the Xforms library.

@<[email protected]>=
open(argf,"",arg channel);
fl initialize(argc,argv,"GUI interact",NIL,0);
main form:=create form main;
fl set input(main input OF main form,float(value,10,5,2));
fl show form(main OF main form,fl place center,fl fullborder,"GUI interact");
fl do forms

@ The input value will be stored in !value!.

@<[email protected]>=
REF FDMAIN main form;
REAL value:=0;
FILE argf;

@1The form.
The following section contains declarations for the form. It was output by
the program 'fdtow68' using the file output by the 'fdesign' program.

@2Modes.
This is the mode declaration for form !main!.

@<[email protected]>=
MODE FDMAIN = STRUCT(
   REF FLFORM main,
   REF FLOBJECT main increment,
   REF FLOBJECT main input,
   REF FLOBJECT main random);

@ This procedure creates form !main!.

@<[email protected]>=
PROC create form main = REF FDMAIN:
BEGIN
   REF FLOBJECT obj;
   REF FDMAIN fdui:=HEAP FDMAIN;
   OP(REF FDMAIN)CBPTR TOCBPTR = BIOP 99;
   main OF fdui:=fl bgn form(fl no box,259,126);
   obj:=fl add box(fl up box,0,0,259,126,"");
      fl set object color(obj,fl col1,fl col1);
   main input OF fdui:=obj:=fl add input(fl float input,78,18,160,35,"Value");
      fl set object lsize(obj,fl normal size);
      fl set object callback(obj,main cb,1);
      fl set object return(obj,fl return end changed);
   main increment OF fdui:=obj:=fl add button(fl normal button,20,70,100,40,"Increment");
      fl set object lsize(obj,fl normal size);
      fl set object callback(obj,main cb,2);
      fl set button mouse buttons(obj,BIN 7);
   main random OF fdui:=obj:=fl add button(fl normal button,140,70,100,40,"Random");
      fl set object lsize(obj,fl normal size);
      fl set object callback(obj,main cb,3);
      fl set button mouse buttons(obj,BIN 7);
   fl end form;
   fl adjust form size(main OF fdui);
   fdui OF main OF fdui:=TOCBPTR fdui;
   fdui
END; #create form main#

@2Callback procedures.
There is only one callback procedure.

@<[email protected]>=
PROC main cb = (REF FLOBJECT obj,INT data)VOID:
CASE data
IN
	#input#
	BEGIN
		FILE mf;
		open(mf,fl get input(main input OF main form)+blank,mem channel);
		get(mf,value);  #convert the input to binary#
		close(mf)
	END
	,
	#increment#
	(
		value +:= 1;
		fl set input(main input OF main form,float(value,10,5,2))
	)
	,
	#random#
	(
		value:=random;
		fl set input(main input OF main form,float(value,10,5,2))
	)
ESAC; #main cb#

@2Macro calls.
Here are all the Xforms macro calls in alphabetical order.

@<[email protected]>=
macro fl add box;
macro fl add button;
macro fl add input;
macro fl adjust form size;
macro fl bgn form;
macro fl do forms;
macro fl end form;
macro fl get border width;
macro fl get input;
macro fl initialize;
macro fl set border width;
macro fl set button mouse buttons;
macro fl set input;
macro fl set object callback;
macro fl set object color;
macro fl set object lsize;
macro fl set object return;
macro fl show form;

@ The end.


import "graphics" for Canvas, Color
import "input" for Mouse, Keyboard
import "dome" for Window
import "random" for Random
import "./polygon" for Polygon

var Rand = Random.new()

class Button {
    construct new(x, y, w, h, legend, c, oc, lc) {
        var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]]
        _rect = Polygon.quick(vertices)
        _x = x
        _y = y
        _w = w
        _h = h
        _legend = legend
        _c = c
        _oc = oc
        _lc = lc
    }

    draw() {
        _rect.drawfill(_c)
        _rect.draw(_oc)
        var l = Canvas.getPrintArea(_legend)
        var lx = ((_w - l.x)/2).truncate
        lx = (lx > 0) ? _x + lx : _x + 1
        var ly = ((_h - l.y)/2).truncate
        ly = (ly > 0) ? _y + ly : _y + 1
        Canvas.print(_legend, lx, ly, _lc)
    }

    justClicked { Mouse["left"].justPressed && _rect.contains(Mouse.position.x, Mouse.position.y) }
}

class TextBox {
    construct new(x, y, w, h, label, c, oc, lc) {
        var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]]
        _rect = Polygon.quick(vertices)
        _x = x
        _y = y
        _w = w
        _h = h
        _label = label
        _c = c
        _oc = oc
        _lc = lc
        _text = ""
    }

    text     { _text }
    text=(t) { _text = t }

    draw() {
        _rect.drawfill(_c)
        _rect.draw(_oc)
        var l = Canvas.getPrintArea(_label).x
        var lx = _x - l - 7
        if (lx < 1) {
             lx = 1
             _label = _label[0..._x]
        }
        Canvas.print(_label, lx, _y, _lc)
        Canvas.getPrintArea(_label).x
        Canvas.print(_text, _x + 3, _y + 1, Color.black)
    }
}

class GUIComponentInteraction {
    construct new() {
        Window.title = "GUI component interaction"
        _btnIncrement = Button.new(60, 40, 80, 80, "Increment", Color.red, Color.blue, Color.white)
        _btnRandom = Button.new(180, 40, 80, 80, "Random", Color.green, Color.blue, Color.white)
        _txtValue = TextBox.new(140, 160, 80, 8, "Value", Color.white, Color.blue, Color.white)
        _txtValue.text = "0"
        Keyboard.handleText = true
        _waiting = false
    }

    init() {
        drawControls()
    }

    update() {
        if (_waiting) {
            if (Keyboard["Y"].justPressed) {
                var rn = Rand.int(1000)  // max 999 say
                _txtValue.text = rn.toString
                _waiting = false
            } else if (Keyboard["N"].justPressed) {
                _waiting = false
            }
        } else if (_btnIncrement.justClicked) {
            var number = Num.fromString(_txtValue.text) + 1
            _txtValue.text = number.toString
        } else if (_btnRandom.justClicked) {
            Canvas.print("Reset to a random number y/n?", 60, 200, Color.white)
            _waiting = true
        } else if ("0123456789".any { |d| Keyboard[d].justPressed }) {
            if (_txtValue.text != "0") {
                _txtValue.text = _txtValue.text + Keyboard.text
            } else {
                _txtValue.text = Keyboard.text
            }
        }
    }

    draw(alpha) {
        if (!_waiting) drawControls()
    }

    drawControls() {
        Canvas.cls()
        _btnIncrement.draw()
        _btnRandom.draw()
        _txtValue.draw()
    }
}

var Game = GUIComponentInteraction.new()


package
{
	import flash.display.Sprite;

	[SWF(width="640", height="480")]
	public class GreyscaleBars extends Sprite
	{

		public function GreyscaleBars()
		{
			_drawRow(8, 0);
			_drawRow(16, stage.stageHeight/4, true);
			_drawRow(32, stage.stageHeight/2);
			_drawRow(64, stage.stageHeight/4 * 3, true);
		}

		private function _drawRow(nbSteps : uint, startingY : uint, reverse : Boolean = false) : void {

			for (var i : int = 0; i < nbSteps; i++) {
				graphics.beginFill(0x00, reverse ? 1 - (i/nbSteps) : (i/nbSteps));
				graphics.drawRect(i * stage.stageWidth / nbSteps, startingY, stage.stageWidth/nbSteps, stage.stageHeight/4);
				graphics.endFill();
			}
		}
	}
}


with Gtk.Window;   use Gtk.Window;
with Gtk.Enums;
with Gtk.Handlers;
with Gtk.Main;
with Gdk;
with Gdk.Event;
with Glib;         use Glib;
with Cairo;        use Cairo;
with Gdk.Cairo;
pragma Elaborate_All (Gtk.Handlers);

procedure Greyscale is

   Win    : Gtk_Window;
   Width  : constant := 640;
   Height : constant := 512;

   package Handlers is new Gtk.Handlers.Callback (Gtk_Window_Record);
   package Event_Cb is new Gtk.Handlers.Return_Callback (
      Widget_Type => Gtk_Window_Record,
      Return_Type => Boolean);

   procedure Quit (Win : access Gtk_Window_Record'Class) is
      pragma Warnings (Off, Win);
   begin
      Gtk.Main.Main_Quit;
   end Quit;

   function Expose
     (Drawing : access Gtk_Window_Record'Class;
      Event   : Gdk.Event.Gdk_Event)
      return    Boolean
   is
      subtype Dub is Glib.Gdouble;
      Cr       : Cairo_Context;
      Revert   : Boolean;
      Grey     : Dub;
      DH       : constant Dub := Dub (Height) / 4.0;
      X, Y, DW : Dub;
      N        : Natural;

   begin
      Cr := Gdk.Cairo.Create (Get_Window (Drawing));
      for Row in 1 .. 4 loop

         N      := 2 ** (Row + 2);
         Revert := (Row mod 2) = 0;
         DW     := Dub (Width) / Dub (N);
         X      := 0.0;
         Y      := DH * Dub (Row - 1);
         for B in 0 .. (N - 1) loop
            Grey := Dub (B) / Dub (N - 1);
            if Revert then
               Grey := 1.0 - Grey;
            end if;
            Cairo.Set_Source_Rgb (Cr, Grey, Grey, Grey);
            Cairo.Rectangle (Cr, X, Y, DW, DH);
            Cairo.Fill (Cr);
            X := X + DW;
         end loop;
      end loop;
      Cairo.Destroy (Cr);
      return False;
   end Expose;

begin
   Gtk.Main.Set_Locale;
   Gtk.Main.Init;

   Gtk_New (Win);
   Gtk.Window.Initialize (Win, Gtk.Enums.Window_Toplevel);
   Set_Title (Win, "Greyscale with GTKAda");
   Set_Default_Size (Win, Width, Height);
   Set_App_Paintable (Win, True);
   --  Attach handlers
   Handlers.Connect (Win, "destroy", Handlers.To_Marshaller (Quit'Access));
   Event_Cb.Connect
     (Win,
      "expose_event",
      Event_Cb.To_Marshaller (Expose'Access));

   Show_All (Win);

   Gtk.Main.Main;
end Greyscale;


#include <flow.h>
#include <flow-term.h>

#define  SPACE(_T_,_N_)   REPLICATE( " ", {_T_}DIV-INTO(_N_) )

DEF-MAIN(argv,argc)
   CLR-SCR
   GOSUB( Print Grey Scale )
END

RUTINES

DEF-FUN( Print Grey Scale )
  SET( nrcolors, 8 )
  SET( direction, 1 )
  MSET( quarter, color )
  LOCATE( 0, 0 )
  FOR( LT?( quarter, 4 ), ++quarter )
      SET( height, 0 )
      FOR( LT?( height, 5 ), ++height )
          SET( width, 0 )
          FOR( LT?( width, nrcolors ), ++width )
              LET( color := CEIL( MUL( width, DIV( 255, SUB(nrcolors,1) ) ) ) )
              WHEN( NOT( MOD( direction, 2 ) ) ){
                  LET( color := SUB( 255, color ) )
              }
               PRN( COLOR-RGBB( color, color, color) SPACE( 128, nrcolors ) )
          NEXT
          PRNL("\OFF")
      NEXT
      nrcolors*=2
      ++direction
  NEXT
RET


100 SET WINDOW 0,1279,0,1023
110 REM (0,0) is the bottom left of the display
120 SET AREA COLOR 1 ! Select color one for drawing
130 FOR row=1 TO 4
140    LET n=IP(2^(row+2))
150    LET w=IP(1280/n)
160    LET py=IP(256*(4-row))
170    FOR b=0 TO n-1
180       LET g=b/(n-1)
190       IF n=16 OR n=64 THEN LET g=1-g
200       SET COLOR MIX(1) g,g,g    !  Reprogram color 1 to the gray we want
210       PLOT AREA: w*b,py; w*b+w,py; w*b+w,py+256; w*b,py+256
220    NEXT b
230 NEXT row
240 END


h	:= A_ScreenHeight
w	:= A_ScreenWidth
pToken	:= gdip_Startup()
hdc	:= CreateCompatibleDC()
hbm	:= CreateDIBSection(w, h)
obm	:= SelectObject(hdc, hbm)
G	:= Gdip_GraphicsFromHDC(hdc)

OnExit, Exit

Gui +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
hwnd	:= WinExist()
Gui Show, NA

columnHeight := h/4

Loop 4
{
	columnY		:= (A_Index-1) * columnHeight
	columnCount	:= 2**(A_Index+2)
	colorgap	:= 255 / (columnCount-1)
	columnWidth	:= w/ColumnCount
	If (A_Index & 1)
		colorComp := 0
	else
		colorComp := 255
		,colorgap *= -1
	MsgBox % colorGap * columnCount
	Loop % columnCount
	{
		columnX := (A_Index-1) * columnWidth
		pBrush := Gdip_BrushCreateSolid(QColor(colorComp, colorComp, colorComp))
		Gdip_FillRectangle(G, pBrush, columnX, columnY, columnWidth, columnHeight)
		Gdip_DeleteBrush(pBrush)
		colorComp += colorgap
	}
	SetFormat, IntegerFast, hex
	SetFormat, IntegerFast, D
}

UpdateLayeredWindow(hwnd, hdc, 0, 0, W, H)

SelectObject(hdc, obm)
DeleteObject(hbm)
DeleteDC(hdc)
Gdip_DeleteGraphics(G)
Return

Esc::
Exit:
Gdip_Shutdown(pToken)
ExitApp

QColor(r, g, b){
	return 0xFF000000 | (r << 16) | (g << 8) | (b)
}


BEGIN {
  nrcolors = 8
  direction = 1

  for (quarter=0; quarter<4; quarter++) {
    for (height=0; height<5; height++) {
      for (width=0; width<nrcolors; width++) {
        # gradient goes white-to-black or black-to-white depending on direction
        if (direction % 2)
          color = width * (255 / (nrcolors-1))
        else
          color = 255 - width * (255 / (nrcolors-1))

        # print (ANSI) RGB greysacle color and amount of spaces
        printf("\033[48;2;%d;%d;%dm%*s", color, color, color, 64 / nrcolors, " ")
      }
      # reset color and print newline
      printf("\033[0m\n")
    }

    # 8, 16, 32, 64 colors and alternating direction of gradient
    nrcolors *= 2
    direction++
  }
}


h=ceil(graphheight/4)
for row=1 to 4
  w=ceil(graphwidth/(8*row))
  c=255/(8*row-1)
  for n = 0 to (8*row-1)
     color 255-c*n,255-c*n,255-c*n
     if row/2 = int(row/2) then color c*n,c*n,c*n
     rect n*w,h*(row-1),w,h
  next n
next row


MODE 8:REM 640 x 512 pixel display mode: BBC BASIC gives 2 graphics points per pixel
REM (0,0) is the bottom left of the display
GCOL 1  :REM Select colour one for drawing
FOR row%=1 TO 4
  n%=2^(row%+2)
  w%=1280/n%
  py%=256*(4-row%)
  FOR b%=0 TO n%-1
    g%=255*b%/(n%-1)
    IF n%=16 OR n%=64 THEN g%=255-g%
    COLOUR 1,g%,g%,g%  : REM Reprogram colour 1 to the grey we want
    RECTANGLE FILL w%*b%,py%,w%,256
  NEXT b%
NEXT row%


#include <gtk/gtk.h>
/* do some greyscale plotting */
void gsplot (cairo_t *cr,int x,int y,double s) {
    cairo_set_source_rgb (cr,s,s,s);
    cairo_move_to (cr,x+0.5,y);
    cairo_rel_line_to (cr,0,1);
    cairo_stroke (cr);
}
/* make a shaded widget */
gboolean expose_event (GtkWidget *widget,GdkEventExpose *event,gpointer data) {
    int r,c,x=0;
    cairo_t *cr;
    cr = gdk_cairo_create (widget->window);
    cairo_scale (cr,5,50);
    cairo_set_line_width (cr,1);
    for (r=0;r<4;r++) {
        c = (r&1)*64-(r%2);
        do gsplot (cr,x++%64,r,c/(1<<(3-r))/(8*(1<<r)-1.0));
        while ((c+=2*!(r%2)-1)!=(!(r%2))*64-(r%2));
    } cairo_destroy (cr);
    return FALSE;
}
/* main */
int main (int argc, char *argv[]) {
    GtkWidget *window;
    gtk_init (&argc, &argv);
    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    g_signal_connect (window, "expose-event",G_CALLBACK (expose_event), NULL);
    g_signal_connect (window, "delete-event", G_CALLBACK(gtk_main_quit), NULL);
    gtk_window_set_default_size (GTK_WINDOW(window), 320, 200);
    gtk_widget_set_app_paintable (window, TRUE);
    gtk_widget_show_all (window);
    gtk_main ();
    return 0;
}


using System;
using System.Drawing;
using System.Windows.Forms;
static class Program { static void Main() { Application.Run(new FullScreen()); } }
public sealed class FullScreen : Form
{
    const int ColorCount = 256;
    public FullScreen()
    {
        FormBorderStyle = FormBorderStyle.None;
        WindowState = FormWindowState.Maximized;
        KeyPress += (s, e) => Application.Exit();
        BackgroundImage = ColorBars(Screen.FromControl(this).Bounds);
    }
    private static Bitmap ColorBars(Rectangle size)
    {
        var colorBars = new Bitmap(size.Width, size.Height);
        Func<int, int, int> forwardColor = (x, divs) => (int)(x * ((float)divs / size.Width)) * ColorCount / divs;
        Func<int, int, int> reverseColor = (x, divs) => ColorCount - 1 - forwardColor(x, divs);
        Action<int, int, int> setGray = (x, y, gray) => colorBars.SetPixel(x, y, Color.FromArgb(gray, gray, gray));
        Action<int, int, int> setForward = (x, y, divs) => setGray(x, y, forwardColor(x, divs));
        Action<int, int, int> setReverse = (x, y, divs) => setGray(x, y, reverseColor(x, divs));
        int verticalStripe = size.Height / 4;
        for (int x = 0; x < size.Width; x++)
        {
            for (int y = 0; y < verticalStripe; y++) setForward(x, y, 8);
            for (int y = verticalStripe; y < verticalStripe * 2; y++) setReverse(x, y, 16);
            for (int y = verticalStripe * 2; y < verticalStripe * 3; y++) setForward(x, y, 32);
            for (int y = verticalStripe * 3; y < verticalStripe * 4; y++) setReverse(x, y, 64);
        }
        return colorBars;
    }
}


MODULE RosettaGreys;
IMPORT Views, Ports, Properties, Controllers, StdLog;

CONST
	(* orient values *)
	left = 1;
	right = 0;

TYPE
	View = POINTER TO RECORD
		(Views.View)
	END;

	PROCEDURE LoadGreyPalette(VAR colors: ARRAY OF Ports.Color);
	VAR
		i, step, hue: INTEGER;
	BEGIN
		step := 255 DIV LEN(colors);
		FOR i := 1 TO LEN(colors) DO
			hue := i * step;
			colors[i - 1] := Ports.RGBColor(hue,hue,hue)
		END
	END LoadGreyPalette;

	PROCEDURE (v: View) Restore(f: Views.Frame; l, t, r, b: INTEGER);
	VAR
		i, w, h: INTEGER;
		colors: POINTER TO ARRAY OF Ports.Color;

		PROCEDURE Draw(row, cols: INTEGER; orient: INTEGER);
		VAR
			w: INTEGER;
			c: Ports.Color;
		BEGIN
			NEW(colors,cols);LoadGreyPalette(colors^);
			w := (r - l) DIV cols;
			FOR i := 1 TO cols DO
				IF orient = left THEN c := colors[cols - i] ELSE c := colors[i - 1] END;
				f.DrawRect((l + w) * (i - 1), t + (row - 1) * h, (l + w) * i, t + row * h,Ports.fill,c);
			END
		END Draw;
	BEGIN
		h := (b - t) DIV 4;
		Draw(1,8,right);
		Draw(2,16,left);
		Draw(3,32,right);
		Draw(4,64,left);
	END Restore;

	PROCEDURE (v: View) HandlePropMsg(VAR msg: Properties.Message);
	CONST
		min = 5 * Ports.mm;
		max = 50 * Ports.mm;
	VAR
		stdProp: Properties.StdProp;
		prop: Properties.Property;
	BEGIN
		WITH msg: Properties.SizePref DO
			IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
				msg.w := 100 * Ports.mm;
				msg.h := 35 * Ports.mm
			END
		ELSE (* ignore other messages *)
		END
	END HandlePropMsg;

	PROCEDURE Deposit*;
	VAR
		v: View;
	BEGIN
		NEW(v);
		Views.Deposit(v)
	END Deposit;
END RosettaGreys.

 "RosettaGreys.Deposit; StdCmds.Open"


n = 8
for row range 4
  sz = 100 / n
  for i range n
    c = i / (n - 1)
    if row mod 2 = 1
      c = 1 - c
    .
    color3 c c c
    move sz * i row * 25
    rect sz + 1 25
  .
  n *= 2
.


>function grayscale(y1,y2,n,direction=1) ...
$  loop 0 to n-1;
$  s=#/(n-1); barcolor(rgb(s,s,s));
$  if direction==1 then plotbar(#/n,y1,1/n,y2-y1);
$  else plotbar(1-(#+1)/n,y1,1/n,y2-y1);
$  endif;
$  end;
$endfunction
>function grayscales () ...
$  aspect(2); barstyle("#");
$  window(0,0,1023,1023); margin(0); setplot(0,1,0,1);
$  clg;
$  hold on;
$  grayscale(3/4,1,8,1);
$  grayscale(1/2,3/4,14,-1);
$  grayscale(1/4,1/2,32,1);
$  grayscale(0,1/4,64,-1);
$  hold off;
$endfunction
>grayscales:


' version 01-09-2017
'    compile with: fbc -s console
' or compile with: fbc -s gui
' hit any key to stop

Dim As UInteger d, blocks, blocksize, ps, col, h, w, x, y1, y2

ScreenInfo w, h
' create display size window, 8bit color (palette), no frame
ScreenRes w, h, 8,, 8

For x = 0 To 255        ' create grayscale palette for
    Palette x, x, x, x  ' the window we just opened
Next

h = h \ 4 : y2 = h -1

If w Mod 64 <> 0 Then w -= (w Mod 64)
blocks = 8 : blocksize = w \ 8

For ps = 1 To 4
    For x = 0 To blocks -1
        col = 255 * x \ (blocks -1)              ' from black to white
        If (ps And 1) = 0 Then col = 255 - col   ' from white to black
        Line (x * blocksize, y1) - (((x +1) * blocksize) -1, y2), col, bf
    Next
    y1 += h : y2 += h
    blocks *= 2 : blocksize \= 2
Next

' empty keyboard buffer
While Inkey <> "" : Wend

Sleep
End


fakewidth =!= dummy

g = new graphics
g.antialiased[false]
drawBars[g, 0, 1, 0, 1/4, 8]
drawBars[g, 1, 0, 1/4, 1/2, 16]
drawBars[g, 0, 1, 1/2, 3/4, 32]
drawBars[g, 1, 0, 3/4, 1, 64]
g.show[640,480,1]  // No portable fullscreen mode; user must maximize window.

drawBars[g is graphics, leftColor, rightColor, top, bottom, steps] :=
{
   colorStep = (rightColor - leftColor) / steps
   color = leftColor
   for i=0 to steps-1
   {
      g.color[color, color, color]
      g.fillRectSides[i/dummy/steps, top, (i+1)/dummy/steps, bottom]
      color = color + colorStep
   }
}


Public Sub Form_Open()
Dim iRow, iCol, iClr As Integer                                     'For Row, Column and Colour
Dim iInc As Integer = 4                                             'To calculate RGB colour
Dim h1Panel As Panel                                                'Panels to display colours

With Me                                                             'Setup the Form
  .Arrangement = Arrange.Row                                        'Arrange children in rows
  .Border = False                                                   'No Border
  .Height = Desktop.Height                                          'Fill the screen
  .Width = Desktop.Width                                            'Fill the screen
  .Fullscreen = True                                                'Set the Form to Fullscreen
End With

For iRow = 1 To 4                                                   'For each row..
  iInc += iInc                                                      'Increase iInc by itself
  For iCol = 0 To iInc - 1                                          'For each column..
    iClr = iCol * (256 / iInc)                                      'Set the RGB colour
    If iRow = 2 Or iRow = 4 Then iClr = 255 - (iCol * (256 / iInc)) 'If row 2 or 4 then reverse the colours
    h1Panel = New Panel(Me)                                         'Create a new Panel
    With h1Panel                                                    'With the Panel..
      .Width = Desktop.Width / iInc                                 'Set the width
      .Height = Desktop.Height / 4                                  'Set the height
      .Background = Color.RGB(iClr, iClr, iClr)                     'Set the Background colour
      .Border = Border.Plain                                        'Set a Border (It's easier to see the colour changes)
    End With
  Next
Next

End


package main

import (
    "github.com/fogleman/gg"
    "math"
)

func greyBars(dc *gg.Context) {
    run := 0
    colorComp := 0.0 // component of the color
    for colCount := 8; colCount < 128; colCount *= 2 {
        // by this gap we change the background color
        colorGap := 255.0 / float64(colCount-1)
        colWidth := float64(dc.Width() / colCount)
        colHeight := float64(dc.Height() / 4)
        // switches color directions with each iteration of for loop
        if run%2 == 0 {
            colorComp = 0.0
        } else {
            colorComp = 255.0
            colorGap = -colorGap
        }
        xstart, ystart := 0.0, colHeight*float64(run)
        for i := 0; i < colCount; i++ {
            icolor := int(math.Round(colorComp)) // round to nearer integer
            dc.SetRGB255(icolor, icolor, icolor)
            dc.DrawRectangle(xstart, ystart, colWidth, colHeight)
            dc.Fill()
            xstart += colWidth
            colorComp += colorGap
        }
        run++
    }
}

func main() {
    dc := gg.NewContext(640, 320)
    greyBars(dc)
    dc.SavePNG("greybars.png")
}


import Graphics.UI.Gtk
import Graphics.UI.Gtk.Gdk.GC
import Control.Monad.Trans (liftIO)

-- click on the window to exit.

main = do
    initGUI

    window <- windowNew

    buf <- pixbufNewFromXPMData bars

    widgetAddEvents window [ButtonPressMask]
    on window objectDestroy mainQuit
    on window exposeEvent (paint buf)
    on window buttonPressEvent $
        liftIO $ do { widgetDestroy window; return True }

    windowFullscreen window
    widgetShowAll window

    mainGUI

paint :: Pixbuf -> EventM EExpose Bool
paint buf = do
    pix <- eventWindow
    liftIO $ do
        (sx, sy) <- drawableGetSize pix
        newBuf <- pixbufScaleSimple buf sx sy InterpNearest
        gc <- gcNewWithValues pix newGCValues
        drawPixbuf pix gc newBuf 0 0 0 0 (-1) (-1) RgbDitherNone 0 0
        return True

bars :: [String]
bars = [
    "64 4 65 1 1 1","  c None","A c #000000",
    "C c #080808","D c #0C0C0C","E c #101010","F c #141414",
    "G c #181818","H c #1C1C1C","I c #202020","J c #242424",
    "K c #282828","L c #2C2C2C","M c #303030","N c #343434",
    "O c #383838","P c #3C3C3C","Q c #404040","R c #444444",
    "S c #484848","T c #4C4C4C","U c #505050","V c #545454",
    "W c #585858","X c #5C5C5C","Y c #606060","Z c #646464",
    "a c #686868","b c #6C6C6C","c c #707070","d c #747474",
    "e c #787878","f c #7C7C7C","g c #808080","h c #848484",
    "i c #888888","j c #8C8C8C","k c #909090","l c #949494",
    "m c #989898","n c #9C9C9C","o c #A0A0A0","p c #A4A4A4",
    "q c #A8A8A8","r c #ACACAC","s c #B0B0B0","t c #B4B4B4",
    "u c #B8B8B8","v c #BCBCBC","w c #C0C0C0","x c #C4C4C4",
    "y c #C8C8C8","z c #CCCCCC","0 c #D0D0D0","1 c #D4D4D4",
    "2 c #D8D8D8","3 c #DCDCDC","4 c #E0E0E0","5 c #E4E4E4",
    "6 c #E8E8E8","7 c #ECECEC","8 c #F0F0F0","9 c #F4F4F4",
    ". c #F8F8F8","+ c #FCFCFC","* c #FFFFFF",
    "AAAAAAAAJJJJJJJJRRRRRRRRZZZZZZZZhhhhhhhhppppppppxxxxxxxx********",
    "****88881111xxxxttttppppllllhhhhddddZZZZVVVVRRRRNNNNJJJJFFFFAAAA",
    "AADDFFHHJJLLNNPPRRTTVVXXZZbbddffhhjjllnnpprrttvvxxzz11336688..**",
    "*+.9876543210zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCA"
     ]


link graphics,printf,numbers

procedure main()
   DrawTestCard(GreyScale_TestCard())
   WDone()
end

procedure greyscale(l,h,s)               #: generate s greys over range l:h
	every i := round(l to h+1 by ((h-l)/(s-1.))) do
	   suspend sprintf("%d,%d,%d",i,i,i)  # return rgb black-grey-white
end

procedure GreyScale_TestCard()           #: return greyscale testcard
   TC := testcard(,"GreyScale Test Card",
                  width := 800, height := 600,
                  list(numbands := 4) )
   maxv := 2^16-1                                      # largest colour value
   every (iv := [], i := 1 to numbands) do {           # for each band
      every put(v := [], greyscale(0,maxv,2^(2+i)))    # compute greyscale
	  put(iv, if i%2 = 0 then v else reverse(v))   # switch directions
	  }

   every r := height/numbands * ((i := 1 to numbands)-1) + 1 do {
      TC.bands[i] := band(r,[])
      every c := width/(*iv[i]) * ((j := 1 to *iv[i])-1) + 1 do
         put(TC.bands[i].bars, bar( c, iv[i,j]))
      put((TC.bands[i]).bars, bar(width))              # right sentinal
      }
   put(TC.bands,band(height))                          # bottom sentinal
   return TC
end


   load 'viewmat'
   size=. 2{.".wd'qm' NB. J6
   size=. getscreenwh_jgtk_ '' NB. J7
   rows=. (2^3+i.4),._1^i.4
   bars=. ((64%{.)#[:(<:@|%~i.)*/)"1 rows
   togreyscale=. (256#. [:<.255 255 255&*)"0
   'rgb' viewmat (4<[email protected]%~{:size)# (64<[email protected]%~{.size)#"1 togreyscale bars


import javax.swing.* ;
import java.awt.* ;

public class Greybars extends JFrame {
   private int width ;
   private int height ;

   public Greybars( )  {
      super( "grey bars example!" ) ;
      width = 640 ;
      height = 320 ;
      setSize( width , height ) ;
      setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ) ;
      setVisible( true ) ;
    }

    public void paint ( Graphics g ) {
      int run = 0 ;
      double colorcomp = 0.0 ; //component of the color
      for ( int columncount = 8 ; columncount < 128 ; columncount *= 2 ) {
	 double colorgap = 255.0 / (columncount - 1) ; //by this gap we change the background color
	 int columnwidth = width / columncount ;
	 int columnheight = height / 4 ;
	 if ( run % 2 == 0 ) //switches color directions with every for loop
	    colorcomp = 0.0 ;
	 else {
	    colorcomp = 255.0 ;
	    colorgap *= -1.0 ;
	 }
	 int ystart = 0 + columnheight * run ;
	 int xstart = 0 ;
	 for ( int i = 0 ; i < columncount ; i++ ) {
            int icolor = (int)Math.round(colorcomp) ; //round to nearer integer
	    Color nextColor = new Color( icolor , icolor, icolor ) ;
	    g.setColor( nextColor ) ;
	    g.fillRect( xstart , ystart , columnwidth , columnheight ) ;
	    xstart += columnwidth ;
	    colorcomp += colorgap ;
	 }
	 run++ ;
      }
    }

    public static void main( String[ ] args ) {
       Greybars gb = new Greybars( ) ;
    }
}


<html><body>
<script type="text/javascript">
var width = 640; var height = 400;
var c = document.createElement("canvas");
c.setAttribute('id',    'myCanvas');
c.setAttribute('style', 'border:1px solid black;');
c.setAttribute('width',  width);
c.setAttribute('height', height);
document.body.appendChild(c);
var ctx = document.getElementById('myCanvas').getContext("2d");

var columnCount = 8;    // number of columns
var rowCount    = 4;    // number of rows
var direction   = 1;    // 1 = from left to right, 0 = from right to left
var blackLeft   = 1;    // black is left: 1 = true, 0 = false
for(var j = 0; j < rowCount; j++){
    for(var i = 0; i < columnCount; i++){
        ctx.fillStyle = 'rgba(0,0,0,'+ (blackLeft-(1/(columnCount-1)*i))*direction +')';
        ctx.fillRect(
            (width/columnCount)*i,(height/rowCount)*j,
            (width/columnCount),(height/rowCount)
            );
        }
    columnCount *= 2;
    direction *= -1;
    blackLeft = blackLeft ? 0 : 1;
    }
</script>
</body></html>


using Gtk, Cairo, ColorTypes

function generategrays(n, screenwidth)
    verts = Vector{RGB}()
    hwidth = Int(ceil(screenwidth/n))
    for x in 00:Int(floor(0xff/(n-1))):0xff
        rgbgray = RGB(x/255, x/255, x/255)
        for i in 1:hwidth
            push!(verts, rgbgray)
        end
    end
    verts
end

function drawline(ctx, p1, p2, color, width)
    move_to(ctx, p1.x, p1.y)
    set_source(ctx, color)
    line_to(ctx, p2.x, p2.y)
    set_line_width(ctx, width)
    stroke(ctx)
end

const can = @GtkCanvas()
const win = GtkWindow(can, "Grayscale bars/Display", 400, 400)
fullscreen(win)  # start full screen, then reduce to regular window in 5 seconds.

draw(can) do widget
    ctx = getgc(can)
    h = height(can)
    w = width(can)
    gpoints = generategrays(8, w)
    for (i, x) in enumerate(0:w-1)
        drawline(ctx, Point(x, 0.25*h), Point(x, 0), gpoints[i], 1)
    end
    gpoints = reverse(generategrays(16, w))
    for (i, x) in enumerate(0:w-1)
        drawline(ctx, Point(x, 0.5*h), Point(x, 0.25*h), gpoints[i], 1)
    end
    gpoints = generategrays(32, w)
    for (i, x) in enumerate(0:w-1)
        drawline(ctx, Point(x, 0.75*h), Point(x, 0.5*h), gpoints[i], 1)
    end
    gpoints = reverse(generategrays(64, w))
    for (i, x) in enumerate(0:w-1)
        drawline(ctx, Point(x, h), Point(x, 0.75*h), gpoints[i], 1)
    end
end

show(can)
sleep(5)
unfullscreen(win)
const cond = Condition()
endit(w) = notify(cond)
signal_connect(endit, win, :destroy)
wait(cond)


// version 1.1

import java.awt.Color
import java.awt.Graphics
import javax.swing.JFrame

class GreyBars : JFrame("grey bars example!") {
    private val w: Int
    private val h: Int

    init {
        w = 640
        h = 320
        setSize(w, h)
        defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        isVisible = true
    }

    override fun paint(g: Graphics) {
        var run = 0
        var colorComp: Double  // component of the color
        var columnCount = 8
        while (columnCount < 128) {
            var colorGap = 255.0 / (columnCount - 1) // by this gap we change the background color
            val columnWidth = w / columnCount
            val columnHeight = h / 4
            if (run % 2 == 0)  // switches color directions with each iteration of while loop
                colorComp = 0.0
            else {
                colorComp = 255.0
                colorGap *= -1.0
            }
            val ystart = columnHeight * run
            var xstart = 0
            for (i in 0 until columnCount) {
                val iColor = Math.round(colorComp).toInt()
                val nextColor = Color(iColor, iColor, iColor)
                g.color = nextColor
                g.fillRect(xstart, ystart, columnWidth, columnHeight)
                xstart += columnWidth
	        colorComp += colorGap
	    }
            run++
            columnCount *= 2
        }
    }
}

fun main(args: Array<String>) {
    GreyBars()
}


nomainwin

WindowWidth  =DisplayWidth
WindowHeight =DisplayHeight

open "Grey bars" for graphics_fs_nsb as #w

#w "trapclose [quit]"
#w "down"

bars             =4 '   alter for more, finer bars.

for group =0 to bars -1
    for i = 0 to 2^( 3 +group) -1
        #w "place "; WindowWidth *i /( 2^( 3 +group)); " "; WindowHeight *group /bars
        if ( group =0) or ( group =2) then
            g$ =str$( int( 255 *i /(2^( 3 +group)-1)))
        else
            g$ =str$( 255 -int( 255 *i /(2^( 3 +group)-1)))
        end if
        grey$ =g$ +" " +g$ +" " +g$
        #w "backcolor "; grey$
        '#w "color ";     grey$ 'rem out for outlined areas..
        #w "boxfilled "; WindowWidth *( i +1) /8 ; " "; WindowHeight *( group +1) /bars
    next i
next group

wait
[quit]
close #w
end


CreateDocument[ Graphics[ [email protected][
{ If[EvenQ[#3], GrayLevel[ 1. - j/#1 ], GrayLevel[ j/#1 ]],
   Rectangle[{j #2, 7*#3}, {#2 (j + 1), (#3 + 1) 7}]}, {j, 0, #1}] & @@@
   {{7, 8, 3}, {15, 4, 2}, {31, 2, 1}, {63, 1, 0} }
,ImageSize -> Full], WindowFrame -> "Frameless", WindowSize -> Full]