<commit_before>root = this

# To be initialized on document load
user_input = null
controller = null
editor = null
progress = null

class_cache = {}
raw_cache = {}

$.ajax "browser/mini-rt.tar", {
  type: 'GET'
  dataType: 'text'
  beforeSend: (jqXHR) -> jqXHR.overrideMimeType('text/plain; charset=x-user-defined')
  success: (data) ->
    file_count = 0
    done = false
    start_untar = (new Date).getTime()
    on_complete = ->
      end_untar = (new Date).getTime()
      console.log "Untarring took a total of #{end_untar-start_untar}ms."
      $('#overlay').fadeOut 'slow'
      $('#progress-container').fadeOut 'slow'
      $('#console').click()
    update_bar = _.throttle ((percent, path) ->
      bar ?= $('#progress > .bar')
      preloading_file ?= $('#preloading-file')
      # +10% hack to make the bar appear fuller before fading kicks in
      display_perc = Math.min Math.ceil(percent*100) + 10, 100
      bar.width "#{display_perc}%", 150
      preloading_file.text(
        if display_perc < 100 then "Loading #{_.last path.split '/'}"  else "Done!"))

    untar new util.BytesArray(util.bytestr_to_array data), ((percent, path, file) ->
      update_bar(percent, path)
      raw_cache[path] = file[0..]
      base_dir = 'third_party/classes/'
      [base,ext] = path.split('.')
      unless ext is 'class'
        on_complete() if percent == 100
        return
      file_count++
      cls = base.substr(base_dir.length)
      asyncExecute (->
        class_cache[cls] = new ClassFile file
        on_complete() if --file_count == 0 and done
      ), 0),
      ->
        done = true
        on_complete() if file_count == 0
  error: (jqXHR, textStatus, errorThrown) ->
    console.error errorThrown
}

demo_files = ['special/DiffPrint.class', 'special/Chatterbot.java',
  'special/Chatterbot.class', 'special/Lzw.java', 'special/Lzw.class',
  'special/RegexTestHarness.java', 'special/RegexTestHarness.class',
  'special/FileRead.java', 'special/Fib.java', 'special/foo', 'special/bar']
for demo in demo_files
  $.ajax "test/#{demo}", {
    type: 'GET'
    dataType: 'text'
    async: false
    beforeSend: (jqXHR) -> jqXHR.overrideMimeType('text/plain; charset=x-user-defined')
    success: (data) ->
      fname = _.last(demo.split '/')
      (new DoppioFile fname).write(data).save()
    error: ->
      fname = _.last(demo.split '/')
      controller.message "Could not load '#{fname}'.\n", 'error', true
  }

if RELEASE?
  $.ajax "third_party/classes/sun/tools/javac/Main.class", {
    type: 'GET'
    dataType: 'text'
    beforeSend: (jqXHR) -> jqXHR.overrideMimeType('text/plain; charset=x-user-defined')
    success: (data) -> class_cache['!javac'] = process_bytecode data
  }

try_path = (path) ->
  # hack. we should implement proper directories
  local_file = DoppioFile.load _.last(path.split '/')
  return util.bytestr_to_array local_file.data if local_file?
  rv = null
  $.ajax path, {
    type: 'GET'
    dataType: 'text'
    async: false
    beforeSend: (jqXHR) -> jqXHR.overrideMimeType('text/plain; charset=x-user-defined')
    success: (data) -> rv = util.bytestr_to_array data
  }
  rv

# Read in a binary classfile synchronously. Return an array of bytes.
read_classfile = (cls) ->
  unless class_cache[cls]?
    classpath = [ "third_party/classes/", "" ]
    for path in classpath
      fullpath = "#{path}#{cls}.class"
      if fullpath of raw_cache
        class_cache[cls] = new ClassFile raw_cache[fullpath]
        break
      data = try_path fullpath
      if data?
        raw_cache[fullpath] = data
        class_cache[cls] = new ClassFile data
        break
  class_cache[cls]

root.read_raw_class = (path) ->
  unless raw_cache[path]?
    data = try_path path
    raw_cache[path] = data if data?
  raw_cache[path]

process_bytecode = (bytecode_string) ->
  bytes_array = util.bytestr_to_array bytecode_string
  new ClassFile(bytes_array)

compile_source = (fname, quiet) ->
  source = DoppioFile.load(fname).read()
  return controller.message "Could not find file '#{fname}'.", 'error' unless source?
  $.ajax 'http://people.cs.umass.edu/~ccarey/javac/', {
    type: 'POST'
    data: { pw: 'coffee', source: source }
    dataType: 'text'
    beforeSend: (jqXHR) -> jqXHR.overrideMimeType('text/plain; charset=x-user-defined')
    success:  (data) ->
      class_name = fname.split('.')[0]
      (new DoppioFile "#{class_name}.class").write(data).save()
      unless quiet
        controller.reprompt()
    error: (jqXHR, textStatus, errorThrown) -> 
      controller.message "AJAX error: #{errorThrown}", 'error'
  }

$(document).ready ->
  editor = $('#editor')
  # set up the local file loaders
  $('#file').change (ev) ->
    f = ev.target.files[0]
    unless FileReader?
      controller.message """
        Your browser doesn't support file loading.
        Try using the editor to create files instead.
        """, "error"
      return $('#console').click() # click to restore focus
    reader = new FileReader
    reader.onerror = (e) ->
      switch e.target.error.code
        when e.target.error.NOT_FOUND_ERR then alert "404'd"
        when e.target.error.NOT_READABLE_ERR then alert "unreadable"
        when e.target.error.SECURITY_ERR then alert "only works with --allow-file-access-from-files"
    ext = f.name.split('.')[1]
    if ext == 'class'
      reader.onload = (e) ->
        (new DoppioFile f.name).write(e.target.result).save()
        controller.message "File '#{f.name}' saved.", 'success'
        editor.getSession?().setValue("/*\n * Binary file: #{f.name}\n */")
        $('#console').click() # click to restore focus
      reader.readAsBinaryString(f)
    else # assume a text file
      reader.onload = (e) ->
        (new DoppioFile f.name).write(e.target.result).save()
        controller.message "File '#{f.name}' saved.", 'success'
        editor.getSession?().setValue(e.target.result)
        $('#console').click() # click to restore focus
      reader.readAsText(f)

  jqconsole = $('#console')
  controller = jqconsole.console
    promptLabel: 'doppio > '
    commandHandle: (line) ->
      [cmd,args...] = line.split /\s+/
      if cmd == '' then return true
      handler = commands[cmd]
      try
        if handler? then handler(args)
        else "Unknown command '#{cmd}'. Enter 'help' for a list of commands."
      catch e
        controller.message e.toString(), 'error'
    tabComplete: tabComplete
    autofocus: false
    animateScroll: true
    promptHistory: true
    welcomeMessage: "Enter 'help' for a list of commands. Ctrl-D is EOF."

  user_input = (n_bytes, resume) ->
    oldPrompt = controller.promptLabel
    controller.promptLabel = '> '
    controller.reprompt()
    oldHandle = controller.commandHandle
    controller.commandHandle = (line) ->
      controller.commandHandle = oldHandle
      controller.promptLabel = oldPrompt
      if line == '\0' # EOF
        resume 0
      else
        line += "\n" # so BufferedReader knows it has a full line
        resume (line.charCodeAt(i) for i in [0...Math.min(n_bytes,line.length)])

  close_editor = ->
    $('#ide').fadeOut 'fast', ->
      $('#console').fadeIn('fast').click() # click to restore focus

  $('#save_btn').click (e) ->
    fname = $('#filename').val()
    contents = editor.getSession().getValue()
    contents += '\n' unless contents[contents.length-1] == '\n'
    (new DoppioFile fname).write(contents).save()
    controller.message("File saved as '#{fname}'.", 'success')
    close_editor()<commit_msg>only load demos after document is ready<commit_after>root = this

# To be initialized on document load
user_input = null
controller = null
editor = null
progress = null

class_cache = {}
raw_cache = {}

$.ajax "browser/mini-rt.tar", {
  type: 'GET'
  dataType: 'text'
  beforeSend: (jqXHR) -> jqXHR.overrideMimeType('text/plain; charset=x-user-defined')
  success: (data) ->
    file_count = 0
    done = false
    start_untar = (new Date).getTime()
    on_complete = ->
      end_untar = (new Date).getTime()
      console.log "Untarring took a total of #{end_untar-start_untar}ms."
      $('#overlay').fadeOut 'slow'
      $('#progress-container').fadeOut 'slow'
      $('#console').click()
    update_bar = _.throttle ((percent, path) ->
      bar ?= $('#progress > .bar')
      preloading_file ?= $('#preloading-file')
      # +10% hack to make the bar appear fuller before fading kicks in
      display_perc = Math.min Math.ceil(percent*100) + 10, 100
      bar.width "#{display_perc}%", 150
      preloading_file.text(
        if display_perc < 100 then "Loading #{_.last path.split '/'}"  else "Done!"))

    untar new util.BytesArray(util.bytestr_to_array data), ((percent, path, file) ->
      update_bar(percent, path)
      raw_cache[path] = file[0..]
      base_dir = 'third_party/classes/'
      [base,ext] = path.split('.')
      unless ext is 'class'
        on_complete() if percent == 100
        return
      file_count++
      cls = base.substr(base_dir.length)
      asyncExecute (->
        class_cache[cls] = new ClassFile file
        on_complete() if --file_count == 0 and done
      ), 0),
      ->
        done = true
        on_complete() if file_count == 0
  error: (jqXHR, textStatus, errorThrown) ->
    console.error errorThrown
}

if RELEASE?
  $.ajax "third_party/classes/sun/tools/javac/Main.class", {
    type: 'GET'
    dataType: 'text'
    beforeSend: (jqXHR) -> jqXHR.overrideMimeType('text/plain; charset=x-user-defined')
    success: (data) -> class_cache['!javac'] = process_bytecode data
  }

try_path = (path) ->
  # hack. we should implement proper directories
  local_file = DoppioFile.load _.last(path.split '/')
  return util.bytestr_to_array local_file.data if local_file?
  rv = null
  $.ajax path, {
    type: 'GET'
    dataType: 'text'
    async: false
    beforeSend: (jqXHR) -> jqXHR.overrideMimeType('text/plain; charset=x-user-defined')
    success: (data) -> rv = util.bytestr_to_array data
  }
  rv

# Read in a binary classfile synchronously. Return an array of bytes.
read_classfile = (cls) ->
  unless class_cache[cls]?
    classpath = [ "third_party/classes/", "" ]
    for path in classpath
      fullpath = "#{path}#{cls}.class"
      if fullpath of raw_cache
        class_cache[cls] = new ClassFile raw_cache[fullpath]
        break
      data = try_path fullpath
      if data?
        raw_cache[fullpath] = data
        class_cache[cls] = new ClassFile data
        break
  class_cache[cls]

root.read_raw_class = (path) ->
  unless raw_cache[path]?
    data = try_path path
    raw_cache[path] = data if data?
  raw_cache[path]

process_bytecode = (bytecode_string) ->
  bytes_array = util.bytestr_to_array bytecode_string
  new ClassFile(bytes_array)

compile_source = (fname, quiet) ->
  source = DoppioFile.load(fname).read()
  return controller.message "Could not find file '#{fname}'.", 'error' unless source?
  $.ajax 'http://people.cs.umass.edu/~ccarey/javac/', {
    type: 'POST'
    data: { pw: 'coffee', source: source }
    dataType: 'text'
    beforeSend: (jqXHR) -> jqXHR.overrideMimeType('text/plain; charset=x-user-defined')
    success:  (data) ->
      class_name = fname.split('.')[0]
      (new DoppioFile "#{class_name}.class").write(data).save()
      unless quiet
        controller.reprompt()
    error: (jqXHR, textStatus, errorThrown) -> 
      controller.message "AJAX error: #{errorThrown}", 'error'
  }

$(document).ready ->
  editor = $('#editor')
  # set up the local file loaders
  $('#file').change (ev) ->
    f = ev.target.files[0]
    unless FileReader?
      controller.message """
        Your browser doesn't support file loading.
        Try using the editor to create files instead.
        """, "error"
      return $('#console').click() # click to restore focus
    reader = new FileReader
    reader.onerror = (e) ->
      switch e.target.error.code
        when e.target.error.NOT_FOUND_ERR then alert "404'd"
        when e.target.error.NOT_READABLE_ERR then alert "unreadable"
        when e.target.error.SECURITY_ERR then alert "only works with --allow-file-access-from-files"
    ext = f.name.split('.')[1]
    if ext == 'class'
      reader.onload = (e) ->
        (new DoppioFile f.name).write(e.target.result).save()
        controller.message "File '#{f.name}' saved.", 'success'
        editor.getSession?().setValue("/*\n * Binary file: #{f.name}\n */")
        $('#console').click() # click to restore focus
      reader.readAsBinaryString(f)
    else # assume a text file
      reader.onload = (e) ->
        (new DoppioFile f.name).write(e.target.result).save()
        controller.message "File '#{f.name}' saved.", 'success'
        editor.getSession?().setValue(e.target.result)
        $('#console').click() # click to restore focus
      reader.readAsText(f)

  jqconsole = $('#console')
  controller = jqconsole.console
    promptLabel: 'doppio > '
    commandHandle: (line) ->
      [cmd,args...] = line.split /\s+/
      if cmd == '' then return true
      handler = commands[cmd]
      try
        if handler? then handler(args)
        else "Unknown command '#{cmd}'. Enter 'help' for a list of commands."
      catch e
        controller.message e.toString(), 'error'
    tabComplete: tabComplete
    autofocus: false
    animateScroll: true
    promptHistory: true
    welcomeMessage: "Enter 'help' for a list of commands. Ctrl-D is EOF."

  demo_files = ['special/DiffPrint.class', 'special/Chatterbot.java',
  'special/Chatterbot.class', 'special/Lzw.java', 'special/Lzw.class',
  'special/RegexTestHarness.java', 'special/RegexTestHarness.class',
  'special/FileRead.java', 'special/Fib.java', 'special/foo', 'special/bar']
  for demo in demo_files
    $.ajax "test/#{demo}", {
      type: 'GET'
      dataType: 'text'
      async: false
      beforeSend: (jqXHR) -> jqXHR.overrideMimeType('text/plain; charset=x-user-defined')
      success: (data) ->
        fname = _.last(demo.split '/')
        (new DoppioFile fname).write(data).save()
      error: ->
        fname = _.last(demo.split '/')
        controller.message "Could not load '#{fname}'.\n", 'error', true
    }

  user_input = (n_bytes, resume) ->
    oldPrompt = controller.promptLabel
    controller.promptLabel = '> '
    controller.reprompt()
    oldHandle = controller.commandHandle
    controller.commandHandle = (line) ->
      controller.commandHandle = oldHandle
      controller.promptLabel = oldPrompt
      if line == '\0' # EOF
        resume 0
      else
        line += "\n" # so BufferedReader knows it has a full line
        resume (line.charCodeAt(i) for i in [0...Math.min(n_bytes,line.length)])

  close_editor = ->
    $('#ide').fadeOut 'fast', ->
      $('#console').fadeIn('fast').click() # click to restore focus

  $('#save_btn').click (e) ->
    fname = $('#filename').val()
    contents = editor.getSession().getValue()
    contents += '\n' unless contents[contents.length-1] == '\n'
    (new DoppioFile fname).write(contents).save()
    controller.message("File saved as '#{fname}'.", 'success')
    close_editor()
{'fraction_non_alphanumeric': 0.1478723404255319, 'fraction_numerical': 0.0045212765957446804, 'mean_word_length': 2.9138693728857663, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 77, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6682615', 'n_tokens_mistral': 4974, 'n_tokens_neox': 4882, 'n_words': 1179}