############################################################################
#
#	File:     sequent.icn
#
#	Subject:  Program to manipulate sequences
#
#	Author:   Ralph E. Griswold
#
#	Date:     October 4, 1999
#
############################################################################
#
#  This program produces sequences from Icon expressions.
#
############################################################################
#
#  Requires:  Version 9 graphics, /tmp
#
############################################################################
#
#  Links: cells, interact, lists, periodic, seqfncs, strings, tables, vsetup
#
############################################################################

link cells
link interact
link lists
link periodic
link seqfncs
link strings
link tables
link vsetup

global current_exp	# current expression
global display		# text-list vidget for result display
global limit		# limit on number of terms
global results		# list of current results
global separator	# separator for terms

$define Limit		300
$define ExprWidth	120
$define Fudge		 20		# width of other stuff

procedure main(args)
   local vidgets, root, paused

   (WOpen ! ui_atts()) | stop("can't open window")
   vidgets := ui()				# set up vidgets

   root := vidgets["root"]
   display := vidgets["display"]

   current_exp := "seq()"
   results := []

   limit := Limit
   separator := ","

   GetEvents(root, , shortcuts)

end

procedure display_results()
   local result_list, term, disp_list, line
   static line_width

   initial line_width := (display.aw - Fudge) / WAttrib("fwidth")

   result_list := []

   every put(result_list, image(!results) || separator)

   line := ""
   disp_list := []

   while term := get(result_list) do {
      if *line + *term > line_width then {
         if *line = 0 then {
            put(disp_list, term[1+:line_width])
            line := term[line_width:0]
            }
         else {
            put(disp_list, line)
            line := term
            }
         }
      else line ||:= term
      }

   if *line > 0 then put(disp_list, line)

   VSetItems(display, disp_list)

   return

end

procedure edit()
   local input

   repeat {
      case TextDialog("Expression:", , current_exp, ExprWidth,
         ["Run", "Okay", "Reset", "Copy", "Paste", "Read"]) of {
            "Run"    :  {
                current_exp := dialog_value[1]
                run()  
                }
            "Okay"   :  {
               current_exp := dialog_value[1]
               }
            "Reset"  :  next
            "Copy"   :  {
               copy_expression(current_exp)
               next
               }
            "Paste"  :  {
               current_exp := paste_expression()
               next
               }
            "Read"   :  {
                repeat {
                   if OpenDialog() == "Cancel" then break next
                   input := open(dialog_value) | {
                      Notice("Cannot open file.")
                      next
                      }
                   current_exp := read(input) | {
                      Notice("Empty file.")
                      close(input)
                      next
                      }
                   close(input)
                   break next
                   }
                }
                     
            }
      return
      }

end

procedure copy_expression(expr)
   local output

   output := open("/tmp/exprclip", "w") | {
      Notice("Cannot copy.")
      fail
      }

   write(output, expr)

   close(output)

   return

end

procedure paste_expression()
   local input

   input := open("/tmp/exprclip") | {
      Notice("Cannot open clipboard.")
      fail
      }

   return read(input) | {
      Notice("Clipboard empty.")
      close(input)
      fail
      }

   close(input)

   return

end

procedure file_cb(vidgets, value)

   case value[1] of {
      "save  @S"  :  write_seq()
      "quit  @Q"  :  exit()
      }

   return

end

procedure grid()
   local panel, i, j
   static xvalues, yvalues, cellsize, xoffset, yoffset

   initial {
      xvalues := 48
      yvalues := 8
      cellsize := 5
      xoffset := 0
      yoffset := 0
      }

   if *results = 0 then {
      Notice("No results.")
      fail
      }

   repeat {
      if TextDialog(
         "Grid parameters:",
         ["x values", "y values", "x offset", "y offset", "cellsize"],
         [xvalues, yvalues, xoffset, yoffset, cellsize],
         [4, 4, 3, 3, 3]
         ) == "Cancel" then fail
      (
         xvalues := (0 < integer(dialog_value[1])) &
         yvalues := (0 < integer(dialog_value[2])) &
         xoffset := integer(dialog_value[3]) &
         yoffset := integer(dialog_value[4]) &
         cellsize := (0 < integer(dialog_value[5]))
         ) | {
           Notice("Invalid parameter.")
           next
           }
         break
      }

   panel := makepanel(xvalues, yvalues, cellsize)

   every i := 1 to xvalues do {
      j := results[xoffset + i] | break		# out of results
      colorcell(panel, i, yvalues - integer(j) +
         yoffset, "black") | {
            Notice("Non-integer value at term " || i || ".")
            WClose(panel.window)
            fail
            }
      }

   WAttrib(panel.window, "canvas=normal")

   if TextDialog("Save image?", , , , ["No", "Yes"]) == "Yes" then
      snapshot(panel.window)

   WClose(panel.window)

   return

end

procedure options_cb(vidgets, value)

   case value[1] of {
      "limit @L"   :  set_limit()
      "separator"  :  set_separator()
      }

   return

end

procedure plot()
   local win, i, j, width, height
   static xvalues, yvalues, padding, separation, radius

   initial {
      xvalues := 20
      yvalues := 20
      padding := 8
      separation := 8
      radius := 2
      }

   if *results = 0 then {
      Notice("No results.")
      fail
      }

   repeat {
      if TextDialog(
         "Plot parameters:",
         ["x values", "y values", "padding", "separation", "circle radius"],
         [xvalues, yvalues, padding, separation, radius],
         [4, 4, 3, 3, 3]
         ) == "Cancel" then fail
      (
         xvalues := (0 < integer(dialog_value[1])) &
         yvalues := (0 < integer(dialog_value[2])) &
         padding := (0 < integer(dialog_value[3])) &
         separation := (0 < integer(dialog_value[4])) &
         radius := (0 < integer(dialog_value[5]))
         ) | {
           Notice("Invalid parameter.")
           next
           }
         break
      }

   width := padding + (xvalues + 1) * separation
   height := padding + (yvalues + 1) * separation

   win := WOpen("width=" || width, "height=" || height) | {
      Notice("Cannot open plot window.")
      fail
      }

   #  Draw axes

   DrawLine(win, padding, 0, padding, height - padding)
   DrawLine(win, padding, height - padding, width, height - padding)

   i := 0

   every j := !results do {
      i +:= 1
      if not(j := numeric(j)) then {
         Notice("Non-integer value:" || image(j) || || "at term " || i || ".")
         fail
         }
      if (i > xvalues) | (j > yvalues) then break
      FillCircle(win, padding + i * separation,
         height - padding - j * separation, radius) 
      }

   if TextDialog("Save image?", , , , ["No", "Yes"]) == "Yes" then snapshot(win)

   WClose(win)

   return

end

procedure plot_cb(vidgets, value)

   case value[1] of {
      "points @P"  :  plot()
      "grid   @G"  :  grid()
      }

   return

end

procedure read_seq()
   local input, line, results, result
   static file, line_number

   initial {
      file := ""
      line_number := "1"
      }

   repeat {
      case TextDialog("Read:", , file, 60, ["Expression Line", "Sequence File", "Cancel"]) of {
         "Cancel"           :  fail
         "Expression Line"  :  {
            input := open(dialog_value[1]) | {
               Notice("Cannot open file for reading.")
               next
               }
            file := dialog_value[1]
            repeat {
               if TextDialog("Line number:", , line_number, 4) == "Cancel" then break next
               line_number := (0 < integer(dialog_value[1])) | {
                  Notice("Invalid specification.")
                  next
                  }
               break
               }
            every 1 to line_number do {
               line := read(input) | {
                  Notice("Short file.")
                  close(input)
                  next
                  }
               }
            current_exp := line
            results := []
            break
            }
         "Sequence File"    :  {
            input := open(dialog_value[1]) | {
               Notice("Cannot open file for reading.")
               next
               }
            file := dialog_value[1]
            current_exp := read(input) | {
               Notice("Empty file.")
               close(input)
               fail
               }
            results := []
            line := read(input) | break			# accept empty sequence
            line ? {
               while result := tab(upto(',')) do {
                  result := integer(result)		# maybe ...
                  put(results, result)
                  move(1)
                  }
               }
            display_results()
            break
            }
         }
      }

   close(input)

   return

end

procedure run()
   local input, output, k, signal, result
   static call

   initial {
      call := "icont -s -u expr_.icn 2>/tmp/sequent.err"
      }

   output := open("expr_.icn", "w") |
      return FailNotice("Cannot open file for expression.")

   write(output, "link seqfncs")
   write(output, "link periodic")
   write(output)
   write(output, "procedure main()")
   write(output)
   write(output, "   every write(", current_exp, ") \\", limit)
   write(output)
   write(output, "end")

   close(output)

   WAttrib("pointer=watch")

   if system(call) ~= 0 then {
      remove("expr_.icn")
      WAttrib("pointer=arrow")
      show_error()
      fail 
      }

   input := open("expr_ 2>/tmp/sequent.err", "p")

   results := []

   while result := read(input) do {
      result := numeric(result)		# make a stab
      put(results, result)
      }

   signal :=  close(input)

   remove("expr_.icn")
   remove("expr_")

   WAttrib("pointer=arrow")

   if signal ~= 0 then {
      show_error()
      fail
      }

   display_results()

   return

end

procedure sequence_cb(vidgets, value)

   case value[1] of {
      "run  @R"  :  run()
      "edit @E"  :  edit()
      }

   return

end

procedure set_limit()

   repeat {
      if TextDialog("Limit on number of terms:", , limit, 4) == "Cancel"
         then fail
      limit := (0 < integer(dialog_value[1])) | {
         Notice("Invalid value.")
         next
         }
      return
      }

end

procedure set_separator()

   if TextDialog("Set separator for terms", , separator, 5) == "Cancel" then
      fail

   separator := dialog_value[1]

   return

end

procedure show_repeat()
   local info, line, lines, output

   WAttrib("pointer=watch")

   info := repeater(results)
   line := ""
   every line ||:= image(!info[1]) || separator	# prefix
   if *info[2] > 0 then {	 		# repeat
      line ||:= "["
      every line ||:= image(!info[2])  || separator
      line[-1] := "] "
      }
   line ||:=  "..."
   lines := split(line)

   put(lines, "", "pre-periodic length: " || *info[1])
   put(lines, "repeat length: " || *info[2])

   WAttrib("pointer=arrow")

   if TextDialog(lines, , , , ["Okay", "Write"]) == "Write" then {
      repeat {
         if OpenDialog("File:") == "Cancel" then fail
         output := open(dialog_value, "w") | {
            Notice("Cannot write file.")
            next
            }
         write(output, line)
         close(output)
         break
         }
      }

   return

end

procedure shortcuts(e)

   if &meta then case e of {
      "1"  :  show_repeat()
      "2"  :  show_error()
      "e"  :  edit()
      "g"  :  grid()
      "l"  :  set_limit()
      "p"  :  plot()
      "q"  :  exit()
      "r"  :  run()
      "s"  :  write_seq()
      }

   return

end

procedure show_error()
   local input, log

   input := open("/tmp/sequent.err") | {
      Notice("Cannot open error log.")
      fail
      }

   log := ["Error log:", ""]

   while put(log, read(input))

   close(input)

   Notice ! log

   return

end

procedure special_cb(vidget, value)

    case value[1] of {
       "show repeat"  :  show_repeat()
       }

end

procedure split(line, limit)	#: split line into pieces
   local i, j, lines

   /limit := 90

   lines := []

   if *line = 0 then {			# don't fail to write empty line
      put(lines, line)
      return lines
      }

   while *line > limit do {
      line ?:= {
         i := j := 0
         every i := find(",") do {	# find a point to split
            if i >= limit then break
            else j := i
            }
         if j = 0 then {		# can't split
            put(lines, line)
            return
            }
         put(lines, tab(j + 1))
         tab(0)				# update line
         }
      }
   if *line > 0 then put(lines, line)	# the rest

   return lines

end

procedure write_seq()
   local option, output
   static file

   initial file := "untitled.seq"

   repeat {
      case TextDialog("Write:", , file, 60, ["Okay", "Cancel"]) of {
            "Cancel"  :  fail
            "Okay"    :  option := "w"
            }
      output := open(dialog_value[1], option) | {
         Notice("Cannot open file for writing.")
         next
         }
      file := dialog_value[1]
      break
      }

   write(output, current_exp)
   every writes(output, !results, separator)
   write(output)

   close(output)

   return

end

#===<<vib:begin>>===	modify using vib; do not remove this marker line
procedure ui_atts()
   return ["size=646,407", "bg=pale gray", "label=The Sequence Machine"]
end

procedure ui(win, cbk)
return vsetup(win, cbk,
   [":Sizer:::0,0,646,407:The Sequence Machine",],
   ["display:List:r::10,31,625,367:",],
   ["file:Menu:pull::0,0,36,21:File",file_cb,
      ["save  @S","quit  @Q"]],
   ["line1:Line:::0,22,645,22:",],
   ["options:Menu:pull::135,0,57,21:Options",options_cb,
      ["limit @L","separator"]],
   ["plot:Menu:pull::100,0,36,21:Plot",plot_cb,
      ["points @P","grid   @G"]],
   ["sequence:Menu:pull::36,0,64,21:Sequence",sequence_cb,
      ["edit @E","run  @R"]],
   ["special:Menu:pull::191,0,57,21:Special",special_cb,
      ["show repeat"]],
   )
end
#===<<vib:end>>===	end of section maintained by vib
