Example #1
0
func (d *Device) FilesAndFolders(storageId uint32, parentId uint32) (files []*File, err error) {
	file := C.LIBMTP_Get_Files_And_Folders(d.me(), C.uint32_t(storageId), C.uint32_t(parentId))
	for f := (*File)(file); f != nil; f = (*File)(f.next) {
		files = append(files, f)
	}
	return files, d.ErrorStack()
}
Example #2
0
// Set the volume of all channels of this sink to a factor of the maximum
// volume (0.0 <= v <= 1.0).  Factors greater than 1.0 will be accepted, but
// clipping or distortion may occur beyond that value.
//
func (self *Sink) SetVolume(factor float64) error {
	if self.Channels > 0 {
		operation := NewOperation(self.Client)
		newVolume := &C.pa_cvolume{}

		//  new volume is the (maximum number of normal volume steps * factor)
		newVolume = C.pa_cvolume_init(newVolume)
		newVolumeT := C.pa_volume_t(C.uint32_t(uint(float64(self.NumVolumeSteps) * factor)))

		//  prepare newVolume for its journey into PulseAudio
		C.pa_cvolume_set(newVolume, C.uint(self.Channels), newVolumeT)

		//  make the call
		operation.paOper = C.pa_context_set_sink_volume_by_index(C.pulse_get_context(), C.uint32_t(self.Index), newVolume, (C.pa_context_success_cb_t)(unsafe.Pointer(C.pulse_generic_success_callback)), unsafe.Pointer(operation))

		//  wait for the result, refresh, return any errors
		return operation.WaitSuccess(func(op *Operation) error {
			return self.Refresh()
		})
	} else {
		return fmt.Errorf("Cannot set volume on sink %d, no channels defined", self.Index)
	}

	return nil
}
Example #3
0
func Write(m message.Message) ([]byte, error) {
	var b C.buf_t
	m2 := C.messageNew()

	switch m1 := m.(type) {
	case *message.Setup:
		m2.mtype = C.Setup
		s := (*C.struct_Setup)(unsafe.Pointer(ptr(m2.u[:])))
		s.ver_min = C.uint32_t(m1.Versions.Min)
		s.ver_max = C.uint32_t(m1.Versions.Max)
		for i, x := range m1.PeerNaClPublicKey {
			s.PeerNaClPublicKey[i] = C.uchar(x)
		}
		s.mtu = C.uint64_t(m1.Mtu)
		s.sharedTokens = C.uint64_t(m1.SharedTokens)
	default:
		panic("not impl yet")
	}

	err := C.messageAppend(m2, &b)
	if err != C.ERR_OK {
		return nil, GoError(err)
	}

	out := C.GoBytes(unsafe.Pointer(b.buf), C.int(b.len))
	C.bufDealloc(&b)
	return out, nil
}
Example #4
0
func Wi_crop(im *Image, x int, y int, cols int, rows int) (int, error) {
	ret := int(C.wi_crop(im.im, C.uint32_t(x), C.uint32_t(y), C.uint32_t(cols), C.uint32_t(rows)))
	if ret == WI_FAILED {
		return ret, errors.New("C.wi_crop() failed!")
	}
	return ret, nil
}
Example #5
0
func diffOptionsToC(opts *DiffOptions) (copts *C.git_diff_options, notifyData *diffNotifyData) {
	cpathspec := C.git_strarray{}
	if opts != nil {
		notifyData = &diffNotifyData{
			Callback: opts.NotifyCallback,
		}
		if opts.Pathspec != nil {
			cpathspec.count = C.size_t(len(opts.Pathspec))
			cpathspec.strings = makeCStringsFromStrings(opts.Pathspec)
		}

		copts = &C.git_diff_options{
			version:           C.GIT_DIFF_OPTIONS_VERSION,
			flags:             C.uint32_t(opts.Flags),
			ignore_submodules: C.git_submodule_ignore_t(opts.IgnoreSubmodules),
			pathspec:          cpathspec,
			context_lines:     C.uint32_t(opts.ContextLines),
			interhunk_lines:   C.uint32_t(opts.InterhunkLines),
			id_abbrev:         C.uint16_t(opts.IdAbbrev),
			max_size:          C.git_off_t(opts.MaxSize),
			old_prefix:        C.CString(opts.OldPrefix),
			new_prefix:        C.CString(opts.NewPrefix),
		}

		if opts.NotifyCallback != nil {
			C._go_git_setup_diff_notify_callbacks(copts)
			copts.notify_payload = unsafe.Pointer(notifyData)
		}
	}
	return
}
Example #6
0
// This will need to be a bit more generic,
// but for testing this will work fine.
func (search *Search) GetSearcher() IndexReader {
	idxLocation := cb_newf(search.Location)
	search.lucySearcher = C.LucyIxSearcherNew(idxLocation)
	C.DECREF(idxLocation)
	return func(q string, field string, offset, limit uint) (uint, []string) {
		query := cb_new_from_utf8(q)
		getField := cb_newf(field)
		hits := C.LucyIxSearcherHits(search.lucySearcher, query, C.uint32_t(offset), C.uint32_t(limit), nil)
		totalNumHits := uint(C.LucyHitsTotal(hits))
		requestedNumHits := minUInt(limit, totalNumHits)
		results := make([]string, requestedNumHits)
		var hit *C.LucyHitDoc
		for i := uint(0); i < requestedNumHits; i++ {
			hit = C.LucyHitsNext(hits)
			if hit == nil {
				break
			}
			value_cb := C.LucyHitDocExtract(hit, getField, nil) // do i need to free this
			value := cb_ptr2char(value_cb)                      // do i need to free this
			results[i] = C.GoString(value)
			C.DECREF(hit)
		}
		C.DECREF(query)
		C.DECREF(getField)
		C.DECREF(hits)
		return totalNumHits, results
	}
}
Example #7
0
File: blame.go Project: wid/git2go
func (v *Repository) BlameFile(path string, opts *BlameOptions) (*Blame, error) {
	var blamePtr *C.git_blame

	var copts *C.git_blame_options
	if opts != nil {
		copts = &C.git_blame_options{
			version:              C.GIT_BLAME_OPTIONS_VERSION,
			flags:                C.uint32_t(opts.Flags),
			min_match_characters: C.uint16_t(opts.MinMatchCharacters),
			min_line:             C.uint32_t(opts.MinLine),
			max_line:             C.uint32_t(opts.MaxLine),
		}
		if opts.NewestCommit != nil {
			copts.newest_commit = *opts.NewestCommit.toC()
		}
		if opts.OldestCommit != nil {
			copts.oldest_commit = *opts.OldestCommit.toC()
		}
	}

	cpath := C.CString(path)
	defer C.free(unsafe.Pointer(cpath))

	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	ecode := C.git_blame_file(&blamePtr, v.ptr, cpath, copts)
	if ecode < 0 {
		return nil, MakeGitError(ecode)
	}

	return newBlameFromC(blamePtr), nil
}
Example #8
0
// Return true if the file header contains instrument information for the file. false otherwise.
func (f *File) SetInstrument(i *Instrument) bool {
	c := new(C.SF_INSTRUMENT)
	c.gain = C.int(i.Gain)
	c.basenote = C.char(i.Basenote)
	c.detune = C.char(i.Detune)
	c.velocity_lo = C.char(i.Velocity[0])
	c.velocity_hi = C.char(i.Velocity[1])
	c.key_lo = C.char(i.Key[0])
	c.key_hi = C.char(i.Key[1])
	c.loop_count = C.int(i.LoopCount)
	var index int
	for ; index < i.LoopCount; index++ {
		c.loops[index].mode = C.int(i.Loops[index].Mode)
		c.loops[index].start = C.uint32_t(i.Loops[index].Start)
		c.loops[index].end = C.uint32_t(i.Loops[index].End)
		c.loops[index].count = C.uint32_t(i.Loops[index].Count)
	}
	for ; index < 16; index++ {
		c.loops[index].mode = C.int(None)
		// why is this necessary? libsndfile doesn't check loopcount for AIFF
	}

	r := C.sf_command(f.s, C.SFC_SET_INSTRUMENT, unsafe.Pointer(c), C.int(unsafe.Sizeof(*c)))
	return (r == C.SF_TRUE)
}
Example #9
0
// Set the volume of all channels of this source to a factor of the maximum
// volume (0.0 <= v <= 1.0).  Factors greater than 1.0 will be accepted, but
// clipping or distortion may occur beyond that value.
//
func (self *Source) SetVolume(factor float64) error {
	if self.Channels > 0 {
		operation := NewOperation(self.Client)
		defer operation.Destroy()
		newVolume := &C.pa_cvolume{}

		//  new volume is the (maximum number of normal volume steps * factor)
		newVolume = C.pa_cvolume_init(newVolume)
		newVolumeT := C.pa_volume_t(C.uint32_t(uint(float64(self.NumVolumeSteps) * factor)))

		//  prepare newVolume for its journey into PulseAudio
		C.pa_cvolume_set(newVolume, C.uint(self.Channels), newVolumeT)

		//  make the call
		operation.paOper = C.pa_context_set_source_volume_by_index(self.Client.context, C.uint32_t(self.Index), newVolume, (C.pa_context_success_cb_t)(C.pulse_generic_success_callback), operation.ToUserdata())

		//  wait for the result, refresh, return any errors
		if err := operation.Wait(); err == nil {
			return self.Refresh()
		} else {
			return err
		}
	} else {
		return fmt.Errorf("Cannot set volume on source %d, no channels defined", self.Index)
	}

	return nil
}
Example #10
0
func newUser(ptr *C.AB_USER) User {
	user := User{}
	user.ID = int(C.AB_User_GetUniqueId(ptr))

	user.UserID = C.GoString(C.AB_User_GetUserId(ptr))
	user.CustomerID = C.GoString(C.AB_User_GetCustomerId(ptr))
	user.Name = C.GoString(C.AB_User_GetUserName(ptr))
	user.BankCode = C.GoString(C.AB_User_GetBankCode(ptr))

	url := C.AH_User_GetServerUrl(ptr)
	if url != nil {
		tbuf := C.GWEN_Buffer_new(
			nil,
			C.uint32_t(256),
			C.uint32_t(0),
			C.int(1),
		)
		C.GWEN_Url_toString(url, tbuf)
		user.ServerURI = C.GoString(C.GWEN_Buffer_GetStart(tbuf))
		C.GWEN_Buffer_free(tbuf)
	}

	user.HbciVersion = int(C.AH_User_GetHbciVersion(ptr))

	user.ptr = ptr
	return user
}
Example #11
0
func (usm *USM) Read(user *C.snmp_user_t) SnmpError {
	usm.auth_proto = AuthType(user.auth_proto)
	usm.priv_proto = PrivType(user.priv_proto)
	usm.name = readGoString(&user.sec_name[0], SNMP_ADM_STR32_LEN)
	usm.localization_auth_key = readGoBytes(&user.auth_key[0], C.uint32_t(user.auth_len))
	usm.localization_priv_key = readGoBytes(&user.priv_key[0], C.uint32_t(user.priv_len))
	return nil
}
Example #12
0
func (g *Geometry) c() *C.struct_wlc_geometry {
	return C.init_geometry(
		C.int32_t(g.Origin.X),
		C.int32_t(g.Origin.Y),
		C.uint32_t(g.Size.W),
		C.uint32_t(g.Size.H),
	)
}
func (this ModbusRTUConnection) SetTimeout(timeout time.Duration) error {
	var sec C.uint32_t = C.uint32_t(timeout / time.Second)
	var usec C.uint32_t = C.uint32_t((timeout - time.Duration(sec)) / time.Microsecond)
	if C.modbus_set_response_timeout(this.ctx, sec, usec) == -1 {
		return errors.New("Invalid timeout value")
	}
	return nil
}
Example #14
0
/*
New to create a memcached client:

servers: is a list of memcached server addresses. Each address can be
in format of hostname[:port] [alias]. port and alias are optional.
If port is not given, default port 11211 will be used. alias will be
used to compute server hash if given, otherwise server hash will be
computed based on host and port (i.e.: If port is not given or it is
equal to 11211, host will be used to compute server hash.
If port is not equal to 11211, host:port will be used).

noreply: whether to enable memcached's noreply behaviour.
default: False

prefix: The key prefix. default: ''

hashFunc: hashing function for keys. possible values:
HashMD5, HashFNV1_32, HashFNV1a32, HashCRC32
NOTE: fnv1_32, fnv1a_32, crc_32 implementations
in libmc are per each spec, but they're not compatible
with corresponding implementions in libmemcached.
NOTE: The hashing algorithm for host mapping on continuum is always md5.

failover: Whether to failover to next server when current server is
not available. default: False

disableLock: Whether to disable a lock of type sync.Mutex which will be
use in every retrieval/storage command. default False.
*/
func New(servers []string, noreply bool, prefix string, hashFunc int, failover bool, disableLock bool) (client *Client) {
	client = new(Client)
	client._imp = C.client_create()
	runtime.SetFinalizer(client, finalizer)

	n := len(servers)
	cHosts := make([]*C.char, n)
	cPorts := make([]C.uint32_t, n)
	cAliases := make([]*C.char, n)

	for i, srv := range servers {
		addrAndAlias := strings.Split(srv, " ")

		addr := addrAndAlias[0]
		if len(addrAndAlias) == 2 {
			cAlias := C.CString(addrAndAlias[1])
			defer C.free(unsafe.Pointer(cAlias))
			cAliases[i] = cAlias
		}

		hostAndPort := strings.Split(addr, ":")
		host := hostAndPort[0]
		cHost := C.CString(host)
		defer C.free(unsafe.Pointer(cHost))
		cHosts[i] = cHost

		if len(hostAndPort) == 2 {
			port, err := strconv.Atoi(hostAndPort[1])
			if err != nil {
				return nil
			}
			cPorts[i] = C.uint32_t(port)
		} else {
			cPorts[i] = C.uint32_t(DefaultPort)
		}
	}

	failoverInt := 0
	if failover {
		failoverInt = 1
	}

	C.client_init(
		client._imp,
		(**C.char)(unsafe.Pointer(&cHosts[0])),
		(*C.uint32_t)(unsafe.Pointer(&cPorts[0])),
		C.size_t(n),
		(**C.char)(unsafe.Pointer(&cAliases[0])),
		C.int(failoverInt),
	)

	client.configHashFunction(int(hashFunctionMapping[hashFunc]))
	client.servers = servers
	client.prefix = prefix
	client.noreply = noreply
	client.disableLock = disableLock
	return
}
Example #15
0
func DebugTextPrintf(x, y int, attr uint8, format string, args ...interface{}) {
	text := []byte(fmt.Sprintf(format+"\x00", args...))
	C.bgfx_dbg_text_print(
		C.uint32_t(x),
		C.uint32_t(y),
		C.uint8_t(attr),
		(*C.char)(unsafe.Pointer(&text[0])),
	)
}
Example #16
0
// KeyboardGetUtf32ForKey is an utility function to convert raw keycode to
// Unicdoe/UTF-32 codepoint. Passed modifiers may transform the key.
func KeyboardGetUtf32ForKey(key uint32, mods *Modifiers) uint32 {
	if mods != nil {
		cmods := mods.c()
		defer C.free(unsafe.Pointer(cmods))
		return uint32(C.wlc_keyboard_get_utf32_for_key(C.uint32_t(key), cmods))
	}

	return uint32(C.wlc_keyboard_get_utf32_for_key(C.uint32_t(key), nil))
}
Example #17
0
func (s *SimpleIMP) Search(query string, offset, numWanted int) (totalHits int, err error) {
	err = clownfish.TrapErr(func() {
		self := (*C.lucy_Simple)(clownfish.Unwrap(s, "s"))
		qStringC := (*C.cfish_String)(clownfish.GoToClownfish(query, unsafe.Pointer(C.CFISH_STRING), false))
		defer C.cfish_decref(unsafe.Pointer(qStringC))
		totalHits = int(C.LUCY_Simple_Search(self, qStringC, C.uint32_t(offset), C.uint32_t(numWanted)))
	})
	return totalHits, err
}
Example #18
0
// ReadAsync reads samples asynchronously. Note, this function
// will block until canceled using CancelAsync. ReadAsyncCbT is
// a package global variable and therefore unsafe for use with
// multiple dongles.
//
// Note, please use ReadAsync2 as this method will be deprecated
// in the future.
//
// Optional bufNum buffer count, bufNum * bufLen = overall buffer size,
// set to 0 for default buffer count (32).
// Optional bufLen buffer length, must be multiple of 512, set to 0 for
// default buffer length (16 * 32 * 512).
func (dev *Context) ReadAsync(f ReadAsyncCbT, _ *UserCtx, bufNum, bufLen int) error {
	clientCb = f
	i := int(C.rtlsdr_read_async((*C.rtlsdr_dev_t)(dev),
		(C.rtlsdr_read_async_cb_t)(C.get_go_cb()),
		nil, // userctx *UserCtx
		C.uint32_t(bufNum),
		C.uint32_t(bufLen)))
	return libError(i)
}
Example #19
0
File: x86.go Project: 4577/unicorn
func (u *uc) RegWriteMmr(reg int, value *X86Mmr) error {
	var val C.uc_x86_mmr
	val.selector = C.uint16_t(value.Selector)
	val.base = C.uint64_t(value.Base)
	val.limit = C.uint32_t(value.Limit)
	val.flags = C.uint32_t(value.Flags)
	ucerr := C.uc_reg_write(u.handle, C.int(reg), unsafe.Pointer(&val))
	return errReturn(ucerr)
}
Example #20
0
// Read samples from the device asynchronously. This function will block until
// it is being canceled using rtlsdr_cancel_async()
//
// Optional buf_num buffer count, buf_num * buf_len = overall buffer size,
// set to 0 for default buffer count (32).
// Optional buf_len buffer length, must be multiple of 512, set to 0 for
// default buffer length (16 * 32 * 512).
//
// int rtlsdr_read_async(rtlsdr_dev_t *dev, rtlsdr_read_async_cb_t cb, void *ctx, uint32_t buf_num, uint32_t buf_len);
// rtlsdr_read_async returns 0 on success
func (c *Context) ReadAsync(f ReadAsyncCb_T, userctx *UserCtx, buf_num,
	buf_len int) (err int) {
	clientCb = f
	err = int(C.rtlsdr_read_async((*C.rtlsdr_dev_t)(c.dev),
		(C.rtlsdr_read_async_cb_t)(C.get_go_cb()),
		unsafe.Pointer(userctx),
		C.uint32_t(buf_num),
		C.uint32_t(buf_len)))
	return
}
Example #21
0
func (c *CGoSystem) CreateDataPipe(flags, elementNumBytes, capacityNumBytes uint32) (result uint32, producerHandle, consumerHandle uint32) {
	var opts *C.struct_MojoCreateDataPipeOptions
	opts = &C.struct_MojoCreateDataPipeOptions{
		C.uint32_t(unsafe.Sizeof(*opts)),
		C.MojoCreateDataPipeOptionsFlags(flags),
		C.uint32_t(elementNumBytes),
		C.uint32_t(capacityNumBytes),
	}
	return createDataPipeWithCOptions(opts)
}
Example #22
0
func (d *Device) CreateFolder(parent uint32, name string, storage uint32) (uint32, error) {
	cname := C.CString(name)
	id := C.LIBMTP_Create_Folder(d.me(), cname, C.uint32_t(parent), C.uint32_t(storage))

	if newName := C.GoString(cname); newName != name {
		log.Println("Folder name changed to %q", newName)
	}
	C.free(unsafe.Pointer(cname))
	return uint32(id), d.ErrorStack()
}
Example #23
0
func (mgr *Gpio) Set(states uint32, mask uint32) {
	val := states & mask
	if val != 0 {
		C.range_set_u32(mgr.hdl, gpioOffSet, C.uint32_t(val))
	}
	val = ^states & mask
	if val != 0 {
		C.range_set_u32(mgr.hdl, gpioOffClear, C.uint32_t(val))
	}
}
Example #24
0
func CreateTexture(data []byte, flags TextureFlags, skip uint8) (Texture, TextureInfo) {
	var ti C.bgfx_texture_info_t
	h := C.bgfx_create_texture(
		C.bgfx_copy(unsafe.Pointer(&data[0]), C.uint32_t(len(data))),
		C.uint32_t(flags),
		C.uint8_t(skip),
		&ti,
	)
	return Texture{h: h}, newTextureInfo(ti)
}
Example #25
0
// Mean accepts a location and returns the mean of the non-nil values in that range.
func (bw *BigWig) Mean(chrom string, start int, end int) float64 {
	cchrom := C.CString(chrom)
	defer C.free(unsafe.Pointer(cchrom))
	// C.int32(1) tells it to use 1 bin
	res := C.bwStats(bw.bw, cchrom, C.uint32_t(start), C.uint32_t(end), C.uint32_t(1), C.mean)
	tmp := (*[1]C.double)(unsafe.Pointer(res))
	v := float64(tmp[0])
	C.free(unsafe.Pointer(res))
	return v
}
Example #26
0
// VImageConvolve_ARGB8888 convolves a region of interest within a source image by an M x N kernel, then divides the pixel values by a divisor.
func VImageConvolve_ARGB8888(src, dst *VImageBuffer, tempBuffer []byte, roiX, roiY int, kernel []int16, kernelHeight, kernelWidth, divisor int, backgroundColor [4]uint8, flags VImageFlag) error {
	var tmpBuf unsafe.Pointer
	if tempBuffer != nil {
		tmpBuf = unsafe.Pointer(&tempBuffer[0])
	}
	srcC := src.toC()
	dstC := dst.toC()
	return toError(C.vImageConvolve_ARGB8888(&srcC, &dstC, tmpBuf, C.vImagePixelCount(roiX),
		C.vImagePixelCount(roiY), (*C.int16_t)(&kernel[0]), C.uint32_t(kernelHeight),
		C.uint32_t(kernelWidth), C.int32_t(divisor), (*C.uint8_t)(&backgroundColor[0]), C.vImage_Flags(flags)))
}
Example #27
0
func NewI32Array(nums []int32) I32Array {
	size := len(nums)
	if int(C.uint32_t(size)) != size {
		panic(clownfish.NewErr("input too large"))
	}
	obj := C.lucy_I32Arr_new_blank(C.uint32_t(size))
	for i := 0; i < size; i++ {
		C.LUCY_I32Arr_Set(obj, C.uint32_t(i), C.int32_t(nums[i]))
	}
	return WRAPI32Array(unsafe.Pointer(obj))
}
Example #28
0
func myPostingLast(data []byte, count uint32, fileid uint32) (int, uint32) {
	var dataptr *C.uint8_t
	if count > 0 {
		dataptr = (*C.uint8_t)(&data[0])
	}
	var totalbytes uint32
	last := int(C.cPostingLast(dataptr,
		C.uint32_t(count),
		C.uint32_t(fileid),
		(*C.uint32_t)(&totalbytes)))
	return last, totalbytes
}
Example #29
0
func GetAllJoynObjects(objects []*AllJoynBindingInfo) unsafe.Pointer {
	array := C.Allocate_AJ_Object_Array(C.uint32_t(len(objects) + 1))
	for i, object := range objects {
		interfaces = ParseAllJoynInterfaces(object.introspectData.Interfaces)
		flags := getAllJoynObjectFlags(object)
		log.Printf("Creating Object %s %u", object.introspectData.Name, flags)
		C.Create_AJ_Object(C.uint32_t(i), array, C.CString(object.introspectData.Name), &interfaces[0], flags, unsafe.Pointer(nil))
		C.Create_AJ_Object(C.uint32_t(i+1), array, nil, nil, 0, nil)
		// log.Printf("*****Alljoyn Objects %s %s", object.introspectData.Name, &interfaces[0])
	}
	return array
}
Example #30
0
// Convert a net.IPMask to an LWIP netmask.
func convert_IPMask_to_LWIP(netMask net.IPMask) *C.struct_ip_addr {
	// Golang actually uses IP the same internally as LWIP. But, since net.IP is a
	// possibly variable length buffer, we need to handle the case where we had to
	// stretch it to 16 bytes for the netmask.
	lwipNetmask := convert_IP_to_LWIP((net.IP)(netMask))
	if len(netMask) == net.IPv4len {
		lwipNetmask.addr[0] = C.uint32_t(^uint32(0))
		lwipNetmask.addr[1] = C.uint32_t(^uint32(0))
		lwipNetmask.addr[2] = C.uint32_t(^uint32(0))
	}
	return lwipNetmask
}