summary refs log blame commit diff stats
path: root/doc/pydoc/ranger.gui.widgets.taskview.html
blob: 548d55d942642966976046f7509cfd7260985f30 (plain) (tree)






















































































































































                                                                                                                                                                                                                                                                                                                          
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><title>Python: module ranger.gui.widgets.taskview</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head><body bgcolor="#f0f0f8">

<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="heading">
<tr bgcolor="#7799ee">
<td valign=bottom>&nbsp;<br>
<font color="#ffffff" face="helvetica, arial">&nbsp;<br><big><big><strong><a href="ranger.html"><font color="#ffffff">ranger</font></a>.<a href="ranger.gui.html"><font color="#ffffff">gui</font></a>.<a href="ranger.gui.widgets.html"><font color="#ffffff">widgets</font></a>.taskview</strong></big></big></font></td
><td align=right valign=bottom
><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:/home/hut/work/ranger/ranger/gui/widgets/taskview.py">/home/hut/work/ranger/ranger/gui/widgets/taskview.py</a></font></td></tr></table>
    <p><tt>The&nbsp;<a href="#TaskView">TaskView</a>&nbsp;allows&nbsp;you&nbsp;to&nbsp;modify&nbsp;what&nbsp;the&nbsp;loader&nbsp;is&nbsp;doing.</tt></p>
<p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#aa55cc">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Modules</strong></big></font></td></tr>
    
<tr><td bgcolor="#aa55cc"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%"><table width="100%" summary="list"><tr><td width="25%" valign=top><a href="curses.html">curses</a><br>
</td><td width="25%" valign=top></td><td width="25%" valign=top></td><td width="25%" valign=top></td></tr></table></td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ee77aa">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
    
<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%"><dl>
<dt><font face="helvetica, arial"><a href="ranger.ext.accumulator.html#Accumulator">ranger.ext.accumulator.Accumulator</a>(<a href="builtins.html#object">builtins.object</a>)
</font></dt><dd>
<dl>
<dt><font face="helvetica, arial"><a href="ranger.gui.widgets.taskview.html#TaskView">TaskView</a>(<a href="ranger.gui.widgets.html#Widget">ranger.gui.widgets.Widget</a>, <a href="ranger.ext.accumulator.html#Accumulator">ranger.ext.accumulator.Accumulator</a>)
</font></dt></dl>
</dd>
<dt><font face="helvetica, arial"><a href="ranger.gui.widgets.html#Widget">ranger.gui.widgets.Widget</a>(<a href="ranger.gui.displayable.html#Displayable">ranger.gui.displayable.Displayable</a>)
</font></dt><dd>
<dl>
<dt><font face="helvetica, arial"><a href="ranger.gui.widgets.taskview.html#TaskView">TaskView</a>(<a href="ranger.gui.widgets.html#Widget">ranger.gui.widgets.Widget</a>, <a href="ranger.ext.accumulator.html#Accumulator">ranger.ext.accumulator.Accumulator</a>)
</font></dt></dl>
</dd>
</dl>
 <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#000000" face="helvetica, arial"><a name="TaskView">class <strong>TaskView</strong></a>(<a href="ranger.gui.widgets.html#Widget">ranger.gui.widgets.Widget</a>, <a href="ranger.ext.accumulator.html#Accumulator">ranger.ext.accumulator.Accumulator</a>)</font></td></tr>
    
<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%"><dl><dt>Method resolution order:</dt>
<dd><a href="ranger.gui.widgets.taskview.html#TaskView">TaskView</a></dd>
<dd><a href="ranger.gui.widgets.html#Widget">ranger.gui.widgets.Widget</a></dd>
<dd><a href="ranger.gui.displayable.html#Displayable">ranger.gui.displayable.Displayable</a></dd>
<dd><a href="ranger.shared.html#EnvironmentAware">ranger.shared.EnvironmentAware</a></dd>
<dd><a href="ranger.shared.html#FileManagerAware">ranger.shared.FileManagerAware</a></dd>
<dd><a href="ranger.shared.html#Awareness">ranger.shared.Awareness</a></dd>
<dd><a href="ranger.gui.curses_shortcuts.html#CursesShortcuts">ranger.gui.curses_shortcuts.CursesShortcuts</a></dd>
<dd><a href="ranger.shared.settings.html#SettingsAware">ranger.shared.settings.SettingsAware</a></dd>
<dd><a href="ranger.ext.accumulator.html#Accumulator">ranger.ext.accumulator.Accumulator</a></dd>
<dd><a href="builtins.html#object">builtins.object</a></dd>
</dl>
<hr>
Methods defined here:<br>
<dl><dt><a name="TaskView-__init__"><strong>__init__</strong></a>(self, win)</dt></dl>

<dl><dt><a name="TaskView-draw"><strong>draw</strong></a>(self)</dt></dl>

<dl><dt><a name="TaskView-get_list"><strong>get_list</strong></a>(self)</dt></dl>

<dl><dt><a name="TaskView-press"><strong>press</strong></a>(self, key)</dt></dl>

<dl><dt><a name="TaskView-task_move"><strong>task_move</strong></a>(self, absolute, i<font color="#909090">=None</font>)</dt></dl>

<dl><dt><a name="TaskView-task_remove"><strong>task_remove</strong></a>(self, i<font color="#909090">=None</font>)</dt></dl>

<hr>
Data and other attributes defined here:<br>
<dl><dt><strong>old_lst</strong> = None</dl>

<hr>
Methods inherited from <a href="ranger.gui.displayable.html#Displayable">ranger.gui.displayable.Displayable</a>:<br>
<dl><dt><a name="TaskView-__contains__"><strong>__contains__</strong></a>(self, item)</dt><dd><tt>Is&nbsp;item&nbsp;inside&nbsp;the&nbsp;boundaries?<br>
item&nbsp;can&nbsp;be&nbsp;an&nbsp;iterable&nbsp;like&nbsp;[y,&nbsp;x]&nbsp;or&nbsp;an&nbsp;object&nbsp;with&nbsp;x&nbsp;and&nbsp;y&nbsp;methods.</tt></dd></dl>

<dl><dt><a name="TaskView-__nonzero__"><strong>__nonzero__</strong></a>(self)</dt><dd><tt>Always&nbsp;True</tt></dd></dl>

<dl><dt><a name="TaskView-__str__"><strong>__str__</strong></a>(self)</dt></dl>

<dl><dt><a name="TaskView-click"><strong>click</strong></a>(self, event)</dt><dd><tt>Called&nbsp;when&nbsp;a&nbsp;mouse&nbsp;key&nbsp;is&nbsp;pressed&nbsp;and&nbsp;self.<strong>focused</strong>&nbsp;is&nbsp;True.<br>
Override&nbsp;this!</tt></dd></dl>

<dl><dt><a name="TaskView-contains_point"><strong>contains_point</strong></a>(self, y, x)</dt><dd><tt>Test&nbsp;whether&nbsp;the&nbsp;point&nbsp;(with&nbsp;absolute&nbsp;coordinates)&nbsp;lies<br>
within&nbsp;the&nbsp;boundaries&nbsp;of&nbsp;this&nbsp;object.</tt></dd></dl>

<dl><dt><a name="TaskView-destroy"><strong>destroy</strong></a>(self)</dt><dd><tt>Called&nbsp;when&nbsp;the&nbsp;object&nbsp;is&nbsp;destroyed.<br>
Override&nbsp;this!</tt></dd></dl>

<dl><dt><a name="TaskView-finalize"><strong>finalize</strong></a>(self)</dt><dd><tt>Called&nbsp;after&nbsp;every&nbsp;displayable&nbsp;is&nbsp;done&nbsp;drawing.<br>
Override&nbsp;this!</tt></dd></dl>

<dl><dt><a name="TaskView-poke"><strong>poke</strong></a>(self)</dt><dd><tt>Called&nbsp;before&nbsp;drawing,&nbsp;even&nbsp;if&nbsp;invisible</tt></dd></dl>

<dl><dt><a name="TaskView-resize"><strong>resize</strong></a>(self, y, x, hei<font color="#909090">=None</font>, wid<font color="#909090">=None</font>)</dt><dd><tt>Resize&nbsp;the&nbsp;widget</tt></dd></dl>

<hr>
Data and other attributes inherited from <a href="ranger.shared.html#EnvironmentAware">ranger.shared.EnvironmentAware</a>:<br>
<dl><dt><strong>env</strong> = None</dl>

<hr>
Data and other attributes inherited from <a href="ranger.shared.html#FileManagerAware">ranger.shared.FileManagerAware</a>:<br>
<dl><dt><strong>fm</strong> = None</dl>

<hr>
Data descriptors inherited from <a href="ranger.shared.html#Awareness">ranger.shared.Awareness</a>:<br>
<dl><dt><strong>__dict__</strong></dt>
<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dd>
</dl>
<dl><dt><strong>__weakref__</strong></dt>
<dd><tt>list&nbsp;of&nbsp;weak&nbsp;references&nbsp;to&nbsp;the&nbsp;object&nbsp;(if&nbsp;defined)</tt></dd>
</dl>
<hr>
Methods inherited from <a href="ranger.gui.curses_shortcuts.html#CursesShortcuts">ranger.gui.curses_shortcuts.CursesShortcuts</a>:<br>
<dl><dt><a name="TaskView-addnstr"><strong>addnstr</strong></a>(self, *args)</dt></dl>

<dl><dt><a name="TaskView-addstr"><strong>addstr</strong></a>(self, *args)</dt></dl>

<dl><dt><a name="TaskView-color"><strong>color</strong></a>(self, keylist<font color="#909090">=None</font>, *keys)</dt><dd><tt>Change&nbsp;the&nbsp;colors&nbsp;from&nbsp;now&nbsp;on.</tt></dd></dl>

<dl><dt><a name="TaskView-color_at"><strong>color_at</strong></a>(self, y, x, wid, keylist<font color="#909090">=None</font>, *keys)</dt><dd><tt>Change&nbsp;the&nbsp;colors&nbsp;at&nbsp;the&nbsp;specified&nbsp;position</tt></dd></dl>

<dl><dt><a name="TaskView-color_reset"><strong>color_reset</strong></a>(self)</dt><dd><tt>Change&nbsp;the&nbsp;colors&nbsp;to&nbsp;the&nbsp;default&nbsp;colors</tt></dd></dl>

<hr>
Data and other attributes inherited from <a href="ranger.shared.settings.html#SettingsAware">ranger.shared.settings.SettingsAware</a>:<br>
<dl><dt><strong>settings</strong> = &lt;ranger.ext.openstruct.OpenStruct object at 0x7f20a718ad90&gt;</dl>

<hr>
Methods inherited from <a href="ranger.ext.accumulator.html#Accumulator">ranger.ext.accumulator.Accumulator</a>:<br>
<dl><dt><a name="TaskView-correct_pointer"><strong>correct_pointer</strong></a>(self)</dt></dl>

<dl><dt><a name="TaskView-get_height"><strong>get_height</strong></a>(self)</dt><dd><tt>OVERRIDE&nbsp;THIS</tt></dd></dl>

<dl><dt><a name="TaskView-move"><strong>move</strong></a>(self, relative<font color="#909090">=0</font>, absolute<font color="#909090">=None</font>, pages<font color="#909090">=False</font>)</dt></dl>

<dl><dt><a name="TaskView-move_to_obj"><strong>move_to_obj</strong></a>(self, arg, attr<font color="#909090">=None</font>)</dt></dl>

<dl><dt><a name="TaskView-pointer_is_synced"><strong>pointer_is_synced</strong></a>(self)</dt></dl>

<dl><dt><a name="TaskView-sync_index"><strong>sync_index</strong></a>(self, **kw)</dt></dl>

</td></tr></table></td></tr></table>
</body></html>
'n278' href='#n278'>278 279 280

                   
 

                       
                 
                   
                 

                     


                          
                    
                 
                  
                
                     
                

                      

    
                      





                                     
 


                      
                        
                                                 
             
                       
                             
                             
                               

                                      
                                   
                                                           
                  
                                                 
                                                                  
                    
                             
 

                      

                                                                   



                     

                       

   
                                                                   
                             

                  
                          
              
                                     
                  

   


                                                     

                                                             
             

                      




                                            
                                
                          
                          
                       
 
                                                              





                                                              
 

                                                                            

                                                  

                                                                        
                                                                   
 







                                                       



                                                                 

                                       
                                     
















                                                                       









                                                                            



                                       
                                                                      




                                          

                                          


                                                          
                                                                   

                              
                                  
                          
                   
                        
 



                                       

                                   
















                                                                    

















                                                             
                                                                    
                       
                                        
                                                                                

                  



                                           

                              
                                  
                          
                   
                        



                                         
                        














                                                             



                                                        

                                                                   
                                                                       
                                   
                                                                    
                          

                                  
                                      


                            
                             
                          
                   
                        
 





                                                                        
   


                                         
import std/strutils
import std/tables

import chagashi/charset
import chagashi/decoder
import img/bitmap
import io/dynstream
import io/promise
import loader/headers
import loader/request
import monoucha/javascript
import monoucha/jserror
import monoucha/quickjs
import monoucha/tojs
import types/blob
import types/color
import types/opt
import types/referrer
import types/url
import utils/mimeguess
import utils/twtstr

type
  ResponseType* = enum
    rtDefault = "default"
    rtBasic = "basic"
    rtCors = "cors"
    rtError = "error"
    rtOpaque = "opaque"
    rtOpaquedirect = "opaqueredirect"

  ResponseFlag* = enum
    rfAborted

  Response* = ref object
    responseType* {.jsget: "type".}: ResponseType
    res*: int
    body*: SocketStream
    bodyUsed* {.jsget.}: bool
    status* {.jsget.}: uint16
    headers* {.jsget.}: Headers
    url*: URL #TODO should be urllist?
    unregisterFun*: proc()
    resumeFun*: proc(outputId: int)
    internalMessage*: string # should NOT be exposed to JS!
    outputId*: int
    onRead*: proc(response: Response) {.nimcall.}
    onFinish*: proc(response: Response; success: bool) {.nimcall.}
    opaque*: RootRef
    flags*: set[ResponseFlag]

jsDestructor(Response)

proc newResponse*(res: int; request: Request; stream: SocketStream;
    outputId: int; status: uint16): Response =
  return Response(
    res: res,
    url: request.url,
    body: stream,
    outputId: outputId,
    status: status
  )

func makeNetworkError*(): Response {.jsstfunc: "Response.error".} =
  #TODO use "create" function
  return Response(
    res: 0,
    responseType: rtError,
    status: 0,
    headers: newHeaders(hgImmutable),
    bodyUsed: true
  )

func sok(response: Response): bool {.jsfget: "ok".} =
  return response.status in 200u16 .. 299u16

func surl*(response: Response): string {.jsfget: "url".} =
  if response.responseType == rtError or response.url == nil:
    return ""
  return $response.url

#TODO: this should be a property of body
proc close*(response: Response) {.jsfunc.} =
  response.bodyUsed = true
  if response.unregisterFun != nil:
    response.unregisterFun()
    response.unregisterFun = nil
  if response.body != nil:
    response.body.sclose()
    response.body = nil

func getCharset*(this: Response; fallback: Charset): Charset =
  this.headers.table.withValue("Content-Type", p):
    let header = p[][0].toLowerAscii()
    let cs = header.getContentTypeAttr("charset").getCharset()
    if cs != CHARSET_UNKNOWN:
      return cs
  return fallback

func getContentType*(this: Response; fallback = "application/octet-stream"):
    string =
  this.headers.table.withValue("Content-Type", p):
    return p[][0].untilLower(';').strip()
  # also use DefaultGuess for container, so that local mime.types cannot
  # override buffer mime.types
  return DefaultGuess.guessContentType(this.url.pathname, fallback)

func getContentLength*(this: Response): int64 =
  this.headers.table.withValue("Content-Length", p):
    for x in p[]:
      let u = parseUInt64(x.strip(), allowSign = false)
      if u.isSome and u.get <= uint64(int64.high):
        return int64(u.get)
  return -1

func getReferrerPolicy*(this: Response): Option[ReferrerPolicy] =
  this.headers.table.withValue("Referrer-Policy", p):
    return strictParseEnum[ReferrerPolicy](p[][0])

type TextOpaque = ref object of RootObj
  buf: string
  bodyRead: Promise[JSResult[string]]

const BufferSize = 4096

proc onReadText(response: Response) =
  let opaque = TextOpaque(response.opaque)
  while true:
    let olen = opaque.buf.len
    try:
      opaque.buf.setLen(olen + BufferSize)
      let n = response.body.recvData(addr opaque.buf[olen], BufferSize)
      opaque.buf.setLen(olen + n)
      if n == 0:
        break
    except ErrorAgain:
      opaque.buf.setLen(olen)
      break

proc onFinishText(response: Response; success: bool) =
  let opaque = TextOpaque(response.opaque)
  let bodyRead = opaque.bodyRead
  if success:
    let charset = response.getCharset(CHARSET_UTF_8)
    bodyRead.resolve(JSResult[string].ok(opaque.buf.decodeAll(charset)))
  else:
    let err = newTypeError("NetworkError when attempting to fetch resource")
    bodyRead.resolve(JSResult[string].err(err))

proc resume*(response: Response) =
  response.resumeFun(response.outputId)
  response.resumeFun = nil

proc text*(response: Response): Promise[JSResult[string]] {.jsfunc.} =
  if response.body == nil:
    let p = newPromise[JSResult[string]]()
    p.resolve(JSResult[string].ok(""))
    return p
  if response.bodyUsed:
    let p = newPromise[JSResult[string]]()
    let err = JSResult[string]
      .err(newTypeError("Body has already been consumed"))
    p.resolve(err)
    return p
  let opaque = TextOpaque(bodyRead: newPromise[JSResult[string]]())
  response.opaque = opaque
  response.onRead = onReadText
  response.onFinish = onFinishText
  response.bodyUsed = true
  response.resume()
  return opaque.bodyRead

type BlobOpaque = ref object of RootObj
  p: pointer
  len: int
  size: int
  bodyRead: Promise[JSResult[Blob]]
  contentType: string

proc onReadBlob(response: Response) =
  let opaque = BlobOpaque(response.opaque)
  while true:
    try:
      let targetLen = opaque.len + BufferSize
      if targetLen > opaque.size:
        opaque.size = targetLen
        opaque.p = realloc(opaque.p, targetLen)
      let p = cast[ptr UncheckedArray[uint8]](opaque.p)
      let n = response.body.recvData(addr p[opaque.len], BufferSize)
      opaque.len += n
      if n == 0:
        break
    except ErrorAgain:
      break

proc onFinishBlob(response: Response; success: bool) =
  let opaque = BlobOpaque(response.opaque)
  let bodyRead = opaque.bodyRead
  if success:
    let p = realloc(opaque.p, opaque.len)
    opaque.p = nil
    let blob = if p == nil:
      newBlob(nil, 0, opaque.contentType, nil)
    else:
      newBlob(p, opaque.len, opaque.contentType, deallocBlob)
    bodyRead.resolve(JSResult[Blob].ok(blob))
  else:
    if opaque.p != nil:
      dealloc(opaque.p)
      opaque.p = nil
    let res = newTypeError("Error reading response")
    bodyRead.resolve(JSResult[Blob].err(res))

proc blob*(response: Response): Promise[JSResult[Blob]] {.jsfunc.} =
  if response.bodyUsed:
    let p = newPromise[JSResult[Blob]]()
    let err = JSResult[Blob].err(newTypeError("Body has already been consumed"))
    p.resolve(err)
    return p
  let opaque = BlobOpaque(
    bodyRead: newPromise[JSResult[Blob]](),
    contentType: response.getContentType()
  )
  response.opaque = opaque
  response.onRead = onReadBlob
  response.onFinish = onFinishBlob
  response.bodyUsed = true
  response.resume()
  return opaque.bodyRead

type BitmapOpaque = ref object of RootObj
  bmp: Bitmap
  idx: int
  bodyRead: EmptyPromise

proc onReadBitmap(response: Response) =
  let opaque = BitmapOpaque(response.opaque)
  let bmp = opaque.bmp
  while true:
    try:
      let p = cast[ptr UncheckedArray[uint8]](addr bmp.px[0])
      let L = bmp.px.len * 4 - opaque.idx
      let n = response.body.recvData(addr p[opaque.idx], L)
      opaque.idx += n
      if n == 0:
        break
    except ErrorAgain:
      break

proc onFinishBitmap(response: Response; success: bool) =
  let opaque = BitmapOpaque(response.opaque)
  opaque.bodyRead.resolve()

proc saveToBitmap*(response: Response; bmp: Bitmap): EmptyPromise =
  assert not response.bodyUsed
  let opaque = BitmapOpaque(bmp: bmp, idx: 0, bodyRead: EmptyPromise())
  let size = bmp.width * bmp.height
  bmp.px = cast[seq[RGBAColorBE]](newSeqUninitialized[uint32](size))
  response.opaque = opaque
  if size > 0:
    response.onRead = onReadBitmap
    response.onFinish = onFinishBitmap
  else:
    response.unregisterFun()
    response.body.sclose()
    opaque.bodyRead.resolve()
  response.bodyUsed = true
  response.resume()
  return opaque.bodyRead

proc json(ctx: JSContext; this: Response): Promise[JSValue] {.jsfunc.} =
  return this.text().then(proc(s: JSResult[string]): JSValue =
    if s.isNone:
      return ctx.toJS(s.error)
    return JS_ParseJSON(ctx, cstring(s.get), csize_t(s.get.len),
      cstring"<input>")
  )

proc addResponseModule*(ctx: JSContext) =
  ctx.registerType(Response)